@pixerate/editor 0.97.0 → 0.99.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.
- package/THIRD_PARTY_NOTICES.md +4 -2
- package/dist/animation-editor/index.cjs +55 -53
- package/dist/animation-editor/index.cjs.map +1 -1
- package/dist/animation-editor/index.d.cts +3 -2
- package/dist/animation-editor/index.d.ts +3 -2
- package/dist/animation-editor/index.js +11 -9
- package/dist/animation-editor/index.js.map +1 -1
- package/dist/chunk-DWGZUSES.cjs +694 -0
- package/dist/chunk-DWGZUSES.cjs.map +1 -0
- package/dist/chunk-GX332W2C.js +181 -0
- package/dist/chunk-GX332W2C.js.map +1 -0
- package/dist/{chunk-7MD7C6XQ.cjs → chunk-JF5PXN7W.cjs} +96 -744
- package/dist/chunk-JF5PXN7W.cjs.map +1 -0
- package/dist/chunk-KKREERP2.js +694 -0
- package/dist/chunk-KKREERP2.js.map +1 -0
- package/dist/chunk-MUUXNRU4.cjs +181 -0
- package/dist/chunk-MUUXNRU4.cjs.map +1 -0
- package/dist/{chunk-OEVSVA6V.js → chunk-WIR377F6.js} +788 -22
- package/dist/chunk-WIR377F6.js.map +1 -0
- package/dist/{chunk-4AB5BHYK.cjs → chunk-WT6ZAWJP.cjs} +788 -22
- package/dist/chunk-WT6ZAWJP.cjs.map +1 -0
- package/dist/{chunk-4JLB2USO.js → chunk-YGZNGDIT.js} +45 -693
- package/dist/chunk-YGZNGDIT.js.map +1 -0
- package/dist/image-editor/index.cjs +1798 -333
- package/dist/image-editor/index.cjs.map +1 -1
- package/dist/image-editor/index.d.cts +482 -6
- package/dist/image-editor/index.d.ts +482 -6
- package/dist/image-editor/index.js +1488 -23
- package/dist/image-editor/index.js.map +1 -1
- package/dist/raster/index.cjs +23 -2
- package/dist/raster/index.cjs.map +1 -1
- package/dist/raster/index.d.cts +98 -2
- package/dist/raster/index.d.ts +98 -2
- package/dist/raster/index.js +23 -2
- package/dist/{svg-ymShkNtu.d.cts → svg-C9r284x8.d.cts} +6 -9
- package/dist/{svg-Dh17jCyA.d.ts → svg-MVKBqwD4.d.ts} +6 -9
- package/dist/types-CwMPoRMU.d.cts +40 -0
- package/dist/types-CwMPoRMU.d.ts +40 -0
- package/dist/vector/index.cjs +490 -554
- package/dist/vector/index.cjs.map +1 -1
- package/dist/vector/index.d.cts +154 -292
- package/dist/vector/index.d.ts +154 -292
- package/dist/vector/index.js +91 -155
- package/dist/vector/index.js.map +1 -1
- package/dist/warp-B8rAguzs.d.ts +165 -0
- package/dist/warp-nYs2DPrx.d.cts +165 -0
- package/package.json +1 -1
- package/skills/pixerate-image-editor/SKILL.md +49 -3
- package/dist/chunk-4AB5BHYK.cjs.map +0 -1
- package/dist/chunk-4JLB2USO.js.map +0 -1
- package/dist/chunk-7MD7C6XQ.cjs.map +0 -1
- package/dist/chunk-OEVSVA6V.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/vector/index.cjs","../../src/vector/gradientTool.ts","../../src/vector/blendGroup.ts","../../src/vector/perspective.ts","../../src/vector/distort.ts","../../src/vector/snap.ts","../../src/vector/pathEdit.ts","../../src/vector/pathCut.ts","../../src/vector/ink.ts","../../src/vector/builder.ts","../../src/vector/controller.ts","../../src/vector/render.ts","../../src/vector/commands.ts"],"names":["lines","near","fi","r","corners","key","node","fmt","list"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACA;AC5QO,IAAM,yBAAA,EAA2B,EAAA;AACjC,IAAM,6B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ACsE,MAAA;AAC1B,QAAA;AAC3B,QAAA;AACJ,QAAA;AACvB,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACU,MAAA;AACN,MAAA;AACiC,MAAA;AAEvC,MAAA;AAC+C,MAAA;AACtC,MAAA;AACqF,MAAA;AACzC,QAAA;AAC3B,QAAA;AACsB,QAAA;AACjD,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACU,MAAA;AACN,MAAA;AACuC,MAAA;AAE7C,MAAA;AACO,MAAA;AACD,QAAA;AACM,QAAA;AAC0B,UAAA;AACH,UAAA;AACa,UAAA;AACZ,UAAA;AACe,UAAA;AACF,UAAA;AACjD,QAAA;AACD,MAAA;AACqE,MAAA;AAC5B,QAAA;AACA,QAAA;AACb,QAAA;AACqB,QAAA;AACjD,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACU,MAAA;AACN,MAAA;AAC4C,MAAA;AACtC,MAAA;AACyC,MAAA;AACA,MAAA;AACvB,QAAA;AACH,QAAA;AAC5B,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACU,MAAA;AACN,MAAA;AACG,MAAA;AAC6B,MAAA;AAC1B,MAAA;AACwC,MAAA;AAC0C,MAAA;AAChG,IAAA;AACA,IAAA;AACI,MAAA;AACU,MAAA;AACN,MAAA;AACqC,MAAA;AAC/B,MAAA;AACwC,MAAA;AAC3C,MAAA;AAC0D,MAAA;AACf,QAAA;AACC,QAAA;AACtD,MAAA;AACD,IAAA;AACD,EAAA;AACD;AZ+qP6D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/vector/index.cjs","sourcesContent":[null,"/**\n * The Gradient tool's on-canvas annotator: a bar from the start (or centre) handle to the end (or\n * radius) handle with the colour stops under it and midpoint diamonds above it, plus a radial,\n * conic or diamond gradient's extent outline, aspect handle and (radial) focal point. All in\n * screen pixels, for hit-testing and the overlay.\n *\n * After vectorcraft `crates/tools/src/xform/gradient.rs` (`Annotator`: stop chips below the bar,\n * midpoints above it, a stop dragged off the bar is removed, a click on the bar adds one), ArtCraft,\n * MIT OR Apache-2.0 — see THIRD_PARTY_NOTICES.md.\n */\nimport { collectPathNodes, findVectorNode, vectorWorldMatrix, IDENTITY_MATRIX, multiplyMatrices, type AffineMatrix } from './geometry.js';\nimport { vectorPathLocalBounds } from './svg.js';\nimport {\n\tisCentredVectorGradient,\n\tisVectorGradient,\n\tsortedVectorGradientStops,\n\tvectorGradientHandles,\n\tvectorGradientMatrix,\n\tvectorGradientMidpointPosition,\n\ttype VectorGradientHandle\n} from './gradient.js';\nimport type { Vec2, VectorBounds, VectorDocument, VectorGradient, VectorGradientStop, VectorPathNode, VectorViewport } from './types.js';\n\n/** Which paint of the selection the Gradient tool and the gradient editor work on. */\nexport type VectorGradientTarget = 'fill' | 'stroke';\n\n/** A part of the annotator under the pointer. */\nexport type VectorGradientPart =\n\t| { kind: 'handle'; handle: VectorGradientHandle }\n\t| { kind: 'stop'; index: number }\n\t| { kind: 'midpoint'; index: number }\n\t/** The bar at `offset` (0–1): a click adds a stop there, a drag moves the gradient. */\n\t| { kind: 'bar'; offset: number };\n\n/** Distance of the stop chips below the bar, the midpoint diamonds above it (screen pixels). */\nexport const VECTOR_GRADIENT_STOP_GAP = 12;\nexport const VECTOR_GRADIENT_MIDPOINT_GAP = 9;\n/** How far off the bar a dragged stop goes before it is removed (screen pixels). */\nexport const VECTOR_GRADIENT_OFF_BAR = 24;\nconst STOP_HIT = 6;\nconst MIDPOINT_HIT = 5;\nconst HANDLE_HIT = 6;\nconst BAR_HIT = 5;\n\nexport interface VectorGradientAnnotator {\n\tnodeId: string;\n\ttarget: VectorGradientTarget;\n\tgradient: VectorGradient;\n\t/** The path's box in its own space. */\n\tbounds: VectorBounds | null;\n\t/** The path's own space → document. */\n\tworld: AffineMatrix;\n\t/** Screen positions of the handles. */\n\tstart: Vec2;\n\tend: Vec2;\n\t/** Radial, conic and diamond gradients. */\n\taspect: Vec2 | null;\n\t/** Radial gradients. */\n\tfocal: Vec2 | null;\n\t/** Unit normal to the bar towards the stop chips (screen). */\n\tnormal: Vec2;\n\t/** Stops (sorted, as the gradient stores them) with their chips' screen positions. */\n\tstops: (VectorGradientStop & { index: number; x: number; y: number })[];\n\t/** The midpoint diamond after each stop but the last (screen). */\n\tmidpoints: { index: number; x: number; y: number; midpoint: number }[];\n\t/** Screen path of the extent: an ellipse (radial, conic) or a rhombus (diamond). */\n\textent: string | null;\n}\n\nconst fmt = (n: number) => Math.round(n * 100) / 100;\nconst apply = (m: AffineMatrix, p: Vec2): Vec2 => ({ x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] });\n\n/** The path whose `target` paint the annotator shows: the first path of the selection with a gradient there. */\nexport function vectorGradientTargetPath(doc: VectorDocument, selection: readonly string[], target: VectorGradientTarget): VectorPathNode | null {\n\tfor (const id of selection) {\n\t\tconst node = findVectorNode(doc.nodes, id);\n\t\tif (!node) continue;\n\t\tconst path = collectPathNodes(node).find((p) => isVectorGradient(p[target]));\n\t\tif (path) return path;\n\t}\n\treturn null;\n}\n\n/** The annotator of the selection's gradient (`target` paint), in screen pixels, or null when it has none. */\nexport function getVectorGradientAnnotator(\n\tdoc: VectorDocument,\n\tselection: readonly string[],\n\tviewport: VectorViewport,\n\ttarget: VectorGradientTarget\n): VectorGradientAnnotator | null {\n\tconst path = vectorGradientTargetPath(doc, selection, target);\n\tif (!path) return null;\n\tconst gradient = path[target] as VectorGradient;\n\tconst world = vectorWorldMatrix(doc.nodes, path.id) ?? IDENTITY_MATRIX;\n\tconst screen = multiplyMatrices(world, [viewport.zoom, 0, 0, viewport.zoom, viewport.x, viewport.y]);\n\tconst bounds = vectorPathLocalBounds(path);\n\tconst h = vectorGradientHandles(gradient, bounds, screen);\n\tconst v = { x: h.end.x - h.start.x, y: h.end.y - h.start.y };\n\tconst len = Math.hypot(v.x, v.y);\n\tconst normal = len > 1e-9 ? { x: -v.y / len, y: v.x / len } : { x: 0, y: 1 };\n\tconst at = (t: number, gap: number) => ({ x: h.start.x + v.x * t + normal.x * gap, y: h.start.y + v.y * t + normal.y * gap });\n\tconst sorted = sortedVectorGradientStops(gradient);\n\tconst stops = sorted.map((s, index) => ({ ...s, index, ...at(s.offset, VECTOR_GRADIENT_STOP_GAP) }));\n\tconst midpoints = sorted.slice(0, -1).flatMap((s, index) => {\n\t\tconst pos = vectorGradientMidpointPosition(sorted, index);\n\t\treturn pos === null || sorted[index + 1].offset - s.offset < 1e-6 ? [] : [{ index, midpoint: s.midpoint ?? 0.5, ...at(pos, -VECTOR_GRADIENT_MIDPOINT_GAP) }];\n\t});\n\tlet extent: string | null = null;\n\tif (isCentredVectorGradient(gradient.type)) {\n\t\tconst frame = multiplyMatrices(vectorGradientMatrix(gradient, bounds), screen);\n\t\tconst pts =\n\t\t\tgradient.type === 'diamond'\n\t\t\t\t? [{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }, { x: 0, y: -1 }]\n\t\t\t\t: Array.from({ length: 48 }, (_, k) => ({ x: Math.cos((k * Math.PI) / 24), y: Math.sin((k * Math.PI) / 24) }));\n\t\textent = `M${pts.map((p) => apply(frame, p)).map((p) => `${fmt(p.x)} ${fmt(p.y)}`).join('L')}Z`;\n\t}\n\treturn { nodeId: path.id, target, gradient, bounds, world, start: h.start, end: h.end, aspect: h.aspect, focal: h.focal, normal, stops, midpoints, extent };\n}\n\n/** Where `p` lies relative to the bar: offset along it (0 at the start, 1 at the end) and distance towards the stop chips. */\nexport function vectorGradientBarPosition(a: Pick<VectorGradientAnnotator, 'start' | 'end' | 'normal'>, p: Vec2): { offset: number; across: number } {\n\tconst v = { x: a.end.x - a.start.x, y: a.end.y - a.start.y };\n\tconst l2 = v.x * v.x + v.y * v.y;\n\tconst d = { x: p.x - a.start.x, y: p.y - a.start.y };\n\tif (l2 < 1e-12) return { offset: 0, across: Math.hypot(d.x, d.y) };\n\treturn { offset: (d.x * v.x + d.y * v.y) / l2, across: d.x * a.normal.x + d.y * a.normal.y };\n}\n\n/** The annotator part under screen point `p`: stops, then midpoints, the handles and the bar. */\nexport function hitVectorGradientAnnotator(a: VectorGradientAnnotator, p: Vec2): VectorGradientPart | null {\n\tconst near = (q: Vec2 | null, r: number) => !!q && Math.hypot(q.x - p.x, q.y - p.y) <= r;\n\tfor (let i = a.stops.length - 1; i >= 0; i--) if (near(a.stops[i], STOP_HIT)) return { kind: 'stop', index: a.stops[i].index };\n\tfor (const m of a.midpoints) if (near(m, MIDPOINT_HIT)) return { kind: 'midpoint', index: m.index };\n\tconst centred = isCentredVectorGradient(a.gradient.type);\n\tif (near(a.end, HANDLE_HIT)) return { kind: 'handle', handle: centred ? 'radius' : 'end' };\n\t// The focal point sits on the centre until moved: grab it with Alt there (see the controller).\n\tif (a.focal && near(a.focal, HANDLE_HIT) && !near(a.start, 1)) return { kind: 'handle', handle: 'focal' };\n\tif (near(a.start, HANDLE_HIT)) return { kind: 'handle', handle: 'start' };\n\tif (near(a.aspect, HANDLE_HIT)) return { kind: 'handle', handle: 'aspect' };\n\tconst { offset, across } = vectorGradientBarPosition(a, p);\n\tif (offset >= 0 && offset <= 1 && across >= -BAR_HIT && across <= VECTOR_GRADIENT_STOP_GAP + STOP_HIT) return { kind: 'bar', offset };\n\treturn null;\n}\n","// Portions ported from vectorcraft-main/crates/doc/src/blend.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\n/**\n * Live blend groups: a group whose `blend` is set keeps its key shapes as children and\n * regenerates the in-betweens (`blendStep` children, locked) whenever a key or the options\n * change. Steps follow the straight lines between the keys' centres, or a replaced spine.\n *\n * - **Spacing** (`vectorBlendStepCount`): a number of steps per pair of keys, a fixed distance\n * along the spine, or smooth colour — one step per two levels of the largest colour channel\n * difference, by distance when the colours match.\n * - **Spine**: with a replaced spine the keys sit along it, spread evenly by arc length; each\n * step is moved by how far the spine bends away from the chord between its keys, so a step\n * lands on the spine and the keys stay where they are. Orient to spine also turns the steps\n * by how much the spine's direction differs from the keys' (keys keep their orientation);\n * without a replaced spine the steps run straight and keep their orientation.\n */\nimport type { Point } from '../canvas/types.js';\nimport { hexToRgba } from '../tokens/color.js';\nimport { segmentPoint, segmentTangent } from '../canvas/pathops/bezier.js';\nimport { createVectorMorph, type VectorMorph } from './blend.js';\nimport {\n\tcollectPathNodes,\n\tIDENTITY_MATRIX,\n\trotateMatrix,\n\tsubpathSegment,\n\tsubpathSegmentCount,\n\ttransformVectorNode,\n\ttranslateMatrix,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\tvectorNodeBounds,\n\ttype AffineMatrix\n} from './geometry.js';\nimport type { VectorBlend, VectorBlendOptions, VectorGroupNode, VectorNode, VectorPaint, VectorPathNode, VectorSubpath } from './types.js';\n\nexport const DEFAULT_VECTOR_BLEND_STEPS = 5;\nexport const DEFAULT_VECTOR_BLEND_DISTANCE = 20;\n/** Most steps between two keys. */\nexport const VECTOR_BLEND_MAX_STEPS = 1000;\n/** Most steps smooth colour makes between two keys. */\nexport const VECTOR_BLEND_MAX_SMOOTH_STEPS = 256;\n\n/** Whether a node is a live blend group. */\nexport function isVectorBlendGroup(node: VectorNode | null | undefined): node is VectorGroupNode & { blend: VectorBlend } {\n\treturn !!node && node.type === 'group' && !!node.blend;\n}\n\n/** The keys of a blend group (its children that are not generated steps), in stacking order. */\nexport function vectorBlendKeys(group: VectorGroupNode): VectorNode[] {\n\treturn group.children.filter((c) => !c.blendStep);\n}\n\n/** The full options of a blend, defaults filled in. */\nexport function resolveVectorBlendOptions(options: VectorBlendOptions | null | undefined): Required<VectorBlendOptions> {\n\treturn {\n\t\tspacing: options?.spacing ?? 'steps',\n\t\tsteps: options?.steps ?? DEFAULT_VECTOR_BLEND_STEPS,\n\t\tdistance: options?.distance ?? DEFAULT_VECTOR_BLEND_DISTANCE,\n\t\torientToSpine: options?.orientToSpine ?? false,\n\t\tlinear: options?.linear ?? false\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Step counts\n// ---------------------------------------------------------------------------\n\nfunction paintColors(p: VectorPaint | undefined): string[] {\n\tif (typeof p === 'string') return [p];\n\tif (p && typeof p === 'object') return p.stops.map((s) => s.color);\n\treturn [];\n}\n\n/** Largest channel difference (0–1) between the colours of two shapes' fills and strokes. */\nexport function vectorBlendColorDistance(a: VectorNode, b: VectorNode): number {\n\tconst pa = collectPathNodes(a)[0];\n\tconst pb = collectPathNodes(b)[0];\n\tif (!pa || !pb) return 0;\n\tlet d = 0;\n\tfor (const key of ['fill', 'stroke'] as const) {\n\t\tconst ca = paintColors(pa[key]);\n\t\tconst cb = paintColors(pb[key]);\n\t\tca.forEach((c, i) => {\n\t\t\tconst other = cb[i] ?? cb[0];\n\t\t\tif (other === undefined) return;\n\t\t\tconst x = hexToRgba(c);\n\t\t\tconst y = hexToRgba(other);\n\t\t\tif (!x || !y) return;\n\t\t\td = Math.max(d, Math.abs(x.r - y.r), Math.abs(x.g - y.g), Math.abs(x.b - y.b), Math.abs(x.a - y.a));\n\t\t});\n\t}\n\treturn d;\n}\n\nconst centreOf = (n: VectorNode): Point => {\n\tconst b = vectorNodeBounds(n);\n\treturn b ? [b.x + b.width / 2, b.y + b.height / 2] : [0, 0];\n};\n\n/** Number of in-betweens between two keys `length` apart along the spine. */\nexport function vectorBlendStepCount(a: VectorNode, b: VectorNode, options: VectorBlendOptions | null | undefined, length: number): number {\n\tconst o = resolveVectorBlendOptions(options);\n\tif (o.spacing === 'distance') {\n\t\tconst d = Math.max(0.01, o.distance);\n\t\treturn Math.min(VECTOR_BLEND_MAX_STEPS, Math.max(0, Math.round(length / d) - 1));\n\t}\n\tif (o.spacing === 'smoothColor') {\n\t\tconst cd = vectorBlendColorDistance(a, b);\n\t\tif (cd > 1 / 255) return Math.min(VECTOR_BLEND_MAX_SMOOTH_STEPS, Math.max(1, Math.ceil((cd * 255) / 2)));\n\t\t// Same colours: base the count on how far the shapes are apart.\n\t\tconst ba = vectorNodeBounds(a);\n\t\tconst bb = vectorNodeBounds(b);\n\t\tconst dist =\n\t\t\tba && bb\n\t\t\t\t? Math.max(Math.abs(ba.x - bb.x), Math.abs(ba.y - bb.y), Math.abs(ba.x + ba.width - bb.x - bb.width), Math.abs(ba.y + ba.height - bb.y - bb.height))\n\t\t\t\t: length;\n\t\treturn Math.min(VECTOR_BLEND_MAX_SMOOTH_STEPS, Math.max(1, Math.ceil(dist / 2)));\n\t}\n\treturn Math.min(VECTOR_BLEND_MAX_STEPS, Math.max(1, Math.round(Number.isFinite(o.steps) ? o.steps : DEFAULT_VECTOR_BLEND_STEPS)));\n}\n\n// ---------------------------------------------------------------------------\n// Spine\n// ---------------------------------------------------------------------------\n\n/** A subpath flattened to a polyline with cumulative arc lengths and tangent angles. */\nexport interface VectorBlendRail {\n\tpts: Point[];\n\tcum: number[];\n\tangles: number[];\n\ttotal: number;\n\tclosed: boolean;\n}\n\n/** Flattens a spine subpath (32 samples per curve). Null with fewer than two distinct points. */\nexport function vectorBlendRail(sp: VectorSubpath): VectorBlendRail | null {\n\tconst pts: Point[] = [];\n\tconst angles: number[] = [];\n\tconst push = (p: Point, tangent: Point) => {\n\t\tconst last = pts[pts.length - 1];\n\t\tif (last && Math.hypot(p[0] - last[0], p[1] - last[1]) < 1e-9) return;\n\t\tpts.push(p);\n\t\tangles.push(Math.atan2(tangent[1], tangent[0]));\n\t};\n\tconst count = subpathSegmentCount(sp);\n\tfor (let i = 0; i < count; i++) {\n\t\tconst seg = subpathSegment(sp, i);\n\t\tconst samples = seg.length === 2 ? 1 : 32;\n\t\tif (i === 0) push(seg[0], segmentTangent(seg, 0));\n\t\tfor (let k = 1; k <= samples; k++) push(segmentPoint(seg, k / samples), segmentTangent(seg, k / samples));\n\t}\n\tif (pts.length < 2) return null;\n\tconst cum = [0];\n\tfor (let i = 1; i < pts.length; i++) cum.push(cum[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));\n\treturn { pts, cum, angles, total: cum[cum.length - 1], closed: sp.closed };\n}\n\n/** Point and direction (radians) at arc length `s` (clamped; a closed rail wraps). */\nexport function vectorBlendRailAt(rail: VectorBlendRail, s: number): { point: Point; angle: number } {\n\tlet len = Number.isFinite(s) ? s : 0;\n\tif (rail.closed && rail.total > 0) len = ((len % rail.total) + rail.total) % rail.total;\n\tlen = Math.min(rail.total, Math.max(0, len));\n\tlet lo = 0;\n\tlet hi = rail.cum.length - 1;\n\twhile (hi - lo > 1) {\n\t\tconst mid = (lo + hi) >> 1;\n\t\tif (rail.cum[mid] <= len) lo = mid;\n\t\telse hi = mid;\n\t}\n\tconst span = rail.cum[hi] - rail.cum[lo];\n\tconst u = span > 1e-12 ? (len - rail.cum[lo]) / span : 0;\n\tconst a = rail.pts[lo];\n\tconst b = rail.pts[hi];\n\treturn { point: [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u], angle: Math.atan2(b[1] - a[1], b[0] - a[0]) };\n}\n\n/**\n * The spine of a blend in the group's space and where along it each key sits: the replaced\n * spine (keys spread evenly by arc length) or the straight lines between the keys' centres.\n */\nexport function vectorBlendSpine(group: VectorGroupNode): { spine: VectorSubpath; rail: VectorBlendRail; stops: number[]; replaced: boolean } | null {\n\tconst keys = vectorBlendKeys(group);\n\tif (keys.length < 2) return null;\n\tconst stored = group.blend?.spine;\n\tif (stored && stored.anchors.length >= 2) {\n\t\tconst rail = vectorBlendRail(stored);\n\t\tif (rail) {\n\t\t\tconst end = rail.closed ? rail.total * (1 - 1 / keys.length) : rail.total;\n\t\t\treturn { spine: stored, rail, stops: keys.map((_, i) => (end * i) / (keys.length - 1)), replaced: true };\n\t\t}\n\t}\n\tconst centres = keys.map(centreOf);\n\tconst spine: VectorSubpath = { closed: false, anchors: centres.map((c) => ({ x: c[0], y: c[1] })) };\n\tconst stops = [0];\n\tfor (let i = 1; i < centres.length; i++) stops.push(stops[i - 1] + Math.hypot(centres[i][0] - centres[i - 1][0], centres[i][1] - centres[i - 1][1]));\n\tconst rail = vectorBlendRail(spine) ?? { pts: centres, cum: stops, angles: centres.map(() => 0), total: stops[stops.length - 1], closed: false };\n\treturn { spine, rail, stops, replaced: false };\n}\n\n/** Where key `i` of a blend with spine `spine` should sit: its stop on the spine. */\nexport function vectorBlendKeyTargets(group: VectorGroupNode): Point[] {\n\tconst s = vectorBlendSpine(group);\n\treturn s ? s.stops.map((stop) => vectorBlendRailAt(s.rail, stop).point) : [];\n}\n\n// ---------------------------------------------------------------------------\n// Generating steps\n// ---------------------------------------------------------------------------\n\nconst morphCache = new WeakMap<VectorNode, WeakMap<VectorNode, Map<string, VectorMorph>>>();\n\nfunction morphFor(a: VectorNode, b: VectorNode, blend: VectorBlend): VectorMorph {\n\tconst starts = [blend.starts?.[a.id] ?? null, blend.starts?.[b.id] ?? null] as const;\n\tconst key = JSON.stringify([!!blend.linear, starts]);\n\tlet inner = morphCache.get(a);\n\tif (!inner) morphCache.set(a, (inner = new WeakMap()));\n\tlet byKey = inner.get(b);\n\tif (!byKey) inner.set(b, (byKey = new Map()));\n\tlet morph = byKey.get(key);\n\tif (!morph) byKey.set(key, (morph = createVectorMorph(a, b, { linear: blend.linear, starts })));\n\treturn morph;\n}\n\nconst wrapAngle = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));\n\n/** A step marked as generated: locked, flagged, ids derived from `id`. */\nfunction asStep(node: VectorNode, id: string): VectorNode {\n\tconst rename = (n: VectorNode, nid: string): VectorNode =>\n\t\tn.type === 'group' ? { ...n, id: nid, children: n.children.map((c, i) => rename(c, `${nid}.${i}`)) } : { ...n, id: nid };\n\treturn { ...rename(node, id), blendStep: true, locked: true };\n}\n\n/**\n * A blend group's children with fresh steps: each key followed by the in-betweens to the next,\n * bottom to top. Groups with fewer than two keys keep just their keys.\n */\nexport function generateVectorBlendChildren(group: VectorGroupNode): VectorNode[] {\n\tconst keys = vectorBlendKeys(group);\n\tconst blend = group.blend;\n\tif (!blend || keys.length < 2) return keys;\n\tconst spine = vectorBlendSpine(group);\n\tif (!spine) return keys;\n\tconst out: VectorNode[] = [];\n\tlet counter = 0;\n\tkeys.forEach((a, i) => {\n\t\tout.push(a);\n\t\tconst b = keys[i + 1];\n\t\tif (!b) return;\n\t\tconst s0 = spine.stops[i];\n\t\tconst s1 = spine.stops[i + 1];\n\t\tconst n = vectorBlendStepCount(a, b, blend, Math.abs(s1 - s0));\n\t\tconst morph = morphFor(a, b, blend);\n\t\tconst p0 = vectorBlendRailAt(spine.rail, s0);\n\t\tconst p1 = vectorBlendRailAt(spine.rail, s1);\n\t\tfor (let j = 1; j <= n; j++) {\n\t\t\tconst t = j / (n + 1);\n\t\t\tlet step = morph.at(t);\n\t\t\tif (spine.replaced) {\n\t\t\t\tconst p = vectorBlendRailAt(spine.rail, s0 + (s1 - s0) * t);\n\t\t\t\tconst dx = p.point[0] - (p0.point[0] + (p1.point[0] - p0.point[0]) * t);\n\t\t\t\tconst dy = p.point[1] - (p0.point[1] + (p1.point[1] - p0.point[1]) * t);\n\t\t\t\tlet m: AffineMatrix = Math.hypot(dx, dy) > 1e-9 ? translateMatrix(dx, dy) : IDENTITY_MATRIX;\n\t\t\t\tif (blend.orientToSpine) {\n\t\t\t\t\tconst turn = wrapAngle(p.angle - (p0.angle + wrapAngle(p1.angle - p0.angle) * t));\n\t\t\t\t\tif (Math.abs(turn) > 1e-9) {\n\t\t\t\t\t\tconst c = centreOf(step);\n\t\t\t\t\t\tconst origin = { x: c[0] + m[4], y: c[1] + m[5] };\n\t\t\t\t\t\tm = multiplyMatrices(m, rotateMatrix((turn * 180) / Math.PI, origin));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (m !== IDENTITY_MATRIX) step = transformVectorNode(step, m);\n\t\t\t}\n\t\t\tout.push(asStep(step, `${group.id}~${++counter}`));\n\t\t}\n\t});\n\treturn out;\n}\n\nconst childrenCache = new WeakMap<VectorNode, { sig: string; keys: VectorNode[]; children: VectorNode[] }>();\n\nconst sameList = (a: readonly VectorNode[], b: readonly VectorNode[]) => a.length === b.length && a.every((n, i) => n === b[i]);\n\nfunction blendChildren(group: VectorGroupNode): VectorNode[] {\n\tconst keys = vectorBlendKeys(group);\n\tconst sig = `${group.id}|${JSON.stringify(group.blend)}`;\n\tconst cached = keys[0] ? childrenCache.get(keys[0]) : undefined;\n\tlet children: VectorNode[];\n\tif (cached && cached.sig === sig && sameList(cached.keys, keys)) children = cached.children;\n\telse {\n\t\tchildren = generateVectorBlendChildren(group);\n\t\tif (keys[0]) childrenCache.set(keys[0], { sig, keys, children });\n\t}\n\treturn sameList(children, group.children) ? group.children : children;\n}\n\n/**\n * Nodes with every blend group's steps brought up to date (nested blends first). Returns the\n * same array when nothing changed; steps are cached per set of keys, so calling this after\n * every edit is cheap.\n */\nexport function refreshVectorBlends(nodes: readonly VectorNode[]): VectorNode[] {\n\tlet changed = false;\n\tconst out = nodes.map((n) => {\n\t\tif (n.type !== 'group') return n;\n\t\tconst inner = refreshVectorBlends(n.children);\n\t\tlet next: VectorGroupNode = inner === n.children ? n : { ...n, children: inner };\n\t\tif (next.blend) {\n\t\t\tconst children = blendChildren(next);\n\t\t\tif (children !== next.children) next = { ...next, children };\n\t\t}\n\t\tif (next !== n) changed = true;\n\t\treturn next;\n\t});\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\n/** A step or key with the generated flags dropped and fresh ids. */\nfunction plain(node: VectorNode, newId: () => string): VectorNode {\n\tconst { blendStep: _s, locked: _l, ...rest } = node;\n\tconst renamed = { ...rest, id: newId() } as VectorNode;\n\tif (renamed.type === 'group') renamed.children = renamed.children.map((c) => plain(c, newId));\n\treturn renamed;\n}\n\n/** Expand: the blend as a plain group of its keys and steps (steps get fresh ids). */\nexport function expandVectorBlend(group: VectorGroupNode, newId: () => string): VectorGroupNode {\n\tconst { blend: _b, ...rest } = group;\n\treturn { ...rest, children: group.children.map((c) => (c.blendStep ? plain(c, newId) : c)) };\n}\n\n/**\n * Release: the blend's keys in the group's parent space (the group's transform and opacity\n * applied), followed by the replaced spine as an unpainted path when there is one.\n */\nexport function releaseVectorBlend(group: VectorGroupNode, newId: () => string): VectorNode[] {\n\tconst m = nodeMatrix(group);\n\tconst opacity = group.opacity;\n\tconst keys = vectorBlendKeys(group)\n\t\t.map((c) => (group.transform ? transformVectorNode(c, m) : c))\n\t\t.map((c) => (opacity !== undefined && opacity < 1 ? { ...c, opacity: (c.opacity ?? 1) * opacity } : c));\n\tconst spine = group.blend?.spine;\n\tif (!spine || spine.anchors.length < 2) return keys;\n\tconst path: VectorPathNode = { id: newId(), type: 'path', name: 'Spine', fill: null, stroke: null, subpaths: [{ closed: spine.closed, anchors: spine.anchors.map((a) => ({ ...a })) }] };\n\treturn [...keys, group.transform ? transformVectorNode(path, m) : path];\n}\n","/**\n * Perspective (projective) maps between quadrilaterals: what Free Distort needs. Pure maths;\n * degenerate or non-finite quads give `null` instead of NaNs.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): pdfcraft `crates/geom/src/perspective.rs` (`Homography::from_points`,\n * `Homography::apply`, `solve8`, `order_quad`).\n */\nimport type { Vec2 } from './types.js';\n\n/** A 3×3 projective map, row-major, normalised so that the last entry is 1. */\nexport type VectorHomography = readonly [number, number, number, number, number, number, number, number, number];\n\n/**\n * Gaussian elimination with partial pivoting on an 8×8 system (the 9th column of each row is the\n * right-hand side). Null when the system is singular.\n */\nexport function solve8(rows: readonly (readonly number[])[]): number[] | null {\n\tconst m = rows.map((r) => r.slice());\n\tfor (let col = 0; col < 8; col++) {\n\t\tlet pivot = col;\n\t\tfor (let r = col + 1; r < 8; r++) if (Math.abs(m[r][col]) > Math.abs(m[pivot][col])) pivot = r;\n\t\tif (!(Math.abs(m[pivot][col]) >= 1e-12)) return null;\n\t\t[m[col], m[pivot]] = [m[pivot], m[col]];\n\t\tconst p = m[col];\n\t\tfor (let r = 0; r < 8; r++) {\n\t\t\tif (r === col) continue;\n\t\t\tconst f = m[r][col] / p[col];\n\t\t\tif (f !== 0) for (let k = 0; k < 9; k++) m[r][k] -= f * p[k];\n\t\t}\n\t}\n\tconst out: number[] = [];\n\tfor (let i = 0; i < 8; i++) {\n\t\tconst v = m[i][8] / m[i][i];\n\t\tif (!Number.isFinite(v)) return null;\n\t\tout.push(v);\n\t}\n\treturn out;\n}\n\n/** The image of `p`, or null where the map sends it to infinity. */\nexport function applyVectorHomography(h: VectorHomography, p: Vec2): Vec2 | null {\n\tconst w = h[6] * p.x + h[7] * p.y + h[8];\n\tif (!Number.isFinite(w) || Math.abs(w) < 1e-12) return null;\n\tconst x = (h[0] * p.x + h[1] * p.y + h[2]) / w;\n\tconst y = (h[3] * p.x + h[4] * p.y + h[5]) / w;\n\treturn Number.isFinite(x) && Number.isFinite(y) ? { x, y } : null;\n}\n\nconst finite = (p: Vec2) => Number.isFinite(p.x) && Number.isFinite(p.y);\n\n/**\n * The projective map that takes each of `from` to the point at the same index of `to`. Null when\n * three of either set are collinear or a coordinate is not finite.\n */\nexport function vectorHomography(from: readonly Vec2[], to: readonly Vec2[]): VectorHomography | null {\n\tif (from.length !== 4 || to.length !== 4 || ![...from, ...to].every(finite)) return null;\n\t// x' = (h0 x + h1 y + h2) / (h6 x + h7 y + 1), y' likewise with h3..h5: eight unknowns, two\n\t// equations per point pair.\n\tconst rows: number[][] = [];\n\tfor (let i = 0; i < 4; i++) {\n\t\tconst { x, y } = from[i];\n\t\tconst { x: u, y: v } = to[i];\n\t\trows.push([x, y, 1, 0, 0, 0, -u * x, -u * y, u]);\n\t\trows.push([0, 0, 0, x, y, 1, -v * x, -v * y, v]);\n\t}\n\tconst h = solve8(rows);\n\tif (!h) return null;\n\tconst out: VectorHomography = [h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7], 1];\n\t// Collinear points can leave a solvable but singular system: check the map really takes the\n\t// four points where they should go.\n\tfor (let i = 0; i < 4; i++) {\n\t\tconst r = applyVectorHomography(out, from[i]);\n\t\tconst q = to[i];\n\t\tconst scale = 1 + Math.max(Math.abs(q.x), Math.abs(q.y));\n\t\tif (!r || Math.abs(r.x - q.x) > 1e-6 * scale || Math.abs(r.y - q.y) > 1e-6 * scale) return null;\n\t}\n\treturn out;\n}\n\n/**\n * Whether `h` maps the whole convex quad `quad` without sending any of it through infinity (the\n * denominator keeps one sign over it): what a usable distortion needs.\n */\nexport function vectorHomographyKeepsQuad(h: VectorHomography, quad: readonly Vec2[]): boolean {\n\tconst ws = quad.map((p) => h[6] * p.x + h[7] * p.y + h[8]);\n\treturn ws.every((w) => w > 1e-9) || ws.every((w) => w < -1e-9);\n}\n\n/**\n * The four corners in reading order for a y-down space: top-left, top-right, bottom-right,\n * bottom-left, whatever order they come in. Null unless they form a convex quadrilateral with a\n * non-negligible area.\n */\nexport function orderVectorQuad(points: readonly Vec2[]): Vec2[] | null {\n\tif (points.length !== 4 || !points.every(finite)) return null;\n\tconst cx = points.reduce((s, p) => s + p.x, 0) / 4;\n\tconst cy = points.reduce((s, p) => s + p.y, 0) / 4;\n\t// Ascending angle about the centre is clockwise on screen (y down).\n\tconst q = points.slice().sort((a, b) => Math.atan2(a.y - cy, a.x - cx) - Math.atan2(b.y - cy, b.x - cx));\n\tlet first = 0;\n\tfor (let i = 1; i < 4; i++) if (q[i].x + q[i].y < q[first].x + q[first].y) first = i;\n\tconst ordered = [...q.slice(first), ...q.slice(0, first)];\n\tconst cross = (o: Vec2, a: Vec2, b: Vec2) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n\tconst turns = ordered.map((_, i) => cross(ordered[i], ordered[(i + 1) % 4], ordered[(i + 2) % 4]));\n\tconst area = turns.reduce((s, t) => s + t, 0) / 2;\n\tconst xs = ordered.map((p) => p.x);\n\tconst ys = ordered.map((p) => p.y);\n\tconst size = Math.max(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));\n\tconst convex = turns.every((t) => t > 1e-9 * size * size);\n\treturn convex && area > 1e-6 * size * size ? ordered : null;\n}\n","/**\n * Free Distort, perspective and skew: the selection box's corners or sides dragged, and nodes sent\n * through a map of document space while each keeps its own (rigid) transform.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): vectorcraft `crates/tools/src/xform/free.rs` (`distort_quad`: a corner\n * moved freely, or with its partner mirrored along the dominant axis for perspective, and a side's\n * two corners moved together; `shear_for_side`: a side handle shears about the opposite side, or\n * the centre with Alt).\n */\nimport { mapVectorSubpaths, type VectorPointMap } from './pathMap.js';\nimport { mapVectorPaint } from './gradient.js';\nimport { applyMatrix, invertMatrix, multiplyMatrices, nodeMatrix, type AffineMatrix } from './geometry.js';\nimport { vectorEffectInputBounds, vectorEnvelopeMap, vectorEnvelopeMesh } from './appearance.js';\nimport { mapVectorMeshPoints } from './warp.js';\nimport type { Vec2, VectorBounds, VectorEffect, VectorGroupNode, VectorNode, VectorPathNode, VectorTransformHandle } from './types.js';\n\n/** Default tolerance (document units) of Free Distort's adaptive path mapping. */\nexport const VECTOR_DISTORT_TOLERANCE = 0.05;\n\n/** How dragging a selection box handle distorts it: each corner freely, or in symmetric perspective. */\nexport type VectorDistortMode = 'distort' | 'perspective';\n\nconst CORNER_INDEX: Partial<Record<VectorTransformHandle, number>> = { nw: 0, ne: 1, se: 2, sw: 3 };\nconst SIDE_CORNERS: Partial<Record<VectorTransformHandle, [number, number]>> = { n: [0, 1], e: [1, 2], s: [2, 3], w: [3, 0] };\n\n/** A box's corners clockwise from the top left. */\nexport const vectorBoxCorners = (b: VectorBounds): Vec2[] => [\n\t{ x: b.x, y: b.y },\n\t{ x: b.x + b.width, y: b.y },\n\t{ x: b.x + b.width, y: b.y + b.height },\n\t{ x: b.x, y: b.y + b.height }\n];\n\n/**\n * The quad (clockwise from the top left) box `b` becomes when handle `handle` is dragged by `d`: a\n * corner moves by `d` (`distort`), or along the drag's dominant axis with the corner beside it on\n * that side moving the opposite way (`perspective`); a side moves both its corners.\n */\nexport function vectorDistortQuad(b: VectorBounds, handle: VectorTransformHandle, d: Vec2, mode: VectorDistortMode = 'distort'): Vec2[] {\n\tconst q = vectorBoxCorners(b);\n\tconst i = CORNER_INDEX[handle];\n\tif (i !== undefined) {\n\t\tif (mode === 'perspective') {\n\t\t\tif (Math.abs(d.x) >= Math.abs(d.y)) {\n\t\t\t\tconst partner = [1, 0, 3, 2][i];\n\t\t\t\tq[i].x += d.x;\n\t\t\t\tq[partner].x -= d.x;\n\t\t\t} else {\n\t\t\t\tconst partner = [3, 2, 1, 0][i];\n\t\t\t\tq[i].y += d.y;\n\t\t\t\tq[partner].y -= d.y;\n\t\t\t}\n\t\t} else {\n\t\t\tq[i].x += d.x;\n\t\t\tq[i].y += d.y;\n\t\t}\n\t\treturn q;\n\t}\n\tconst side = SIDE_CORNERS[handle];\n\tif (side) for (const k of side) q[k] = { x: q[k].x + d.x, y: q[k].y + d.y };\n\treturn q;\n}\n\nconst about = (o: Vec2, m: AffineMatrix): AffineMatrix => multiplyMatrices(multiplyMatrices([1, 0, 0, 1, -o.x, -o.y], m), [1, 0, 0, 1, o.x, o.y]);\n\n/**\n * The skew for dragging side `handle` of box `b` by `d`: along that side, about the opposite side\n * (or the centre, `fromCenter`). Corners give the identity.\n */\nexport function vectorShearForSide(b: VectorBounds, handle: VectorTransformHandle, d: Vec2, fromCenter = false): AffineMatrix {\n\tconst center = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\tif (handle === 'n' || handle === 's') {\n\t\tconst o = fromCenter ? center : { x: center.x, y: handle === 'n' ? b.y + b.height : b.y };\n\t\tconst lever = (handle === 'n' ? b.y : b.y + b.height) - o.y;\n\t\treturn about(o, [1, 0, Math.abs(lever) > 1e-9 ? d.x / lever : 0, 1, 0, 0]);\n\t}\n\tif (handle === 'e' || handle === 'w') {\n\t\tconst o = fromCenter ? center : { x: handle === 'w' ? b.x + b.width : b.x, y: center.y };\n\t\tconst lever = (handle === 'w' ? b.x : b.x + b.width) - o.x;\n\t\treturn about(o, [1, Math.abs(lever) > 1e-9 ? d.y / lever : 0, 0, 1, 0, 0]);\n\t}\n\treturn [1, 0, 0, 1, 0, 0];\n}\n\n/**\n * A skew by `ax` degrees horizontally (vertical lines lean right for positive angles: x' = x + tan(ax)·y)\n * and `ay` degrees vertically (y' = y + tan(ay)·x), about `origin`.\n */\nexport function vectorSkewMatrix(ax: number, ay: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n\tconst tx = Math.tan((ax * Math.PI) / 180);\n\tconst ty = Math.tan((ay * Math.PI) / 180);\n\treturn about(origin, [1, ty, tx, 1, 0, 0]);\n}\n\n/** Effects after their node's geometry went through a non-affine map: envelope meshes follow it (a preset becomes the mesh it stood for). */\nfunction mapEffects(node: VectorNode, f: VectorPointMap): VectorEffect[] | undefined {\n\tif (!node.effects?.length) return undefined;\n\treturn node.effects.map((e) => {\n\t\tif (e.type !== 'envelope') return e;\n\t\tif (e.params.style === 'mesh') return e.params.mesh ? { ...e, params: { ...e.params, mesh: mapVectorMeshPoints(e.params.mesh, f) } } : e;\n\t\tconst bounds = vectorEffectInputBounds(node, e.id);\n\t\tif (!bounds || !vectorEnvelopeMap(e.params, bounds)) return e;\n\t\treturn { ...e, params: { ...e.params, style: 'mesh', mesh: mapVectorMeshPoints(vectorEnvelopeMesh(e.params, bounds), f) } };\n\t});\n}\n\n/**\n * A node sent through `f`, a map of the space `parentToDoc` maps its parent to (the document):\n * every anchor and handle is mapped in the node's own space, adaptively so curves stay within\n * `tolerance`, and the node keeps its rigid `transform`. Gradients in the node's space have their\n * handles mapped (bounding-box ones follow the new bounds), envelope meshes and a blend's spine\n * are mapped too; stroke widths, live corner radii and effect parameters are kept.\n */\nexport function distortVectorNode<T extends VectorNode>(node: T, parentToDoc: AffineMatrix, f: VectorPointMap, tolerance = VECTOR_DISTORT_TOLERANCE): T {\n\tconst toDoc = multiplyMatrices(nodeMatrix(node), parentToDoc);\n\tconst inv = invertMatrix(toDoc);\n\tconst local: VectorPointMap = (p) => applyMatrix(inv, f(applyMatrix(toDoc, p)));\n\tconst effects = mapEffects(node, local);\n\tif (node.type === 'group') {\n\t\tconst group = node as VectorGroupNode;\n\t\tconst children = group.children.map((c) => distortVectorNode(c, toDoc, f, tolerance));\n\t\tconst spine = group.blend?.spine;\n\t\treturn {\n\t\t\t...group,\n\t\t\tchildren,\n\t\t\t...(effects ? { effects } : {}),\n\t\t\t...(spine ? { blend: { ...group.blend, spine: mapVectorSubpaths([spine], local, tolerance)[0] } } : {})\n\t\t} as T;\n\t}\n\tconst path = node as VectorPathNode;\n\treturn {\n\t\t...path,\n\t\t...(effects ? { effects } : {}),\n\t\t...(path.fill !== undefined ? { fill: mapVectorPaint(path.fill, local) } : {}),\n\t\t...(path.stroke !== undefined ? { stroke: mapVectorPaint(path.stroke, local) } : {}),\n\t\tsubpaths: mapVectorSubpaths(path.subpaths, local, tolerance)\n\t} as T;\n}\n","/**\n * Smart guides and object snapping for the vector editor. Targets — anchors, bounding-box\n * edges and centres, path segments and the artboard — are gathered once per gesture in\n * document space (rotated nodes included) and kept sorted by x and y, so each pointer move\n * finds the few near the pointer by bisection. A point snaps, in this order of priority: kept\n * to its Shift angle and slid into line with a target, onto an anchor or centre, onto an\n * intersection of two paths, onto the perpendicular foot or tangent point from where it\n * leaves, onto a path, onto a construction angle, then into line with targets on x and y. A\n * moved box lines its edges and centre up with targets, or spaces itself evenly in its row\n * and column; a resized box lands its moving edges on targets, or matches another object's\n * width or height. Every snap reports labelled guide lines in document units.\n *\n * Portions ported from vectorcraft-main/crates/tools/src/guides.rs (`Targets`, `within`,\n * `for_move`, `for_drawing`, `for_handle`, `for_anchor_drag`, `push_segments`, `snap_from`,\n * `slide`, `lined_up`, `on_segment`, `crossing`, `align_rects`, `snap_rects`, `even_spacing`,\n * `gap_marks`, `snap_scale`, `Leave`), figcraft-main/crates/engine/src/snap.rs (`spacings`,\n * `equal_spacing`, `spacing_guides`: equal-spacing cases and gap labels),\n * designcraft-main/crates/tools/src/snap.rs (`pass_dimensions`: matching other objects'\n * sizes) and cadcraft-main/crates/engine/src/snap/curves.rs (`Param::solve`: perpendicular and\n * tangent points by sign-change sampling and bisection) (MIT OR Apache-2.0, © ArtCraft Team\n * and contributors). See THIRD_PARTY_NOTICES.md.\n */\nimport type { Point } from '../canvas/types.js';\nimport { expandVectorAppearance } from './appearance.js';\nimport { segmentDerivative, segmentNearest, segmentPoint, type BezierSegment } from '../canvas/pathops/bezier.js';\nimport { segmentIntersections } from '../canvas/pathops/boolean.js';\nimport {\n\tapplyMatrix,\n\tIDENTITY_MATRIX,\n\tmatrixRotation,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\trotateMatrix,\n\tsubpathSegment,\n\tsubpathSegmentCount,\n\tvectorNodeBounds,\n\ttype AffineMatrix\n} from './geometry.js';\nimport type { VectorAnchorRef, VectorBounds, VectorDocument, VectorNode, VectorSubpath, VectorTransformHandle, Vec2 } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * What a guide line shows: `align` lines run from a target through the snapped point or box,\n * `construction` lines from where a drawn point leaves, `spacing` marks equal gaps and `size`\n * the side whose length matches another object's.\n */\nexport type VectorGuideKind = 'align' | 'construction' | 'spacing' | 'size';\n\n/** A guide line in document units. */\nexport interface VectorGuideLine {\n\tkind: VectorGuideKind;\n\tx1: number;\n\ty1: number;\n\tx2: number;\n\ty2: number;\n}\n\n/** What a point or box snapped to. */\nexport type VectorSnapKind = 'anchor' | 'centre' | 'intersect' | 'perpendicular' | 'tangent' | 'path' | 'construction' | 'align' | 'spacing' | 'size';\n\n/** A guide label in document units: the snap kind's name, or a distance for gaps and sizes. */\nexport interface VectorGuideLabel {\n\tkind: VectorSnapKind;\n\tx: number;\n\ty: number;\n\ttext: string;\n}\n\nexport interface VectorSnapGuides {\n\tlines: VectorGuideLine[];\n\tlabels: VectorGuideLabel[];\n}\n\nexport interface VectorPointSnap extends VectorSnapGuides {\n\tpoint: Vec2;\n\t/** The rule that placed the point, or null when nothing was in reach. */\n\tkind: VectorSnapKind | null;\n\t/** Whether x / y were set by a target (for falling back to the grid on the other axis). */\n\tx: boolean;\n\ty: boolean;\n}\n\nexport interface VectorRectSnap extends VectorSnapGuides {\n\t/** Correction to add to the move. */\n\tdx: number;\n\tdy: number;\n\tx: boolean;\n\ty: boolean;\n}\n\nexport interface VectorScaleSnap extends VectorSnapGuides {\n\tsx: number;\n\tsy: number;\n\tsnapped: boolean;\n}\n\n/**\n * The point a drawn point leaves from (the anchor before it, a shape's start, a handle's\n * anchor) and how it keeps to it.\n */\nexport interface VectorSnapLeave {\n\tat: Vec2;\n\t/**\n\t * Shift held: keep to 45° steps round `at` (`angle`), to a diagonal (`square`, a box's\n\t * corner) or to the nearer axis (`axis`, a dragged point).\n\t */\n\tconstrain?: 'angle' | 'square' | 'axis' | null;\n\t/** Construction guide angles through `at`, degrees counter-clockwise on screen. */\n\tangles?: readonly number[];\n\t/** Snap to the perpendicular foot and tangent points from `at` on paths (default true). */\n\tcurves?: boolean;\n}\n\n/** The construction guide angles new editors start with. */\nexport const VECTOR_CONSTRUCTION_ANGLES: readonly number[] = [0, 45, 90, 135];\n\n/** Where `constrain` puts `p` (unchanged without one). */\nexport function constrainToLeave(leave: VectorSnapLeave | null | undefined, p: Vec2): Vec2 {\n\tif (!leave?.constrain) return p;\n\tconst dx = p.x - leave.at.x;\n\tconst dy = p.y - leave.at.y;\n\tswitch (leave.constrain) {\n\t\tcase 'axis':\n\t\t\treturn Math.abs(dx) > Math.abs(dy) ? { x: p.x, y: leave.at.y } : { x: leave.at.x, y: p.y };\n\t\tcase 'square': {\n\t\t\tconst s = Math.max(Math.abs(dx), Math.abs(dy));\n\t\t\treturn { x: leave.at.x + Math.sign(dx || 1) * s, y: leave.at.y + Math.sign(dy || 1) * s };\n\t\t}\n\t\tdefault: {\n\t\t\tconst len = Math.hypot(dx, dy);\n\t\t\tconst a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);\n\t\t\treturn { x: leave.at.x + Math.cos(a) * len, y: leave.at.y + Math.sin(a) * len };\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Targets\n// ---------------------------------------------------------------------------\n\ntype TargetKind = 'anchor' | 'centre' | 'edge' | 'artboard';\n\ninterface PointTarget {\n\tp: Vec2;\n\tkind: 'anchor' | 'centre';\n}\n\n/** A line to line up with: where it runs on its axis and the target point it comes from. */\ninterface LineTarget {\n\tv: number;\n\tfrom: Vec2;\n\tkind: TargetKind;\n}\n\ninterface SegmentTarget {\n\tseg: Point[];\n\tminX: number;\n\tminY: number;\n\tmaxX: number;\n\tmaxY: number;\n}\n\n/** How many anchors, and how many segments, the targets gather at most. */\nconst BUDGET = 20_000;\n/** The first near segments paired up when looking for intersections. */\nconst CROSSING_PAIRS = 32;\n/** Parameter samples per segment for perpendicular / tangent roots, and bisection steps. */\nconst CURVE_SAMPLES = 48;\nconst BISECT = 50;\nconst EQUAL = 1e-6;\n\n/** First index of `sorted` whose key is not below `v` (`strict`: above `v`). */\nfunction bound<T>(sorted: readonly T[], key: (e: T) => number, v: number, strict: boolean): number {\n\tlet lo = 0;\n\tlet hi = sorted.length;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi) >>> 1;\n\t\tconst k = key(sorted[mid]);\n\t\tif (strict ? k <= v : k < v) lo = mid + 1;\n\t\telse hi = mid;\n\t}\n\treturn lo;\n}\n\n/** The entries of `sorted` (ascending by `key`) whose key is within `tol` of `v`, by bisection. */\nfunction within<T>(sorted: readonly T[], key: (e: T) => number, v: number, tol: number): readonly T[] {\n\treturn sorted.slice(bound(sorted, key, v - tol, false), bound(sorted, key, v + tol, true));\n}\n\nconst linesNear = (lines: readonly LineTarget[], v: number, tol: number) => within(lines, (l) => l.v, v, tol);\n\nconst distance = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\nconst toPoint = (p: Vec2): Point => [p.x, p.y];\nconst toVec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\n\n/** What `collect` gathers from each path besides its anchors and bounds. */\ntype Gather = 'bounds' | 'segments' | 'drawing';\n\nconst LABELS: Record<VectorSnapKind, string> = {\n\tanchor: 'anchor',\n\tcentre: 'centre',\n\tintersect: 'intersect',\n\tperpendicular: 'perpendicular',\n\ttangent: 'tangent',\n\tpath: 'path',\n\tconstruction: 'angle',\n\talign: 'align',\n\tspacing: 'spacing',\n\tsize: 'size'\n};\n\nconst fmtLength = (n: number) => String(Math.round(n * 100) / 100);\n\n/** A node's own (possibly rotated) frame: its size there and its centre in document space. */\nfunction nodeFrame(node: VectorNode, parent: AffineMatrix, aabb?: VectorBounds | null): { width: number; height: number; centre: Vec2 } | null {\n\tconst angle = matrixRotation(multiplyMatrices(nodeMatrix(node), parent));\n\tconst b = angle ? vectorNodeBounds(node, multiplyMatrices(parent, rotateMatrix(-angle))) : aabb !== undefined ? aabb : vectorNodeBounds(node, parent);\n\tif (!b) return null;\n\tconst c = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\treturn { width: b.width, height: b.height, centre: angle ? applyMatrix(rotateMatrix(angle), c) : c };\n}\n\n/** True when `id` is `node` or inside it. */\nfunction contains(node: VectorNode, ids: ReadonlySet<string>): boolean {\n\tif (ids.has(node.id)) return true;\n\treturn node.type === 'group' && node.children.some((c) => contains(c, ids));\n}\n\n/**\n * Snap targets in document space, gathered once per gesture. Build them with `forMove`,\n * `forResize`, `forDrawing`, `forAnchorDrag` or `forHandle`, then call `snapFrom`,\n * `snapRect` or `snapScale` on every pointer move. Tolerances are in document units (screen\n * pixels divided by the zoom).\n */\nexport class VectorSnapTargets {\n\tprivate readonly points: PointTarget[] = [];\n\tprivate readonly xs: LineTarget[] = [];\n\tprivate readonly ys: LineTarget[] = [];\n\tprivate readonly segments: SegmentTarget[] = [];\n\t/** Bounds of the objects a moved box spaces itself evenly with. */\n\tprivate readonly boxes: VectorBounds[] = [];\n\t/** Side lengths of the other objects (in their own frames), which a resize may match. */\n\tprivate readonly sizes: number[] = [];\n\n\tprivate constructor() {}\n\n\t/** How many targets of each sort were gathered. */\n\tget counts(): { points: number; lines: number; segments: number; boxes: number } {\n\t\treturn { points: this.points.length, lines: this.xs.length + this.ys.length, segments: this.segments.length, boxes: this.boxes.length };\n\t}\n\n\t/** Targets for moving nodes `ids`: the other art's anchors, bounds and centres, the artboard, and boxes to space evenly with. */\n\tstatic forMove(doc: VectorDocument, ids: readonly string[]): VectorSnapTargets {\n\t\treturn VectorSnapTargets.collect(doc, new Set(ids), 'bounds');\n\t}\n\n\t/** Targets for resizing nodes `ids`: as for a move, plus the other objects' sizes. */\n\tstatic forResize(doc: VectorDocument, ids: readonly string[]): VectorSnapTargets {\n\t\treturn VectorSnapTargets.collect(doc, new Set(ids), 'bounds');\n\t}\n\n\t/**\n\t * Targets for a drawn point (pen, shape tools): the art but `exclude`, its anchors (as\n\t * points and in line), centres, edges and segments. The anchors and segments of `exclude`\n\t * (the path being drawn, whose bounds grow with it) stay targets.\n\t */\n\tstatic forDrawing(doc: VectorDocument, exclude: readonly string[] = []): VectorSnapTargets {\n\t\tconst skip = new Set(exclude);\n\t\tconst t = VectorSnapTargets.collect(doc, skip, 'drawing', false);\n\t\tt.pushPaths(doc, skip, () => false, true);\n\t\treturn t.index();\n\t}\n\n\t/**\n\t * Targets for dragging anchors: the other art with its segments, and the anchors and\n\t * segments that stay put on the paths being reshaped (their bounds move along, so they are\n\t * no targets). The moving anchors are left out.\n\t */\n\tstatic forAnchorDrag(doc: VectorDocument, anchors: readonly VectorAnchorRef[]): VectorSnapTargets {\n\t\tconst moving = new Map<string, Set<string>>();\n\t\tfor (const r of anchors) {\n\t\t\tconst set = moving.get(r.nodeId) ?? new Set<string>();\n\t\t\tset.add(`${r.subpath}:${r.index}`);\n\t\t\tmoving.set(r.nodeId, set);\n\t\t}\n\t\tconst t = VectorSnapTargets.collect(doc, new Set(moving.keys()), 'segments', false);\n\t\tt.pushPaths(doc, new Set(moving.keys()), (id, s, i) => !!moving.get(id)?.has(`${s}:${i}`), true);\n\t\treturn t.index();\n\t}\n\n\t/**\n\t * Targets for dragging a handle of path `nodeId`: the other art and that path's anchors\n\t * (its bounds and the segments through the handle move with it, so they would chase it).\n\t */\n\tstatic forHandle(doc: VectorDocument, nodeId: string): VectorSnapTargets {\n\t\tconst skip = new Set([nodeId]);\n\t\tconst t = VectorSnapTargets.collect(doc, skip, 'bounds', false);\n\t\tt.pushPaths(doc, skip, () => false, false);\n\t\treturn t.index();\n\t}\n\n\t/** The anchors of the paths `ids` as targets (on them and in line), and their segments when `segments`. */\n\tprivate pushPaths(doc: VectorDocument, ids: ReadonlySet<string>, moving: (id: string, subpath: number, index: number) => boolean, segments: boolean) {\n\t\tlet anchors = BUDGET;\n\t\tlet segmentBudget = segments ? BUDGET : 0;\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') visit(n.children, m);\n\t\t\t\telse if (ids.has(n.id) && n.visible !== false) {\n\t\t\t\t\tn.subpaths.forEach((sp, s) => {\n\t\t\t\t\t\tsp.anchors.forEach((a, i) => {\n\t\t\t\t\t\t\tif (anchors <= 0 || moving(n.id, s, i)) return;\n\t\t\t\t\t\t\tthis.pushAnchor(applyMatrix(m, a));\n\t\t\t\t\t\t\tanchors--;\n\t\t\t\t\t\t});\n\t\t\t\t\t\tsegmentBudget = this.pushSegments(sp, m, (i) => moving(n.id, s, i), segmentBudget);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvisit(doc.nodes, IDENTITY_MATRIX);\n\t}\n\n\tprivate pushAnchor(p: Vec2) {\n\t\tthis.points.push({ p, kind: 'anchor' });\n\t\tthis.xs.push({ v: p.x, from: p, kind: 'anchor' });\n\t\tthis.ys.push({ v: p.y, from: p, kind: 'anchor' });\n\t}\n\n\t/** The segments of `sp` (mapped by `m`) that stay put while the anchors `moving` accepts move. */\n\tprivate pushSegments(sp: VectorSubpath, m: AffineMatrix, moving: (index: number) => boolean, budget: number): number {\n\t\tconst n = sp.anchors.length;\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count && budget > 0; i++) {\n\t\t\tif (moving(i) || moving((i + 1) % n)) continue;\n\t\t\tconst seg = subpathSegment(sp, i).map((q) => toPoint(applyMatrix(m, toVec(q))));\n\t\t\tlet minX = Infinity;\n\t\t\tlet minY = Infinity;\n\t\t\tlet maxX = -Infinity;\n\t\t\tlet maxY = -Infinity;\n\t\t\tfor (const [x, y] of seg) {\n\t\t\t\tminX = Math.min(minX, x);\n\t\t\t\tminY = Math.min(minY, y);\n\t\t\t\tmaxX = Math.max(maxX, x);\n\t\t\t\tmaxY = Math.max(maxY, y);\n\t\t\t}\n\t\t\tthis.segments.push({ seg, minX, minY, maxX, maxY });\n\t\t\tbudget--;\n\t\t}\n\t\treturn budget;\n\t}\n\n\tprivate pushRect(r: VectorBounds, kind: TargetKind, centre: Vec2 | null) {\n\t\tconst corners = [\n\t\t\t{ x: r.x, y: r.y },\n\t\t\t{ x: r.x + r.width, y: r.y },\n\t\t\t{ x: r.x + r.width, y: r.y + r.height },\n\t\t\t{ x: r.x, y: r.y + r.height }\n\t\t];\n\t\tfor (const p of corners) {\n\t\t\tthis.xs.push({ v: p.x, from: p, kind });\n\t\t\tthis.ys.push({ v: p.y, from: p, kind });\n\t\t}\n\t\tif (centre) {\n\t\t\tthis.points.push({ p: centre, kind: 'centre' });\n\t\t\tthis.xs.push({ v: centre.x, from: centre, kind: 'centre' });\n\t\t\tthis.ys.push({ v: centre.y, from: centre, kind: 'centre' });\n\t\t}\n\t}\n\n\t/** Sorts the targets for `within` (stable: of targets alike, the first gathered wins). */\n\tprivate index(): this {\n\t\tthis.points.sort((a, b) => a.p.x - b.p.x);\n\t\tthis.xs.sort((a, b) => a.v - b.v);\n\t\tthis.ys.sort((a, b) => a.v - b.v);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Gathers targets from the artboard and every visible node but `exclude` (and what is inside\n\t * those): each leaf's anchors (also as lines for `drawing`), its segments (`segments`,\n\t * `drawing`), its bounds' corners as lines and its centre; and the top-level objects' boxes and\n\t * sizes (inside a group holding an excluded node, that group's other members).\n\t */\n\tprivate static collect(doc: VectorDocument, exclude: ReadonlySet<string>, gather: Gather, sort = true): VectorSnapTargets {\n\t\tconst self = new VectorSnapTargets();\n\t\tconst artboard = { x: 0, y: 0, width: doc.width, height: doc.height };\n\t\tself.pushRect(artboard, 'artboard', { x: doc.width / 2, y: doc.height / 2 });\n\t\tlet anchors = BUDGET;\n\t\tlet segments = BUDGET;\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const stored of list) {\n\t\t\t\tif (exclude.has(stored.id) || stored.visible === false) continue;\n\t\t\t\t// Other art snaps where it draws (path effects and live booleans applied).\n\t\t\t\tconst n = contains(stored, exclude) ? stored : expandVectorAppearance(stored);\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tvisit(n.children, m);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (anchors <= 0) continue;\n\t\t\t\tfor (const sp of n.subpaths) {\n\t\t\t\t\tfor (const a of sp.anchors) {\n\t\t\t\t\t\tif (anchors-- <= 0) break;\n\t\t\t\t\t\tconst p = applyMatrix(m, a);\n\t\t\t\t\t\tif (gather === 'drawing') self.pushAnchor(p);\n\t\t\t\t\t\telse self.points.push({ p, kind: 'anchor' });\n\t\t\t\t\t}\n\t\t\t\t\tif (gather !== 'bounds') segments = self.pushSegments(sp, m, () => false, segments);\n\t\t\t\t}\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tconst f = nodeFrame(n, parent, b);\n\t\t\t\tif (b) self.pushRect(b, 'edge', f?.centre ?? null);\n\t\t\t}\n\t\t};\n\t\tvisit(doc.nodes, IDENTITY_MATRIX);\n\t\t// Boxes to space evenly with and sizes to match: whole objects, opening groups that hold an excluded node.\n\t\tconst objects = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tif (exclude.has(n.id) || n.visible === false || self.boxes.length >= BUDGET) continue;\n\t\t\t\tif (n.type === 'group' && contains(n, exclude)) {\n\t\t\t\t\tobjects(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tif (b) self.boxes.push(b);\n\t\t\t\tconst f = nodeFrame(n, parent, b);\n\t\t\t\tif (f) self.sizes.push(f.width, f.height);\n\t\t\t}\n\t\t};\n\t\tobjects(doc.nodes, IDENTITY_MATRIX);\n\t\treturn sort ? self.index() : self;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Points\n\t// -------------------------------------------------------------------------\n\n\t/** Snaps a single point (see `snapFrom`). */\n\tsnapPoint(p: Vec2, tol: number): VectorPointSnap {\n\t\treturn this.snapFrom(p, null, tol);\n\t}\n\n\t/**\n\t * Snaps a point `p`, drawn or dragged from `leave` when given. With `leave.constrain` it keeps\n\t * to its angle round `leave.at`, sliding along that way into line with the nearest target.\n\t * Otherwise it lands, in order, on an anchor or centre, an intersection of two paths, the\n\t * perpendicular foot or a tangent point from `leave.at`, a path, a construction guide\n\t * through `leave.at` (where a target's line crosses it if one does nearby), or else lines up\n\t * with targets on x and y.\n\t */\n\tsnapFrom(p: Vec2, leave: VectorSnapLeave | null | undefined, tol: number): VectorPointSnap {\n\t\tconst none = (q: Vec2): VectorPointSnap => ({ point: q, kind: null, x: false, y: false, lines: [], labels: [] });\n\t\tconst at = (q: Vec2, kind: VectorSnapKind, lines: VectorGuideLine[] = []): VectorPointSnap => ({\n\t\t\tpoint: q,\n\t\t\tkind,\n\t\t\tx: true,\n\t\t\ty: true,\n\t\t\tlines,\n\t\t\tlabels: [this.label(q, kind)]\n\t\t});\n\t\tif (leave?.constrain) {\n\t\t\tconst q = constrainToLeave(leave, p);\n\t\t\tconst hit = this.slide(leave.at, { x: q.x - leave.at.x, y: q.y - leave.at.y }, q, tol, true);\n\t\t\treturn hit ? { point: hit.point, x: true, y: true, ...this.linedUp(hit.point, hit.from) } : none(q);\n\t\t}\n\t\tconst point = this.nearestPoint(p, tol);\n\t\tif (point) return at(point.p, point.kind);\n\t\tconst near = this.segmentsNear(p, tol);\n\t\tconst crossing = this.crossing(near, p, tol);\n\t\tif (crossing) return at(crossing, 'intersect');\n\t\tif (leave && leave.curves !== false) {\n\t\t\tconst foot = this.curvePoint(near, leave.at, p, tol);\n\t\t\tif (foot) return at(foot.point, foot.kind, [line('construction', leave.at, foot.point)]);\n\t\t}\n\t\tconst on = this.onSegment(near);\n\t\tif (on) return at(on, 'path');\n\t\tif (leave?.angles?.length) {\n\t\t\tconst c = construction(leave, p, tol);\n\t\t\tif (c) {\n\t\t\t\tconst hit = this.slide(leave.at, c.dir, c.point, tol, false);\n\t\t\t\tif (hit) {\n\t\t\t\t\tconst lined = this.linedUp(hit.point, hit.from);\n\t\t\t\t\treturn { point: hit.point, x: true, y: true, kind: lined.kind, lines: [line('construction', leave.at, hit.point), ...lined.lines], labels: lined.labels };\n\t\t\t\t}\n\t\t\t\treturn { point: c.point, kind: 'construction', x: true, y: true, lines: [line('construction', leave.at, c.point)], labels: [] };\n\t\t\t}\n\t\t}\n\t\tconst nearest = (lines: readonly LineTarget[], v: number) => {\n\t\t\tlet best: LineTarget | null = null;\n\t\t\tfor (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.v - v)) best = l;\n\t\t\treturn best;\n\t\t};\n\t\tconst bx = nearest(this.xs, p.x);\n\t\tconst by = nearest(this.ys, p.y);\n\t\tif (!bx && !by) return none(p);\n\t\tconst out = { x: bx ? bx.v : p.x, y: by ? by.v : p.y };\n\t\tconst lines: VectorGuideLine[] = [];\n\t\tif (bx) lines.push(line('align', bx.from, { x: out.x, y: out.y }));\n\t\tif (by) lines.push(line('align', by.from, { x: out.x, y: out.y }));\n\t\treturn { point: out, kind: 'align', x: !!bx, y: !!by, lines, labels: [this.label(out, 'align')] };\n\t}\n\n\tprivate label(p: Vec2, kind: VectorSnapKind, text = LABELS[kind]): VectorGuideLabel {\n\t\treturn { kind, x: p.x, y: p.y, text };\n\t}\n\n\t/** The anchor or centre nearest `p`, within `tol`. */\n\tprivate nearestPoint(p: Vec2, tol: number): PointTarget | null {\n\t\tlet best: PointTarget | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const t of within(this.points, (e) => e.p.x, p.x, tol)) {\n\t\t\tconst d = distance(t.p, p);\n\t\t\tif (d <= tol && d < bestD) {\n\t\t\t\tbest = t;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * Slides `q`, on the line through `at` along `dir` (beyond `at` only for a `ray`), to where\n\t * the nearest target line crosses it, at most twice `tol` away: where it lands and the\n\t * target point that line comes from.\n\t */\n\tprivate slide(at: Vec2, dir: Vec2, q: Vec2, tol: number, ray: boolean): { point: Vec2; from: Vec2 } | null {\n\t\tconst len2 = dir.x * dir.x + dir.y * dir.y;\n\t\tif (!Number.isFinite(len2) || len2 <= 1e-18) return null;\n\t\tconst reach = 2 * tol;\n\t\tlet best: { moved: number; point: Vec2; from: Vec2 } | null = null;\n\t\tfor (const vertical of [true, false]) {\n\t\t\tconst d = vertical ? dir.x : dir.y;\n\t\t\tif (Math.abs(d) <= 1e-9) continue;\n\t\t\tconst a = vertical ? at.x : at.y;\n\t\t\tfor (const l of linesNear(vertical ? this.xs : this.ys, vertical ? q.x : q.y, reach)) {\n\t\t\t\tconst s = (l.v - a) / d;\n\t\t\t\t// Exactly on the line, whatever the rounding along the way.\n\t\t\t\tconst hit = vertical ? { x: l.v, y: at.y + dir.y * s } : { x: at.x + dir.x * s, y: l.v };\n\t\t\t\tconst moved = distance(hit, q);\n\t\t\t\tif (moved <= reach && (!ray || s > 0) && (!best || moved < best.moved)) best = { moved, point: hit, from: l.from };\n\t\t\t}\n\t\t}\n\t\treturn best && { point: best.point, from: best.from };\n\t}\n\n\t/** The guides of a point `q` slid into line with the target at `from`: the line and \"align\", or the target's own label when `q` sits on it. */\n\tprivate linedUp(q: Vec2, from: Vec2): { kind: VectorSnapKind } & VectorSnapGuides {\n\t\tconst on = this.nearestPoint(q, 1e-9);\n\t\tif (on) return { kind: on.kind, lines: [], labels: [this.label(on.p, on.kind)] };\n\t\treturn { kind: 'align', lines: [line('align', from, q)], labels: [this.label(q, 'align')] };\n\t}\n\n\t/** Target segments whose control box reaches `p` and which pass within `tol` of it, nearest first. */\n\tprivate segmentsNear(p: Vec2, tol: number): { seg: Point[]; t: number; distance: number }[] {\n\t\tconst out: { seg: Point[]; t: number; distance: number }[] = [];\n\t\tconst pt = toPoint(p);\n\t\tfor (const s of this.segments) {\n\t\t\tif (p.x < s.minX - tol || p.x > s.maxX + tol || p.y < s.minY - tol || p.y > s.maxY + tol) continue;\n\t\t\tconst hit = segmentNearest(s.seg, pt);\n\t\t\tif (hit.distance <= tol) out.push({ seg: s.seg, t: hit.t, distance: hit.distance });\n\t\t}\n\t\treturn out.sort((a, b) => a.distance - b.distance);\n\t}\n\n\tprivate onSegment(near: readonly { seg: Point[]; t: number }[]): Vec2 | null {\n\t\treturn near.length ? toVec(segmentPoint(near[0].seg, near[0].t)) : null;\n\t}\n\n\t/** Where two of the target segments near `p` cross, the crossing nearest `p` within `tol`. */\n\tprivate crossing(near: readonly { seg: Point[] }[], p: Vec2, tol: number): Vec2 | null {\n\t\tconst list = near.slice(0, CROSSING_PAIRS);\n\t\tlet best: Vec2 | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (let i = 0; i < list.length; i++) {\n\t\t\tfor (let j = i + 1; j < list.length; j++) {\n\t\t\t\tfor (const hit of segmentIntersections(list[i].seg as BezierSegment, list[j].seg as BezierSegment)) {\n\t\t\t\t\tconst q = toVec(hit.point);\n\t\t\t\t\tconst d = distance(q, p);\n\t\t\t\t\tif (d <= tol && d < bestD) {\n\t\t\t\t\t\tbest = q;\n\t\t\t\t\t\tbestD = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * The foot of a perpendicular, or a tangent point, from `base` on a target segment near `p`\n\t * (within `tol` of it): roots of `(B(t) − base) · B′(t)` and `(B(t) − base) × B′(t)`\n\t * bracketed by sign changes of samples and narrowed by bisection.\n\t */\n\tprivate curvePoint(near: readonly { seg: Point[] }[], base: Vec2, p: Vec2, tol: number): { point: Vec2; kind: 'perpendicular' | 'tangent' } | null {\n\t\tlet best: { point: Vec2; kind: 'perpendicular' | 'tangent'; d: number } | null = null;\n\t\tfor (const { seg } of near) {\n\t\t\tfor (const kind of ['perpendicular', 'tangent'] as const) {\n\t\t\t\tif (kind === 'tangent' && seg.length === 2) continue;\n\t\t\t\tfor (const q of solveOnSegment(seg, base, kind === 'perpendicular' ? dotCondition : crossCondition)) {\n\t\t\t\t\tconst d = distance(q, p);\n\t\t\t\t\tif (d <= tol && (!best || d < best.d)) best = { point: q, kind, d };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best && { point: best.point, kind: best.kind };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Boxes\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Snaps a moving box `r` (the moved selection's bounds): its edge or centre nearest a target\n\t * line on each axis (`axes` limits which may move). With `spacing`, an axis that lines up\n\t * with nothing spaces the box evenly in its row or column. Returns the correction and guides.\n\t */\n\tsnapRect(r: VectorBounds, tol: number, options: { spacing?: boolean; axes?: { x?: boolean; y?: boolean } } = {}): VectorRectSnap {\n\t\tconst axes = { x: options.axes?.x !== false, y: options.axes?.y !== false };\n\t\tconst nearest = (lines: readonly LineTarget[], values: number[]) => {\n\t\t\tlet best: { d: number; from: Vec2 } | null = null;\n\t\t\tfor (const v of values) for (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.d)) best = { d: l.v - v, from: l.from };\n\t\t\treturn best;\n\t\t};\n\t\tconst bx = axes.x ? nearest(this.xs, [r.x, r.x + r.width / 2, r.x + r.width]) : null;\n\t\tconst by = axes.y ? nearest(this.ys, [r.y, r.y + r.height / 2, r.y + r.height]) : null;\n\t\tconst out: VectorRectSnap = { dx: bx?.d ?? 0, dy: by?.d ?? 0, x: !!bx, y: !!by, lines: [], labels: [] };\n\t\tconst done = { ...r, x: r.x + out.dx, y: r.y + out.dy };\n\t\tif (bx) {\n\t\t\tconst x = bx.from.x;\n\t\t\tout.lines.push({ kind: 'align', x1: x, y1: Math.min(bx.from.y, done.y), x2: x, y2: Math.max(bx.from.y, done.y + done.height) });\n\t\t}\n\t\tif (by) {\n\t\t\tconst y = by.from.y;\n\t\t\tout.lines.push({ kind: 'align', x1: Math.min(by.from.x, done.x), y1: y, x2: Math.max(by.from.x, done.x + done.width), y2: y });\n\t\t}\n\t\tif (options.spacing && this.boxes.length) {\n\t\t\tfor (const horizontal of [true, false]) {\n\t\t\t\tif (horizontal ? out.x || !axes.x : out.y || !axes.y) continue;\n\t\t\t\tconst moved = { ...r, x: r.x + out.dx, y: r.y + out.dy };\n\t\t\t\tconst even = this.evenSpacing(moved, horizontal, tol);\n\t\t\t\tif (!even) continue;\n\t\t\t\tif (horizontal) {\n\t\t\t\t\tout.dx += even.shift;\n\t\t\t\t\tout.x = true;\n\t\t\t\t} else {\n\t\t\t\t\tout.dy += even.shift;\n\t\t\t\t\tout.y = true;\n\t\t\t\t}\n\t\t\t\tfor (const gap of even.gaps) this.gapMarks(gap, horizontal, tol, out);\n\t\t\t}\n\t\t}\n\t\tif (bx || by) out.labels.unshift(this.label({ x: r.x + out.dx + r.width / 2, y: r.y + out.dy + r.height / 2 }, 'align'));\n\t\treturn out;\n\t}\n\n\t/**\n\t * Equal spacing along x (`horizontal`) or y for the moved box `r`, among the objects of its\n\t * row (column): the shift within `tol` that centres it between its neighbours, or leaves it\n\t * as far from the neighbour before or after it as two other objects of the row are apart;\n\t * and the gaps that are equal then, as (start, end, where across).\n\t */\n\tprivate evenSpacing(r: VectorBounds, horizontal: boolean, tol: number): { shift: number; gaps: [number, number, number][] } | null {\n\t\tconst span = (b: VectorBounds, x: boolean): [number, number] => (x ? [b.x, b.x + b.width] : [b.y, b.y + b.height]);\n\t\tconst [r0, r1] = span(r, horizontal);\n\t\tconst len = r1 - r0;\n\t\tconst [c0, c1] = span(r, !horizontal);\n\t\tconst row = this.boxes\n\t\t\t.map((b) => ({ b, a0: span(b, horizontal)[0], a1: span(b, horizontal)[1] }))\n\t\t\t.filter((e) => span(e.b, !horizontal)[0] < c1 && span(e.b, !horizontal)[1] > c0 && (e.a1 <= r0 + tol || e.a0 >= r1 - tol))\n\t\t\t.sort((a, b) => a.a0 - b.a0);\n\t\tif (!row.length) return null;\n\t\t// Across the middle of what two boxes share (or of the space between them).\n\t\tconst mid = (a: VectorBounds, b: VectorBounds) => (Math.max(span(a, !horizontal)[0], span(b, !horizontal)[0]) + Math.min(span(a, !horizontal)[1], span(b, !horizontal)[1])) / 2;\n\t\tconst pairs: { g: number; gap: [number, number, number] }[] = [];\n\t\tfor (const p of row) {\n\t\t\tconst next = bound(row, (e) => e.a0, p.a1, false);\n\t\t\tconst q = row[next];\n\t\t\tif (!q) continue;\n\t\t\tconst straddles = p.a1 <= r0 + tol && q.a0 >= r1 - tol;\n\t\t\tif (q.a0 > p.a1 && !straddles) pairs.push({ g: q.a0 - p.a1, gap: [p.a1, q.a0, mid(p.b, q.b)] });\n\t\t}\n\t\tlet before: (typeof row)[number] | null = null;\n\t\tlet after: (typeof row)[number] | null = null;\n\t\tfor (const e of row) {\n\t\t\tif (e.a1 <= r0 + tol && (!before || e.a1 > before.a1)) before = e;\n\t\t\tif (e.a0 >= r1 - tol && (!after || e.a0 < after.a0)) after = e;\n\t\t}\n\t\tconst starts: { start: number; repeats: number | null }[] = [];\n\t\tif (before && after && after.a0 - before.a1 > len) starts.push({ start: (before.a1 + after.a0 - len) / 2, repeats: null });\n\t\tfor (const { g } of pairs) {\n\t\t\tif (before) starts.push({ start: before.a1 + g, repeats: g });\n\t\t\tif (after) starts.push({ start: after.a0 - g - len, repeats: g });\n\t\t}\n\t\tlet pick: { start: number; repeats: number | null } | null = null;\n\t\tfor (const s of starts) if (Math.abs(s.start - r0) <= tol && (!pick || Math.abs(s.start - r0) < Math.abs(pick.start - r0))) pick = s;\n\t\tif (!pick) return null;\n\t\tconst { start, repeats } = pick;\n\t\tconst at = horizontal ? { ...r, x: start } : { ...r, y: start };\n\t\tconst end = start + len;\n\t\tconst gaps: [number, number, number][] = [];\n\t\tif (before && (repeats === null || Math.abs(start - before.a1 - repeats) <= EQUAL)) gaps.push([before.a1, start, mid(before.b, at)]);\n\t\tif (after && (repeats === null || Math.abs(after.a0 - end - repeats) <= EQUAL)) gaps.push([end, after.a0, mid(after.b, at)]);\n\t\tif (repeats !== null) for (const p of pairs) if (Math.abs(p.g - repeats) <= EQUAL) gaps.push(p.gap);\n\t\treturn { shift: start - r0, gaps };\n\t}\n\n\t/** A gap mark: a line across the gap with a tick at each end, and its length as a label. */\n\tprivate gapMarks([u0, u1, c]: [number, number, number], horizontal: boolean, tick: number, out: VectorSnapGuides) {\n\t\tconst pt = (u: number, v: number): Vec2 => (horizontal ? { x: u, y: v } : { x: v, y: u });\n\t\tout.lines.push(line('spacing', pt(u0, c), pt(u1, c)), line('spacing', pt(u0, c - tick), pt(u0, c + tick)), line('spacing', pt(u1, c - tick), pt(u1, c + tick)));\n\t\tout.labels.push(this.label(pt((u0 + u1) / 2, c), 'spacing', fmtLength(u1 - u0)));\n\t}\n\n\t/** The other objects' side length nearest `length`, within `tol`, or null. */\n\tmatchSize(length: number, tol: number): number | null {\n\t\tlet best: number | null = null;\n\t\tfor (const s of this.sizes) if (Math.abs(s - length) <= tol && (best === null || Math.abs(s - length) < Math.abs(best - length))) best = s;\n\t\treturn best;\n\t}\n\n\t/**\n\t * Snaps a selection-box resize. `sx / sy` are the scale `scaleFor` gave for dragging\n\t * `handle` of `frame` (in the box's own, possibly rotated frame), `mods.shift` keeps the\n\t * proportions and `mods.alt` scales about the centre. The handle lands on an anchor or\n\t * centre within `tol`, else the corner or the side it moves lines up with the nearest\n\t * target, whatever the box's angle; a handle with one way to go (a side, or a proportional\n\t * corner) slides along it until one of them is on a target. An axis that snaps to nothing\n\t * may match another object's width or height instead.\n\t */\n\tsnapScale(\n\t\tframe: VectorBounds & { angle: number },\n\t\thandle: Exclude<VectorTransformHandle, 'rotate'>,\n\t\tsx: number,\n\t\tsy: number,\n\t\tmods: { shift?: boolean; alt?: boolean },\n\t\ttol: number\n\t): VectorScaleSnap {\n\t\tconst toDoc = frame.angle ? rotateMatrix(frame.angle) : IDENTITY_MATRIX;\n\t\tconst toLocal = frame.angle ? rotateMatrix(-frame.angle) : IDENTITY_MATRIX;\n\t\tconst corner = handle.length === 2;\n\t\tconst proportional = !!mods.shift;\n\t\tconst centre = { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 };\n\t\tconst origin = mods.alt ? centre : handlePos(opposite(handle), frame);\n\t\tconst hp = handlePos(handle, frame);\n\t\tconst d0 = { x: hp.x - origin.x, y: hp.y - origin.y };\n\t\tconst valid = (n: number, s: number) => Number.isFinite(n) && n * s > 0;\n\t\tconst nearest = (v: number, lines: readonly LineTarget[]) => {\n\t\t\tlet best: LineTarget | null = null;\n\t\t\tfor (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.v - v)) best = l;\n\t\t\treturn best;\n\t\t};\n\t\ttype Snap = { hx: LineTarget | null; hy: LineTarget | null; on: PointTarget | null };\n\t\tlet nx = sx;\n\t\tlet ny = sy;\n\t\tlet snap: Snap = { hx: null, hy: null, on: null };\n\t\tif (corner && !proportional) {\n\t\t\t// The corner goes anywhere: onto an anchor or centre, else it takes a target's x, its y, or both.\n\t\t\tconst p = applyMatrix(toDoc, { x: origin.x + d0.x * sx, y: origin.y + d0.y * sy });\n\t\t\tconst hx = nearest(p.x, this.xs);\n\t\t\tconst hy = nearest(p.y, this.ys);\n\t\t\tconst on = this.nearestPoint(p, tol);\n\t\t\tconst tries: { tx: number | null; ty: number | null; s: Snap }[] = [];\n\t\t\tif (on) tries.push({ tx: on.p.x, ty: on.p.y, s: { hx: null, hy: null, on } });\n\t\t\ttries.push({ tx: hx?.v ?? null, ty: hy?.v ?? null, s: { hx, hy, on: null } });\n\t\t\ttries.push({ tx: hx?.v ?? null, ty: null, s: { hx, hy: null, on: null } });\n\t\t\ttries.push({ tx: null, ty: hy?.v ?? null, s: { hx: null, hy, on: null } });\n\t\t\tfor (const { tx, ty, s } of tries) {\n\t\t\t\tif (tx === null && ty === null) continue;\n\t\t\t\tconst q = applyMatrix(toLocal, { x: tx ?? p.x, y: ty ?? p.y });\n\t\t\t\tlet cx = (q.x - origin.x) / d0.x;\n\t\t\t\tlet cy = (q.y - origin.y) / d0.y;\n\t\t\t\t// Square to the page, the axis without a target stays exactly where it was.\n\t\t\t\tif (!frame.angle) {\n\t\t\t\t\tif (tx === null) cx = sx;\n\t\t\t\t\tif (ty === null) cy = sy;\n\t\t\t\t}\n\t\t\t\tif (valid(cx, sx) && valid(cy, sy)) {\n\t\t\t\t\tnx = cx;\n\t\t\t\t\tny = cy;\n\t\t\t\t\tsnap = s;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// One parameter `s`: the scale is `c + s·e` on each axis.\n\t\t\tconst movesX = handle === 'e' || handle === 'w';\n\t\t\tlet e: Vec2;\n\t\t\tlet c: Vec2;\n\t\t\tlet s0: number;\n\t\t\tif (corner) [e, c, s0] = [{ x: Math.sign(sx), y: Math.sign(sy) }, { x: 0, y: 0 }, Math.abs(sx)];\n\t\t\telse if (movesX) [e, c, s0] = proportional ? [{ x: 1, y: Math.sign(sx) }, { x: 0, y: 0 }, sx] : [{ x: 1, y: 0 }, { x: 0, y: 1 }, sx];\n\t\t\telse [e, c, s0] = proportional ? [{ x: Math.sign(sy), y: 1 }, { x: 0, y: 0 }, sy] : [{ x: 0, y: 1 }, { x: 1, y: 0 }, sy];\n\t\t\t// The points that may land on a target: the handle, and the two ends of its side.\n\t\t\tconst i = RING.indexOf(handle);\n\t\t\tconst ends = corner ? [] : [RING[(i + 1) % 8], RING[(i + 7) % 8]];\n\t\t\t// How far the handle travels per unit of `s`: a snap may not drag it far from the pointer.\n\t\t\tconst travel = Math.hypot(e.x * d0.x, e.y * d0.y);\n\t\t\tlet best: { s: number; inLine: boolean; moved: number; snap: Snap } | null = null;\n\t\t\tconst consider = (s: number, inLine: boolean, found: Snap) => {\n\t\t\t\tconst moved = Math.abs(s - s0) * travel;\n\t\t\t\tif (!valid(s, s0) || moved > 2 * tol) return;\n\t\t\t\tif (!best || (inLine === best.inLine ? moved < best.moved : !inLine)) best = { s, inLine, moved, snap: found };\n\t\t\t};\n\t\t\tfor (const h of [handle, ...ends]) {\n\t\t\t\tconst hv = handlePos(h, frame);\n\t\t\t\tconst v = { x: hv.x - origin.x, y: hv.y - origin.y };\n\t\t\t\tconst base = applyMatrix(toDoc, { x: origin.x + c.x * v.x, y: origin.y + c.y * v.y });\n\t\t\t\tconst dir = applyMatrix(toDoc, { x: e.x * v.x, y: e.y * v.y });\n\t\t\t\tconst p = { x: base.x + dir.x * s0, y: base.y + dir.y * s0 };\n\t\t\t\tconst l2 = dir.x * dir.x + dir.y * dir.y;\n\t\t\t\tconst on = l2 > 1e-18 ? this.nearestPoint(p, tol) : null;\n\t\t\t\t// An anchor or centre beside its way: it stops at the nearest point of the way.\n\t\t\t\tif (on) consider(((on.p.x - base.x) * dir.x + (on.p.y - base.y) * dir.y) / l2, false, { hx: null, hy: null, on });\n\t\t\t\tif (Math.abs(dir.x) > 1e-9) {\n\t\t\t\t\tconst hit = nearest(p.x, this.xs);\n\t\t\t\t\tif (hit) consider((hit.v - base.x) / dir.x, true, { hx: hit, hy: null, on: null });\n\t\t\t\t}\n\t\t\t\tif (Math.abs(dir.y) > 1e-9) {\n\t\t\t\t\tconst hit = nearest(p.y, this.ys);\n\t\t\t\t\tif (hit) consider((hit.v - base.y) / dir.y, true, { hx: null, hy: hit, on: null });\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst found = best as { s: number; snap: Snap } | null;\n\t\t\tif (found) {\n\t\t\t\tnx = c.x + found.s * e.x;\n\t\t\t\tny = c.y + found.s * e.y;\n\t\t\t\tsnap = found.snap;\n\t\t\t}\n\t\t}\n\t\tconst out: VectorScaleSnap = { sx: nx, sy: ny, snapped: false, lines: [], labels: [] };\n\t\tconst handleAt = () => applyMatrix(toDoc, { x: origin.x + d0.x * out.sx, y: origin.y + d0.y * out.sy });\n\t\tif (snap.on) {\n\t\t\tout.snapped = true;\n\t\t\tout.labels.push(this.label(snap.on.p, snap.on.kind));\n\t\t\treturn out;\n\t\t}\n\t\t// Sides that line up with nothing may match another object's width or height.\n\t\tconst movesX = handle !== 'n' && handle !== 's';\n\t\tconst movesY = handle !== 'e' && handle !== 'w';\n\t\tconst sized: ('x' | 'y')[] = [];\n\t\tif (!proportional) {\n\t\t\tif (movesX && !snap.hx && !(frame.angle && snap.hy) && frame.width > 1e-9) {\n\t\t\t\tconst len = this.matchSize(Math.abs(out.sx) * frame.width, tol);\n\t\t\t\tif (len !== null && len > 0) {\n\t\t\t\t\tout.sx = Math.sign(out.sx || 1) * (len / frame.width);\n\t\t\t\t\tsized.push('x');\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (movesY && !snap.hy && !(frame.angle && snap.hx) && frame.height > 1e-9) {\n\t\t\t\tconst len = this.matchSize(Math.abs(out.sy) * frame.height, tol);\n\t\t\t\tif (len !== null && len > 0) {\n\t\t\t\t\tout.sy = Math.sign(out.sy || 1) * (len / frame.height);\n\t\t\t\t\tsized.push('y');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// The resized box in its frame, and its corners on the page.\n\t\tconst x0 = origin.x + (frame.x - origin.x) * out.sx;\n\t\tconst x1 = origin.x + (frame.x + frame.width - origin.x) * out.sx;\n\t\tconst y0 = origin.y + (frame.y - origin.y) * out.sy;\n\t\tconst y1 = origin.y + (frame.y + frame.height - origin.y) * out.sy;\n\t\tconst box = { x0: Math.min(x0, x1), x1: Math.max(x0, x1), y0: Math.min(y0, y1), y1: Math.max(y0, y1) };\n\t\tconst page = [\n\t\t\t{ x: box.x0, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y1 },\n\t\t\t{ x: box.x0, y: box.y1 }\n\t\t].map((q) => applyMatrix(toDoc, q));\n\t\tconst pminY = Math.min(...page.map((q) => q.y));\n\t\tconst pmaxY = Math.max(...page.map((q) => q.y));\n\t\tconst pminX = Math.min(...page.map((q) => q.x));\n\t\tconst pmaxX = Math.max(...page.map((q) => q.x));\n\t\tif (snap.hx) out.lines.push({ kind: 'align', x1: snap.hx.v, y1: Math.min(snap.hx.from.y, pminY), x2: snap.hx.v, y2: Math.max(snap.hx.from.y, pmaxY) });\n\t\tif (snap.hy) out.lines.push({ kind: 'align', x1: Math.min(snap.hy.from.x, pminX), y1: snap.hy.v, x2: Math.max(snap.hy.from.x, pmaxX), y2: snap.hy.v });\n\t\tif (snap.hx || snap.hy) {\n\t\t\tout.snapped = true;\n\t\t\tout.labels.push(this.label(handleAt(), 'align'));\n\t\t}\n\t\tfor (const axis of sized) {\n\t\t\tout.snapped = true;\n\t\t\t// Along the matched side, just outside the box.\n\t\t\tconst off = tol * 2;\n\t\t\tconst [a, b] = axis === 'x' ? [{ x: box.x0, y: box.y1 + off }, { x: box.x1, y: box.y1 + off }] : [{ x: box.x1 + off, y: box.y0 }, { x: box.x1 + off, y: box.y1 }];\n\t\t\tconst pa = applyMatrix(toDoc, a);\n\t\t\tconst pb = applyMatrix(toDoc, b);\n\t\t\tout.lines.push(line('size', pa, pb));\n\t\t\tout.labels.push(this.label({ x: (pa.x + pb.x) / 2, y: (pa.y + pb.y) / 2 }, 'size', `${axis === 'x' ? 'W' : 'H'} ${fmtLength(axis === 'x' ? box.x1 - box.x0 : box.y1 - box.y0)}`));\n\t\t}\n\t\treturn out;\n\t}\n}\n\n/** The eight resize handles clockwise from the top left (each side sits between its two corners). */\nconst RING: readonly Exclude<VectorTransformHandle, 'rotate'>[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];\n\nfunction opposite(h: Exclude<VectorTransformHandle, 'rotate'>): Exclude<VectorTransformHandle, 'rotate'> {\n\treturn RING[(RING.indexOf(h) + 4) % 8];\n}\n\nfunction handlePos(h: Exclude<VectorTransformHandle, 'rotate'>, r: VectorBounds): Vec2 {\n\tconst x = h.includes('w') ? r.x : h.includes('e') ? r.x + r.width : r.x + r.width / 2;\n\tconst y = h.startsWith('n') ? r.y : h.startsWith('s') ? r.y + r.height : r.y + r.height / 2;\n\treturn { x, y };\n}\n\nfunction line(kind: VectorGuideKind, a: Vec2, b: Vec2): VectorGuideLine {\n\treturn { kind, x1: a.x, y1: a.y, x2: b.x, y2: b.y };\n}\n\n/** The construction guide through `leave.at` nearest `p`, within `tol` (and `p` farther than that from `at`): its direction and where `p` lands. */\nfunction construction(leave: VectorSnapLeave, p: Vec2, tol: number): { dir: Vec2; point: Vec2 } | null {\n\tconst v = { x: p.x - leave.at.x, y: p.y - leave.at.y };\n\tif (Math.hypot(v.x, v.y) <= tol) return null;\n\tlet best: { dir: Vec2; point: Vec2; d: number } | null = null;\n\tfor (const a of leave.angles ?? []) {\n\t\t// Counter-clockwise as seen on the y-down page.\n\t\tconst r = (a * Math.PI) / 180;\n\t\t// Exactly along an axis for multiples of 90°.\n\t\tconst exact = (n: number) => (Math.abs(n) < 1e-12 ? 0 : n);\n\t\tconst dir = { x: exact(Math.cos(r)), y: exact(-Math.sin(r)) };\n\t\tconst k = v.x * dir.x + v.y * dir.y;\n\t\tconst point = { x: leave.at.x + dir.x * k, y: leave.at.y + dir.y * k };\n\t\tconst d = distance(point, p);\n\t\tif (d <= tol && (!best || d < best.d)) best = { dir, point, d };\n\t}\n\treturn best && { dir: best.dir, point: best.point };\n}\n\nconst dotCondition = (r: Point, d: Point) => r[0] * d[0] + r[1] * d[1];\nconst crossCondition = (r: Point, d: Point) => r[0] * d[1] - r[1] * d[0];\n\n/**\n * The points of a segment where `cond(B(t) − base, B′(t))` is zero: sign changes of samples,\n * narrowed by bisection, kept when the normalised condition is (nearly) zero there.\n */\nfunction solveOnSegment(seg: readonly Point[], base: Vec2, cond: (r: Point, d: Point) => number): Vec2[] {\n\tconst b: Point = [base.x, base.y];\n\tconst g = (t: number) => {\n\t\tconst p = segmentPoint(seg, t);\n\t\treturn cond([p[0] - b[0], p[1] - b[1]], segmentDerivative(seg, t));\n\t};\n\tconst vals: number[] = [];\n\tlet scale = 0;\n\tfor (let i = 0; i <= CURVE_SAMPLES; i++) {\n\t\tconst t = i / CURVE_SAMPLES;\n\t\tconst p = segmentPoint(seg, t);\n\t\tconst d = segmentDerivative(seg, t);\n\t\tconst r: Point = [p[0] - b[0], p[1] - b[1]];\n\t\tvals.push(cond(r, d));\n\t\tscale = Math.max(scale, Math.hypot(r[0], r[1]) * Math.hypot(d[0], d[1]));\n\t}\n\t// Every point qualifies (a line seen from a point on it): no particular solution.\n\tif (!(scale > 0) || vals.every((v) => Math.abs(v) <= scale * 1e-12)) return [];\n\tconst out: Vec2[] = [];\n\tfor (let i = 0; i < CURVE_SAMPLES; i++) {\n\t\tconst ga = vals[i];\n\t\tconst gb = vals[i + 1];\n\t\tif (!(Number.isFinite(ga) && Number.isFinite(gb)) || (ga > 0 === gb > 0 && ga !== 0)) continue;\n\t\tlet lo = i / CURVE_SAMPLES;\n\t\tlet hi = (i + 1) / CURVE_SAMPLES;\n\t\tlet flo = ga;\n\t\tfor (let k = 0; k < BISECT; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = g(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm > 0 === flo > 0) {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t} else hi = m;\n\t\t}\n\t\tconst t = (lo + hi) / 2;\n\t\tconst p = segmentPoint(seg, t);\n\t\tconst dv = segmentDerivative(seg, t);\n\t\tconst r = Math.hypot(p[0] - b[0], p[1] - b[1]);\n\t\tconst dl = Math.hypot(dv[0], dv[1]);\n\t\tif (!(r > 1e-9 && dl > 0) || Math.abs(cond([p[0] - b[0], p[1] - b[1]], dv)) > 1e-6 * r * dl) continue;\n\t\tif (!out.some((q) => Math.hypot(q.x - p[0], q.y - p[1]) <= 1e-9 * (1 + r))) out.push({ x: p[0], y: p[1] });\n\t}\n\treturn out;\n}\n","/**\n * Path editing on subpaths in a node's own space: anchor deletion that keeps the shape,\n * segment bending, Curvature-tool anchor moves, cutting at anchors (Scissors), Join, Average,\n * Remove Redundant Points and Smooth.\n *\n * Portions ported from (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md):\n * - vectorcraft-main/crates/pathops/src/edit.rs (`remove_anchor`, `golden_min`, `smooth`,\n * `remove_redundant_points`, `merge_pair`, `average`, `join`)\n * - vectorcraft-main/crates/geom/src/path.rs (`SubPath::cut_at`)\n * - vectorcraft-main/crates/tools/src/draw2/curvature.rs (`curvature_move`)\n * - figcraft-main/crates/engine/src/vectoredit/ops.rs (`bend`)\n */\nimport type { Point } from '../canvas/types.js';\nimport { fitCubicWithTangents } from '../canvas/curveFit.js';\nimport { segmentPoint } from '../canvas/pathops/bezier.js';\nimport { cloneAnchor, inferAnchorType, insertAnchor, moveAnchorHandle, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath, Vec2 } from './types.js';\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nconst unit = (x: number, y: number): Point | null => {\n\tconst l = Math.hypot(x, y);\n\treturn l > 1e-12 && Number.isFinite(l) ? [x / l, y / l] : null;\n};\n\n/** Segment `i` as four control points (a line has its controls at the thirds of its chord). */\nfunction cubicOf(sp: VectorSubpath, i: number): Point[] {\n\tconst s = subpathSegment(sp, i);\n\tif (s.length === 4) return s;\n\tconst [a, b] = s;\n\treturn [a, [a[0] + (b[0] - a[0]) / 3, a[1] + (b[1] - a[1]) / 3], [a[0] + (2 * (b[0] - a[0])) / 3, a[1] + (2 * (b[1] - a[1])) / 3], b];\n}\n\nconst isLine = (sp: VectorSubpath, i: number) => subpathSegment(sp, i).length === 2;\n\n/** Direction the curve leaves `c[0]`. */\nfunction startTangent(c: readonly Point[]): Point {\n\tfor (let k = 1; k < 4; k++) {\n\t\tconst u = unit(c[k][0] - c[0][0], c[k][1] - c[0][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** Direction the curve arrives at `c[3]` (forward along the curve). */\nfunction endTangent(c: readonly Point[]): Point {\n\tfor (let k = 2; k >= 0; k--) {\n\t\tconst u = unit(c[3][0] - c[k][0], c[3][1] - c[k][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** `n + 1` points of a cubic at even parameters (`withStart` false skips the first). */\nfunction sample(c: readonly Point[], n: number, out: Point[], withStart: boolean) {\n\tfor (let i = withStart ? 0 : 1; i <= n; i++) out.push(segmentPoint(c, i / n));\n}\n\nconst onAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n/** Drops handles that sit on their anchor and sets the type the handles show (a symmetric pair that is no longer equal becomes smooth). */\nfunction tidy(a: VectorAnchor, keepType = true): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tif (onAnchor(next, next.in)) delete next.in;\n\tif (onAnchor(next, next.out)) delete next.out;\n\tconst shown = inferAnchorType(next);\n\tconst type = keepType && a.type ? (a.type === 'symmetric' && shown !== 'symmetric' ? (shown === 'corner' ? 'corner' : 'smooth') : a.type === 'smooth' && shown === 'corner' ? 'corner' : a.type) : shown;\n\tif (type === 'corner') delete next.type;\n\telse next.type = type;\n\treturn next;\n}\n\n/** Index of the anchor before / after `i` (round the start of a closed subpath), or -1. */\nfunction neighbours(sp: VectorSubpath, i: number): [number, number] {\n\tconst n = sp.anchors.length;\n\tconst wrap = sp.closed && n > 1;\n\treturn [i > 0 ? i - 1 : wrap ? n - 1 : -1, i < n - 1 ? i + 1 : wrap ? 0 : -1];\n}\n\n// ---------------------------------------------------------------------------\n// Deleting anchors without changing the shape\n// ---------------------------------------------------------------------------\n\n/**\n * The value of `f` with the least error for an argument in [a, b], by a golden-section search\n * (a fixed number of steps). An error that is not a number never wins.\n */\nfunction goldenMin<T extends { error: number }>(f: (x: number) => T, a: number, b: number): T {\n\tconst R = 0.618033988749895;\n\tlet x1 = b - R * (b - a);\n\tlet x2 = a + R * (b - a);\n\tlet f1 = f(x1);\n\tlet f2 = f(x2);\n\tfor (let i = 0; i < 40; i++) {\n\t\tif (f1.error < f2.error || Number.isNaN(f2.error)) {\n\t\t\tb = x2;\n\t\t\tx2 = x1;\n\t\t\tf2 = f1;\n\t\t\tx1 = b - R * (b - a);\n\t\t\tf1 = f(x1);\n\t\t} else {\n\t\t\ta = x1;\n\t\t\tx1 = x2;\n\t\t\tf1 = f2;\n\t\t\tx2 = a + R * (b - a);\n\t\t\tf2 = f(x2);\n\t\t}\n\t}\n\treturn f1.error <= f2.error ? f1 : f2;\n}\n\n/**\n * One cubic through `pts`: `N + 1` samples of a left curve then `N` of a right one. The new\n * curve passes their joint at some parameter k: the left samples sit at k·i/N, the right ones\n * at k + (1 − k)·i/N. Searches k for the closest fit.\n */\nfunction fitAcross(pts: Point[], N: number, t0: Point, t1: Point) {\n\tconst fit = (k: number) => {\n\t\tconst u: number[] = [];\n\t\tfor (let i = 0; i <= N; i++) u.push((k * i) / N);\n\t\tfor (let i = 1; i <= N; i++) u.push(k + ((1 - k) * i) / N);\n\t\treturn fitCubicWithTangents(pts, u, t0, t1);\n\t};\n\treturn goldenMin(fit, 0, 1);\n}\n\n/**\n * Removes anchor `index` without opening the path: its neighbours keep their handle directions\n * and their facing handles are refitted so one cubic follows the two segments that met there\n * as closely as possible (least maximum error over where the new curve passes the removed\n * point). Two straight segments become one; removing an end of an open subpath drops its\n * segment. Returns the subpath unchanged (a copy) when `index` is out of range.\n */\nexport function removeAnchorKeepingShape(sp: VectorSubpath, index: number): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tif (index < 0 || index >= n) return { anchors, closed: sp.closed };\n\tif ((sp.closed || (index > 0 && index < n - 1)) && n >= 3) {\n\t\tconst pi = (index + n - 1) % n;\n\t\tconst ni = (index + 1) % n;\n\t\tif (!(isLine(sp, pi) && isLine(sp, index))) {\n\t\t\tconst left = cubicOf(sp, pi);\n\t\t\tconst right = cubicOf(sp, index);\n\t\t\tconst N = 16;\n\t\t\tconst pts: Point[] = [];\n\t\t\tsample(left, N, pts, true);\n\t\t\tsample(right, N, pts, false);\n\t\t\tconst t0 = startTangent(left);\n\t\t\tconst t1 = endTangent(right);\n\t\t\tconst { curve } = fitAcross(pts, N, t0, t1);\n\t\t\tif ([curve.p1, curve.p2].every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) {\n\t\t\t\tanchors[pi] = tidy({ ...anchors[pi], out: { x: curve.p1[0], y: curve.p1[1] } });\n\t\t\t\tanchors[ni] = tidy({ ...anchors[ni], in: { x: curve.p2[0], y: curve.p2[1] } });\n\t\t\t}\n\t\t}\n\t}\n\tanchors.splice(index, 1);\n\tlet closed = sp.closed;\n\tif (!closed && anchors.length) {\n\t\t// A new end has nothing beyond it.\n\t\tanchors[0] = tidy({ ...anchors[0], in: null });\n\t\tconst last = anchors.length - 1;\n\t\tanchors[last] = tidy({ ...anchors[last], out: null });\n\t}\n\tif (anchors.length < 3) closed = closed && anchors.length === 2 && anchors.some((a) => a.in || a.out);\n\treturn { anchors, closed };\n}\n\n/** Removes several anchors of a subpath, keeping the shape (see `removeAnchorKeepingShape`). */\nexport function removeAnchorsKeepingShape(sp: VectorSubpath, indices: readonly number[]): VectorSubpath {\n\tconst order = [...new Set(indices)].filter((i) => i >= 0 && i < sp.anchors.length).sort((a, b) => b - a);\n\treturn order.reduce((acc, i) => removeAnchorKeepingShape(acc, i), { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed });\n}\n\n// ---------------------------------------------------------------------------\n// Bending a segment\n// ---------------------------------------------------------------------------\n\n/**\n * Bends segment `segment` so the curve passes through `p` at parameter `t` (clamped to\n * 0.05–0.95): its handles go to the thirds of the chord plus one shared offset, so\n * `B(t) = L(t) + 3t(1 − t)·offset` exactly. The end anchors keep their types (a smooth or\n * symmetric end turns its other handle to stay in line).\n */\nexport function bendSegment(sp: VectorSubpath, segment: number, t: number, p: Vec2): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tif (segment < 0 || segment >= subpathSegmentCount(sp) || !Number.isFinite(t) || !Number.isFinite(p.x) || !Number.isFinite(p.y)) return { anchors, closed: sp.closed };\n\tconst tc = Math.min(0.95, Math.max(0.05, t));\n\tconst ia = segment;\n\tconst ib = (segment + 1) % n;\n\tconst a = anchors[ia];\n\tconst b = anchors[ib];\n\tconst k = 3 * tc * (1 - tc);\n\tconst ox = (p.x - (a.x + (b.x - a.x) * tc)) / k;\n\tconst oy = (p.y - (a.y + (b.y - a.y) * tc)) / k;\n\tconst c1 = { x: a.x + (b.x - a.x) / 3 + ox, y: a.y + (b.y - a.y) / 3 + oy };\n\tconst c2 = { x: b.x + (a.x - b.x) / 3 + ox, y: b.y + (a.y - b.y) / 3 + oy };\n\tanchors[ia] = moveAnchorHandle(a, 'out', c1);\n\tanchors[ib] = moveAnchorHandle(b, 'in', c2);\n\treturn { anchors, closed: sp.closed };\n}\n\n/** The point at parameter `t` of segment `segment` (for tests and previews). */\nexport function subpathPointAt(sp: VectorSubpath, segment: number, t: number): Vec2 {\n\tconst [x, y] = segmentPoint(subpathSegment(sp, segment), t);\n\treturn { x, y };\n}\n\n// ---------------------------------------------------------------------------\n// Curvature-tool anchor move\n// ---------------------------------------------------------------------------\n\n/**\n * Moves anchor `index` to `q` the way the Curvature tool drags a point: only the two segments\n * at it change. A smooth or symmetric anchor turns its handles along the line through its\n * neighbours; the neighbours' handles on those segments, and a corner's own handles, keep\n * their directions while their lengths scale with their segment's chord, so the segments\n * beyond don't move and a corner without handles keeps none.\n */\nexport function curvatureMoveAnchor(sp: VectorSubpath, index: number, q: Vec2): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst a = sp.anchors[index];\n\tif (!a) return { anchors, closed: sp.closed };\n\tconst own: [Vec2 | null, Vec2 | null] = [\n\t\ta.in && !onAnchor(a, a.in) ? { x: a.in.x - a.x, y: a.in.y - a.y } : null,\n\t\ta.out && !onAnchor(a, a.out) ? { x: a.out.x - a.x, y: a.out.y - a.y } : null\n\t];\n\tconst ends: [Vec2 | null, Vec2 | null] = [null, null];\n\tneighbours(sp, index).forEach((j, side) => {\n\t\tif (j < 0 || j === index) return;\n\t\tconst b = anchors[j];\n\t\tconst old = Math.hypot(a.x - b.x, a.y - b.y);\n\t\tconst s = old > 1e-9 ? Math.hypot(q.x - b.x, q.y - b.y) / old : 1;\n\t\tconst key = side === 0 ? 'out' : 'in';\n\t\tconst h = b[key];\n\t\tif (h) b[key] = { x: b.x + (h.x - b.x) * s, y: b.y + (h.y - b.y) * s };\n\t\tconst o = own[side];\n\t\tif (o) own[side] = { x: o.x * s, y: o.y * s };\n\t\tends[side] = { x: b.x, y: b.y };\n\t});\n\tconst moved: VectorAnchor = { x: q.x, y: q.y };\n\tif (own[0]) moved.in = { x: q.x + own[0].x, y: q.y + own[0].y };\n\tif (own[1]) moved.out = { x: q.x + own[1].x, y: q.y + own[1].y };\n\tif (a.type) moved.type = a.type;\n\tif (a.corner) moved.corner = { ...a.corner };\n\tconst [prev, next] = ends;\n\tif (a.type && a.type !== 'corner' && prev && next) {\n\t\tconst dx = next.x - prev.x;\n\t\tconst dy = next.y - prev.y;\n\t\tconst l = Math.hypot(dx, dy);\n\t\tif (l > 1e-9) {\n\t\t\t// A handle it lacks comes out a third of the way to that side's neighbour.\n\t\t\tconst len = (h: Vec2 | null, to: Vec2) => (h ? Math.hypot(h.x, h.y) : Math.hypot(q.x - to.x, q.y - to.y) / 3);\n\t\t\tlet li = len(own[0], prev);\n\t\t\tlet lo = len(own[1], next);\n\t\t\tif (a.type === 'symmetric') li = lo = (li + lo) / 2;\n\t\t\tmoved.in = { x: q.x - (dx * li) / l, y: q.y - (dy * li) / l };\n\t\t\tmoved.out = { x: q.x + (dx * lo) / l, y: q.y + (dy * lo) / l };\n\t\t}\n\t}\n\tanchors[index] = moved;\n\treturn { anchors, closed: sp.closed };\n}\n\n// ---------------------------------------------------------------------------\n// Scissors\n// ---------------------------------------------------------------------------\n\n/**\n * Cuts a subpath at the anchors `at`: each becomes the end of one open piece and the start of\n * the next, its handle off each piece dropped (the shape doesn't change). A closed subpath\n * opens at its first cut, so one cut leaves one piece whose ends coincide. The ends of an open\n * subpath and indices out of range don't cut; with no cut left the subpath comes back as it is.\n */\nexport function cutSubpathAt(sp: VectorSubpath, at: readonly number[]): VectorSubpath[] {\n\tconst n = sp.anchors.length;\n\tconst cuts = [...new Set(at)].filter((i) => Number.isInteger(i) && i >= 0 && i < n && (sp.closed || (i > 0 && i < n - 1))).sort((a, b) => a - b);\n\tif (!cuts.length || n < 2) return [{ anchors: sp.anchors.map(cloneAnchor), closed: sp.closed }];\n\tconst first = cuts[0];\n\t// A closed subpath's anchors from the first cut round to it again; an open one's as they are.\n\tconst run = sp.closed ? Array.from({ length: n + 1 }, (_, i) => sp.anchors[(first + i) % n]) : sp.anchors;\n\tconst cutSet = new Set(sp.closed ? [...cuts.map((c) => (c - first + n) % n), n] : cuts);\n\tconst pieces: VectorSubpath[] = [];\n\tlet cur: VectorAnchor[] = [];\n\trun.forEach((a, i) => {\n\t\tif (!cutSet.has(i)) {\n\t\t\tcur.push(cloneAnchor(a));\n\t\t\treturn;\n\t\t}\n\t\tif (cur.length) {\n\t\t\tcur.push(tidy({ ...a, out: null }, false));\n\t\t\tpieces.push({ anchors: cur, closed: false });\n\t\t\tcur = [];\n\t\t}\n\t\tif (i < n) cur.push(tidy({ ...a, in: null }, false));\n\t});\n\tif (cur.length > 1) pieces.push({ anchors: cur, closed: false });\n\treturn pieces;\n}\n\n/**\n * Cuts a subpath at parameter `t` of segment `segment` (Scissors on a segment): an anchor is\n * inserted there without changing the shape, then cut. Within `endTolerance` of the segment's\n * ends (in parameter) the existing anchor is cut instead.\n */\nexport function splitSubpathAt(sp: VectorSubpath, segment: number, t: number, endTolerance = 1e-6): VectorSubpath[] {\n\tconst n = sp.anchors.length;\n\tif (segment < 0 || segment >= subpathSegmentCount(sp)) return [{ anchors: sp.anchors.map(cloneAnchor), closed: sp.closed }];\n\tif (t <= endTolerance) return cutSubpathAt(sp, [segment]);\n\tif (t >= 1 - endTolerance) return cutSubpathAt(sp, [(segment + 1) % n]);\n\tconst { subpath, index } = insertAnchor(sp, segment, t);\n\treturn cutSubpathAt(subpath, [index]);\n}\n\n// ---------------------------------------------------------------------------\n// Join\n// ---------------------------------------------------------------------------\n\nconst endOf = (sp: VectorSubpath, last: boolean): VectorAnchor => sp.anchors[last ? sp.anchors.length - 1 : 0];\nconst dist = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\n\nfunction reverse(sp: VectorSubpath): VectorSubpath {\n\treturn {\n\t\tclosed: sp.closed,\n\t\tanchors: sp.anchors\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.map((a) => {\n\t\t\t\tconst next: VectorAnchor = { x: a.x, y: a.y };\n\t\t\t\tif (a.out) next.in = { ...a.out };\n\t\t\t\tif (a.in) next.out = { ...a.in };\n\t\t\t\tif (a.type) next.type = a.type;\n\t\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\t\treturn next;\n\t\t\t})\n\t};\n}\n\n/**\n * Join: open subpaths are joined nearest-endpoints-first into one open subpath (endpoints\n * within `tolerance` merge into one anchor, otherwise a straight segment connects them). A\n * single open subpath is closed instead (its ends merged when they meet). Closed subpaths and\n * lone anchors pass through unchanged, before the joined one.\n */\nexport function joinSubpaths(subpaths: readonly VectorSubpath[], tolerance: number): VectorSubpath[] {\n\tconst closed: VectorSubpath[] = [];\n\tlet open: VectorSubpath[] = [];\n\tfor (const sp of subpaths) {\n\t\tconst copy = { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n\t\tif (sp.closed || sp.anchors.length < 2) {\n\t\t\tif (sp.anchors.length) closed.push(copy);\n\t\t} else open.push(copy);\n\t}\n\tif (open.length === 1) {\n\t\tconst sp = open[0];\n\t\tconst first = sp.anchors[0];\n\t\tconst last = sp.anchors[sp.anchors.length - 1];\n\t\tif (sp.anchors.length > 2 && dist(first, last) <= tolerance) {\n\t\t\tsp.anchors.pop();\n\t\t\tsp.anchors[0] = tidy({ ...first, in: last.in ?? null }, false);\n\t\t} else {\n\t\t\tsp.anchors[0] = tidy({ ...first, in: null }, false);\n\t\t\tsp.anchors[sp.anchors.length - 1] = tidy({ ...sp.anchors[sp.anchors.length - 1], out: null }, false);\n\t\t}\n\t\tsp.closed = true;\n\t\treturn [...closed, sp];\n\t}\n\twhile (open.length > 1) {\n\t\t// The closest pair of endpoints on different subpaths.\n\t\tlet best = { d: Infinity, i: 0, j: 1, ei: true, ej: false };\n\t\tfor (let i = 0; i < open.length; i++) {\n\t\t\tfor (let j = i + 1; j < open.length; j++) {\n\t\t\t\tfor (const ei of [false, true]) {\n\t\t\t\t\tfor (const ej of [false, true]) {\n\t\t\t\t\t\tconst d = dist(endOf(open[i], ei), endOf(open[j], ej));\n\t\t\t\t\t\tif (d < best.d) best = { d, i, j, ei, ej };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet a = open[best.i];\n\t\tlet b = open[best.j];\n\t\topen = open.filter((_, k) => k !== best.j);\n\t\t// `a` ends at the meeting point, `b` starts there.\n\t\tif (!best.ei) a = reverse(a);\n\t\tif (best.ej) b = reverse(b);\n\t\tconst anchors = a.anchors;\n\t\tif (best.d <= tolerance) {\n\t\t\tconst [head, ...rest] = b.anchors;\n\t\t\tconst l = anchors[anchors.length - 1];\n\t\t\tanchors[anchors.length - 1] = tidy({ ...l, out: head.out ?? null }, false);\n\t\t\tanchors.push(...rest);\n\t\t} else {\n\t\t\tconst l = anchors[anchors.length - 1];\n\t\t\tanchors[anchors.length - 1] = tidy({ ...l, out: null }, false);\n\t\t\tanchors.push(tidy({ ...b.anchors[0], in: null }, false), ...b.anchors.slice(1));\n\t\t}\n\t\topen[best.i > best.j ? best.i - 1 : best.i] = { anchors, closed: false };\n\t}\n\treturn [...closed, ...open];\n}\n\n// ---------------------------------------------------------------------------\n// Smooth and Remove Redundant Points\n// ---------------------------------------------------------------------------\n\n/**\n * Smooth: pulls handles towards Catmull-Rom-like tangents (a third of the way to each\n * neighbour along the line through both). `amount` 0–1 (0 = unchanged, 1 = fully smooth).\n * Only the anchors in `only` change when it is given; endpoints of open subpaths keep their\n * handles. Subpaths of fewer than three anchors are unchanged.\n */\nexport function smoothSubpath(sp: VectorSubpath, amount = 1, only?: ReadonlySet<number>): VectorSubpath {\n\tconst t = Math.min(1, Math.max(0, amount));\n\tconst orig = sp.anchors;\n\tconst n = orig.length;\n\tconst anchors = orig.map(cloneAnchor);\n\tif (n < 3 || t === 0) return { anchors, closed: sp.closed };\n\tfor (let i = 0; i < n; i++) {\n\t\tif (!sp.closed && (i === 0 || i === n - 1)) continue;\n\t\tif (only && !only.has(i)) continue;\n\t\tconst prev = orig[(i + n - 1) % n];\n\t\tconst next = orig[(i + 1) % n];\n\t\tconst p = orig[i];\n\t\tconst dir = unit(next.x - prev.x, next.y - prev.y);\n\t\tif (!dir) continue;\n\t\tconst li = dist(p, prev) / 3;\n\t\tconst lo = dist(p, next) / 3;\n\t\tconst hin = p.in ?? p;\n\t\tconst hout = p.out ?? p;\n\t\tconst target = (h: Vec2, x: number, y: number) => ({ x: h.x + (x - h.x) * t, y: h.y + (y - h.y) * t });\n\t\tanchors[i] = tidy(\n\t\t\t{\n\t\t\t\tx: p.x,\n\t\t\t\ty: p.y,\n\t\t\t\tin: target(hin, p.x - dir[0] * li, p.y - dir[1] * li),\n\t\t\t\tout: target(hout, p.x + dir[0] * lo, p.y + dir[1] * lo)\n\t\t\t},\n\t\t\tfalse\n\t\t);\n\t}\n\treturn { anchors, closed: sp.closed };\n}\n\ninterface Seg {\n\tc: Point[];\n\tline: boolean;\n}\n\nfunction segsOf(sp: VectorSubpath): Seg[] {\n\tconst out: Seg[] = [];\n\tfor (let i = 0; i < subpathSegmentCount(sp); i++) {\n\t\tconst s = subpathSegment(sp, i);\n\t\tout.push(s.length === 2 ? { c: s, line: true } : { c: s, line: false });\n\t}\n\treturn out;\n}\n\n/** A subpath from consecutive segments (anchor types inferred; original types kept where they still hold). */\nfunction segsToSubpath(segs: readonly Seg[], closed: boolean, types: Map<string, VectorAnchor['type']>): VectorSubpath | null {\n\tif (!segs.length) return null;\n\tconst anchors: VectorAnchor[] = [];\n\tconst at = (p: Point): VectorAnchor => ({ x: p[0], y: p[1] });\n\tanchors.push(at(segs[0].c[0]));\n\tfor (const s of segs) {\n\t\tconst end = s.c[s.c.length - 1];\n\t\tif (!s.line) anchors[anchors.length - 1].out = { x: s.c[1][0], y: s.c[1][1] };\n\t\tconst next = at(end);\n\t\tif (!s.line) next.in = { x: s.c[2][0], y: s.c[2][1] };\n\t\tanchors.push(next);\n\t}\n\tif (closed) {\n\t\tconst last = anchors.pop()!;\n\t\tif (last.in) anchors[0].in = last.in;\n\t}\n\tconst typed = anchors.map((a) => {\n\t\tconst type = types.get(`${a.x},${a.y}`);\n\t\treturn tidy(type ? { ...a, type } : a, !!type);\n\t});\n\treturn { anchors: typed, closed };\n}\n\nconst isZeroSeg = (s: Seg) => s.c.every((p) => Math.abs(p[0] - s.c[0][0]) < 1e-9 && Math.abs(p[1] - s.c[0][1]) < 1e-9);\n\n/** One segment replacing `a` then `b` within `tol`, or null. */\nfunction mergePair(a: Seg, b: Seg, tol: number): Seg | null {\n\tconst a0 = a.c[0];\n\tconst a3 = a.c[a.c.length - 1];\n\tconst b3 = b.c[b.c.length - 1];\n\tif (a.line && b.line) {\n\t\tconst cx = b3[0] - a0[0];\n\t\tconst cy = b3[1] - a0[1];\n\t\tconst len = Math.hypot(cx, cy);\n\t\tif (len < 1e-12) return null;\n\t\tconst mx = a3[0] - a0[0];\n\t\tconst my = a3[1] - a0[1];\n\t\tconst along = (mx * cx + my * cy) / len;\n\t\treturn Math.abs((mx * cy - my * cx) / len) <= tol && along >= 0 && along <= len ? { c: [a0, b3], line: true } : null;\n\t}\n\tconst ca = a.line ? [a0, a0, a3, a3] : a.c;\n\tconst cb = b.line ? [a3, a3, b3, b3] : b.c;\n\tconst ta = endTangent(ca);\n\tconst tb = startTangent(cb);\n\t// Only merge across (near-)smooth joints.\n\tif (ta[0] * tb[0] + ta[1] * tb[1] < 0.99) return null;\n\tconst pts: Point[] = [];\n\tsample(ca, 16, pts, true);\n\tsample(cb, 16, pts, false);\n\tconst { curve, error } = fitAcross(pts, 16, startTangent(ca), endTangent(cb));\n\treturn error <= tol ? { c: [curve.p0, curve.p1, curve.p2, curve.p3], line: false } : null;\n}\n\n/**\n * Remove Redundant Points: drops anchors that can go without changing the shape by more than\n * `tolerance` (collinear corners, duplicate points, and smooth joints that one cubic can\n * replace).\n */\nexport function removeRedundantPoints(sp: VectorSubpath, tolerance: number): VectorSubpath {\n\tconst tol = Math.max(tolerance, 1e-9);\n\tconst types = new Map(sp.anchors.filter((a) => a.type).map((a) => [`${a.x},${a.y}`, a.type] as const));\n\tconst segs = segsOf(sp).filter((s) => !isZeroSeg(s));\n\tif (!segs.length) return { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n\tconst minSegs = sp.closed ? 2 : 1;\n\tlet changed = true;\n\twhile (changed && segs.length > minSegs) {\n\t\tchanged = false;\n\t\tconst n = segs.length;\n\t\tconst joints = sp.closed ? n : n - 1;\n\t\tfor (let j = 0; j < joints; j++) {\n\t\t\tconst [i0, i1] = sp.closed ? [(j + n - 1) % n, j] : [j, j + 1];\n\t\t\tconst m = mergePair(segs[i0], segs[i1], tol);\n\t\t\tif (!m) continue;\n\t\t\tsegs[i0] = m;\n\t\t\tsegs.splice(i1, 1);\n\t\t\t// The merged segment now starts the loop.\n\t\t\tif (sp.closed && i1 === 0) segs.unshift(segs.pop()!);\n\t\t\tchanged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn segsToSubpath(segs, sp.closed, types) ?? { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n}\n","/**\n * Knife and eraser on Bézier paths, built on the curve booleans and `outlineStroke`.\n *\n * The knife cuts filled regions along a polyline with no gap: each stretch of the polyline\n * that crosses a region from boundary to boundary (a chord) splits the boundary loop it starts\n * and ends on into two loops sharing that chord, or, when it joins two loops (an outline and a\n * hole), merges them into one. Crossings are exact (line–cubic roots), and the pieces share\n * the cut edge exactly.\n *\n * The eraser removes the area of a round-capped stroke along a polyline: filled shapes lose it\n * by a boolean difference; outlines are cut where they cross the stroke's outline (exact\n * curve–curve intersections) and keep the parts outside it.\n *\n * Modelled on vectorcraft-main/crates/engine/src/cmd/draw2.rs (`knife`, `erase_region`,\n * `erase_outline`, `cut_subpath`; MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md), without its fixed knife slit and its sampled crossing search.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcloseContour,\n\tcontourSignedArea,\n\tcontoursToPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentBounds,\n\tsegmentPoint,\n\tsubSegment,\n\twindingNumber,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport { normalizeBezierPath, pathBoolean, segmentIntersections } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport { inferAnchorType, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath } from './types.js';\n\ntype FillRule = 'nonzero' | 'evenodd';\n\n// ---------------------------------------------------------------------------\n// Faces: an outer loop with its holes\n// ---------------------------------------------------------------------------\n\ninterface Loop {\n\tsegs: Point[][];\n\t/** Which segments came from a knife chord (not sampled for containment). */\n\tchord: boolean[];\n}\n\ninterface Face {\n\tloops: Loop[];\n}\n\nconst loopArea = (l: Loop) => contourSignedArea(l.segs);\n\n/** A point on the loop that is not on a chord (chords are shared with a neighbouring piece). */\nfunction loopSample(l: Loop): Point {\n\tconst k = l.chord.findIndex((c) => !c);\n\treturn segmentPoint(l.segs[k >= 0 ? k : 0], 0.5);\n}\n\nconst contains = (l: Loop, p: Point) => windingNumber([l.segs], p) !== 0;\n\n/**\n * Groups non-crossing loops into faces: loops turning like the largest one are outlines, the\n * others holes of the smallest outline around them.\n */\nfunction groupFaces(loops: Loop[]): Face[] {\n\tconst usable = loops.filter((l) => l.segs.length && Math.abs(loopArea(l)) > 1e-12);\n\tif (!usable.length) return [];\n\tconst largest = usable.reduce((a, b) => (Math.abs(loopArea(b)) > Math.abs(loopArea(a)) ? b : a));\n\tconst sign = Math.sign(loopArea(largest));\n\tconst outers = usable.filter((l) => Math.sign(loopArea(l)) === sign).sort((a, b) => Math.abs(loopArea(a)) - Math.abs(loopArea(b)));\n\tconst faces = new Map<Loop, Face>(outers.map((o) => [o, { loops: [o] }]));\n\tfor (const hole of usable.filter((l) => Math.sign(loopArea(l)) !== sign)) {\n\t\tconst p = loopSample(hole);\n\t\tconst parent = outers.find((o) => Math.abs(loopArea(o)) > Math.abs(loopArea(hole)) && contains(o, p));\n\t\tif (parent) faces.get(parent)!.loops.push(hole);\n\t}\n\treturn outers.reverse().map((o) => faces.get(o)!);\n}\n\nfunction faceToPath(face: Face): BezierPath {\n\treturn contoursToPath(face.loops.map((l) => ({ segments: l.segs, closed: true })));\n}\n\n/** Simple, consistently oriented faces of a filled path. */\nfunction facesOf(path: BezierPathInput, fillRule: FillRule): Face[] {\n\tconst normalized = normalizeBezierPath(path, fillRule);\n\tconst loops = pathToContours(normalized).map((c) => {\n\t\tconst segs = closeContour(c, true).map((s) => s.slice());\n\t\treturn { segs, chord: segs.map(() => false) };\n\t});\n\treturn groupFaces(loops);\n}\n\n/** One path per face (an outline with its holes) of a filled path, largest first. */\nexport function splitIntoFaces(path: BezierPathInput, fillRule: FillRule = 'nonzero'): BezierPath[] {\n\treturn facesOf(path, fillRule).map(faceToPath);\n}\n\n// ---------------------------------------------------------------------------\n// Line × segment crossings\n// ---------------------------------------------------------------------------\n\n/** Real roots in [0, 1] of `a·t³ + b·t² + c·t + d` (monotone pieces, bisection). */\nfunction rootsInUnit(a: number, b: number, c: number, d: number, scale: number): number[] {\n\tconst f = (t: number) => ((a * t + b) * t + c) * t + d;\n\tconst tol = 1e-12 * Math.max(1, scale);\n\t// Critical points split [0, 1] into monotone pieces.\n\tconst cuts = [0];\n\tconst qa = 3 * a;\n\tconst qb = 2 * b;\n\tif (Math.abs(qa) > 1e-18) {\n\t\tconst disc = qb * qb - 4 * qa * c;\n\t\tif (disc >= 0) {\n\t\t\tconst r = Math.sqrt(disc);\n\t\t\tfor (const t of [(-qb - r) / (2 * qa), (-qb + r) / (2 * qa)].sort((x, y) => x - y)) if (t > 0 && t < 1) cuts.push(t);\n\t\t}\n\t} else if (Math.abs(qb) > 1e-18) {\n\t\tconst t = -c / qb;\n\t\tif (t > 0 && t < 1) cuts.push(t);\n\t}\n\tcuts.push(1);\n\tconst roots: number[] = [];\n\tconst push = (t: number) => {\n\t\tif (!roots.some((r) => Math.abs(r - t) < 1e-9)) roots.push(t);\n\t};\n\tfor (let i = 0; i < cuts.length - 1; i++) {\n\t\tlet lo = cuts[i];\n\t\tlet hi = cuts[i + 1];\n\t\tlet flo = f(lo);\n\t\tconst fhi = f(hi);\n\t\tif (Math.abs(flo) <= tol) push(lo);\n\t\tif (Math.abs(fhi) <= tol) push(hi);\n\t\tif (flo * fhi >= 0) continue;\n\t\tfor (let k = 0; k < 80; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = f(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm * flo < 0) hi = m;\n\t\t\telse {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t}\n\t\t}\n\t\tpush((lo + hi) / 2);\n\t}\n\treturn roots.sort((x, y) => x - y);\n}\n\n/** Where the line `p → q` crosses a segment: `s` on the line (0–1), `t` on the segment. Parallel overlaps are not crossings. */\nfunction lineHits(p: Point, q: Point, seg: readonly Point[]): { s: number; t: number; point: Point }[] {\n\tconst dx = q[0] - p[0];\n\tconst dy = q[1] - p[1];\n\tconst len2 = dx * dx + dy * dy;\n\tif (len2 < 1e-24) return [];\n\t// Signed distance (times |d|) of the segment from the line, as a polynomial in t.\n\tconst h = (pt: Point) => (pt[0] - p[0]) * -dy + (pt[1] - p[1]) * dx;\n\tlet coeffs: [number, number, number, number];\n\tif (seg.length === 2) coeffs = [0, 0, h(seg[1]) - h(seg[0]), h(seg[0])];\n\telse {\n\t\tconst [h0, h1, h2, h3] = seg.map(h);\n\t\tcoeffs = [-h0 + 3 * h1 - 3 * h2 + h3, 3 * h0 - 6 * h1 + 3 * h2, -3 * h0 + 3 * h1, h0];\n\t}\n\tif (coeffs.every((c) => Math.abs(c) < 1e-12 * Math.max(1, len2))) return [];\n\tconst scale = Math.sqrt(len2) * Math.max(1, ...seg.map((pt) => Math.abs(pt[0]) + Math.abs(pt[1])));\n\tconst out: { s: number; t: number; point: Point }[] = [];\n\tfor (const t of rootsInUnit(...coeffs, scale)) {\n\t\tconst point = segmentPoint(seg, t);\n\t\tconst s = ((point[0] - p[0]) * dx + (point[1] - p[1]) * dy) / len2;\n\t\tif (s >= -1e-9 && s <= 1 + 1e-9) out.push({ s: Math.min(1, Math.max(0, s)), t, point });\n\t}\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Knife\n// ---------------------------------------------------------------------------\n\ninterface Hit {\n\t/** Knife position: segment index + parameter. */\n\ts: number;\n\tloop: number;\n\tseg: number;\n\tt: number;\n\tpoint: Point;\n}\n\nconst near = (a: Point, b: Point, eps: number) => Math.abs(a[0] - b[0]) <= eps && Math.abs(a[1] - b[1]) <= eps;\nconst degenerate = (seg: readonly Point[], eps: number) => seg.every((p) => near(p, seg[0], eps));\n\n/** The loop's pieces from (seg a, t a) forward to (seg b, t b); `full` goes all the way round when they coincide. */\nfunction arc(l: Loop, a: { seg: number; t: number }, b: { seg: number; t: number }, eps: number): { segs: Point[][]; chord: boolean[] } {\n\tconst n = l.segs.length;\n\tconst segs: Point[][] = [];\n\tconst chord: boolean[] = [];\n\tconst push = (k: number, t0: number, t1: number) => {\n\t\tconst piece = t0 <= 0 && t1 >= 1 ? l.segs[k].slice() : subSegment(l.segs[k], t0, t1);\n\t\tif (!degenerate(piece, eps)) {\n\t\t\tsegs.push(piece);\n\t\t\tchord.push(l.chord[k]);\n\t\t}\n\t};\n\tif (a.seg === b.seg && b.t >= a.t + 1e-12) {\n\t\tpush(a.seg, a.t, b.t);\n\t\treturn { segs, chord };\n\t}\n\tpush(a.seg, a.t, 1);\n\tfor (let k = (a.seg + 1) % n; k !== b.seg; k = (k + 1) % n) push(k, 0, 1);\n\tpush(b.seg, 0, b.t);\n\treturn { segs, chord };\n}\n\n/** Line segments through `points`. */\nfunction polySegs(points: readonly Point[], eps: number): Point[][] {\n\tconst out: Point[][] = [];\n\tfor (let i = 1; i < points.length; i++) if (!near(points[i - 1], points[i], eps)) out.push([points[i - 1], points[i]]);\n\treturn out;\n}\n\n/**\n * Cuts the filled path along the open polyline `knife`. Returns one path per resulting face\n * (an outline with its holes), or null when the knife crossed nothing from edge to edge. A\n * stretch of the knife that starts or ends inside the shape does not cut.\n */\nexport function knifePath(path: BezierPathInput, fillRule: FillRule, knife: readonly Point[]): BezierPath[] | null {\n\tconst pts = knife.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tif (pts.length < 2) return null;\n\tlet faces = facesOf(path, fillRule);\n\tif (!faces.length) return null;\n\tconst b = bezierPathBounds(path);\n\tconst size = b ? Math.max(b.maxX - b.minX, b.maxY - b.minY, 1) : 1;\n\tconst eps = size * 1e-9;\n\tlet cursor = -Infinity;\n\tlet cuts = 0;\n\tfor (let guard = 0; guard < 512; guard++) {\n\t\tlet best: { face: number; from: Hit; to: Hit } | null = null;\n\t\tfaces.forEach((face, fi) => {\n\t\t\tconst hits: Hit[] = [];\n\t\t\tfor (let m = 0; m < pts.length - 1; m++) {\n\t\t\t\tif (m + 1 < cursor - 1e-9) continue;\n\t\t\t\tconst kb = { minX: Math.min(pts[m][0], pts[m + 1][0]), maxX: Math.max(pts[m][0], pts[m + 1][0]), minY: Math.min(pts[m][1], pts[m + 1][1]), maxY: Math.max(pts[m][1], pts[m + 1][1]) };\n\t\t\t\tface.loops.forEach((l, li) =>\n\t\t\t\t\tl.segs.forEach((seg, si) => {\n\t\t\t\t\t\tconst sb = segmentBounds(seg);\n\t\t\t\t\t\tif (sb.maxX < kb.minX - eps || sb.minX > kb.maxX + eps || sb.maxY < kb.minY - eps || sb.minY > kb.maxY + eps) return;\n\t\t\t\t\t\tfor (const h of lineHits(pts[m], pts[m + 1], seg)) {\n\t\t\t\t\t\t\tconst s = m + h.s;\n\t\t\t\t\t\t\tif (s >= cursor - 1e-9) hits.push({ s, loop: li, seg: si, t: h.t, point: h.point });\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\thits.sort((x, y) => x.s - y.s);\n\t\t\tconst unique = hits.filter((h, i) => i === 0 || h.s - hits[i - 1].s > 1e-9 || !near(h.point, hits[i - 1].point, eps * 10));\n\t\t\tconst inside = (s: number) => {\n\t\t\t\tconst m = Math.min(pts.length - 2, Math.floor(s));\n\t\t\t\tconst u = s - m;\n\t\t\t\tconst q: Point = [pts[m][0] + (pts[m + 1][0] - pts[m][0]) * u, pts[m][1] + (pts[m + 1][1] - pts[m][1]) * u];\n\t\t\t\treturn windingNumber(face.loops.map((l) => l.segs), q) !== 0;\n\t\t\t};\n\t\t\tfor (let i = 0; i < unique.length - 1; i++) {\n\t\t\t\tconst from = unique[i];\n\t\t\t\tconst to = unique[i + 1];\n\t\t\t\tif (near(from.point, to.point, eps * 10) || !inside((from.s + to.s) / 2)) continue;\n\t\t\t\tif (!best || from.s < best.from.s) best = { face: fi, from, to };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tif (!best) break;\n\t\tconst { face: fi, from, to } = best as { face: number; from: Hit; to: Hit };\n\t\tconst face = faces[fi];\n\t\t// The chord: the crossing points with the knife's corners between them.\n\t\tconst corners: Point[] = [from.point];\n\t\tfor (let m = Math.floor(from.s) + 1; m <= to.s - 1e-12 && m < pts.length; m++) if (m > from.s) corners.push(pts[m]);\n\t\tcorners.push(to.point);\n\t\tconst forward = polySegs(corners, eps);\n\t\tconst back = polySegs(corners.slice().reverse(), eps);\n\t\tconst la = face.loops[from.loop];\n\t\tconst loops = face.loops.filter((_, i) => i !== from.loop && i !== to.loop);\n\t\tif (from.loop === to.loop) {\n\t\t\tconst ab = arc(la, from, to, eps);\n\t\t\tconst ba = arc(la, to, from, eps);\n\t\t\tloops.push(\n\t\t\t\t{ segs: [...ab.segs, ...back], chord: [...ab.chord, ...back.map(() => true)] },\n\t\t\t\t{ segs: [...ba.segs, ...forward], chord: [...ba.chord, ...forward.map(() => true)] }\n\t\t\t);\n\t\t} else {\n\t\t\t// The chord joins two loops into one, with the chord on both sides of a zero-width slit.\n\t\t\tconst lb = face.loops[to.loop];\n\t\t\tconst roundA = arc(la, from, from, eps);\n\t\t\tconst roundB = arc(lb, to, to, eps);\n\t\t\tloops.push({\n\t\t\t\tsegs: [...roundA.segs, ...forward, ...roundB.segs, ...back],\n\t\t\t\tchord: [...roundA.chord, ...forward.map(() => true), ...roundB.chord, ...back.map(() => true)]\n\t\t\t});\n\t\t}\n\t\tfaces = [...faces.slice(0, fi), ...groupFaces(loops), ...faces.slice(fi + 1)];\n\t\tcursor = to.s;\n\t\tcuts++;\n\t}\n\treturn cuts ? faces.map(faceToPath) : null;\n}\n\n// ---------------------------------------------------------------------------\n// Eraser\n// ---------------------------------------------------------------------------\n\n/** The area a round eraser of diameter `width` covers along `points` (a disc for one point). */\nexport function eraserRegion(points: readonly Point[], width: number): BezierPath {\n\tconst pts = points.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tconst r = width / 2;\n\tif (!pts.length || !(r > 0)) return [];\n\tconst moved = pts.some((p) => !near(p, pts[0], 1e-9));\n\tif (!moved) {\n\t\tconst [cx, cy] = pts[0];\n\t\tconst k = r * 0.5522847498307936;\n\t\treturn [\n\t\t\t{ type: 'M', x: cx, y: cy - r },\n\t\t\t{ type: 'C', x1: cx + k, y1: cy - r, x2: cx + r, y2: cy - k, x: cx + r, y: cy },\n\t\t\t{ type: 'C', x1: cx + r, y1: cy + k, x2: cx + k, y2: cy + r, x: cx, y: cy + r },\n\t\t\t{ type: 'C', x1: cx - k, y1: cy + r, x2: cx - r, y2: cy + k, x: cx - r, y: cy },\n\t\t\t{ type: 'C', x1: cx - r, y1: cy - k, x2: cx - k, y2: cy - r, x: cx, y: cy - r },\n\t\t\t{ type: 'Z' }\n\t\t];\n\t}\n\tconst line: BezierPath = [{ type: 'M', x: pts[0][0], y: pts[0][1] }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p[0], y: p[1] }))];\n\treturn outlineStroke(line, { width, cap: 'round', join: 'round' });\n}\n\n/**\n * A filled path with `region` removed: one path per remaining face, or null when the region\n * does not overlap the fill.\n */\nexport function eraseFromFill(path: BezierPathInput, fillRule: FillRule, region: BezierPathInput): BezierPath[] | null {\n\tconst overlap = pathBoolean('intersection', [{ path, fillRule }, { path: region }]).path;\n\tif (!pathToContours(overlap).some((c) => Math.abs(contourSignedArea(closeContour(c, true))) > 1e-9)) return null;\n\tconst rest = pathBoolean('difference', [{ path, fillRule }, { path: region }]).path;\n\treturn splitIntoFaces(rest);\n}\n\n/**\n * The parts of a subpath's outline outside `region`, as open subpaths that keep the original\n * curves exactly; null when the outline does not enter the region. A closed subpath's last\n * and first parts join at its first anchor.\n */\nexport function eraseFromOutline(sp: VectorSubpath, region: BezierPathInput): VectorSubpath[] | null {\n\tconst regionSegs = pathToContours(region).flatMap((c) => closeContour(c, true));\n\tif (!regionSegs.length) return null;\n\tconst rb = bezierPathBounds(region);\n\tconst count = subpathSegmentCount(sp);\n\tif (!rb || count === 0) return null;\n\tconst removed = (p: Point) => pointInBezierPath(region, p, 'nonzero');\n\ttype Piece = { seg: number; t0: number; t1: number };\n\tconst runs: Piece[][] = [];\n\tlet cur: Piece[] = [];\n\tlet any = false;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst seg = subpathSegment(sp, i);\n\t\tconst sb = segmentBounds(seg);\n\t\tconst ts = [0, 1];\n\t\tif (!(sb.maxX < rb.minX || sb.minX > rb.maxX || sb.maxY < rb.minY || sb.minY > rb.maxY)) {\n\t\t\tfor (const r of regionSegs) {\n\t\t\t\tconst b = segmentBounds(r);\n\t\t\t\tif (b.maxX < sb.minX || b.minX > sb.maxX || b.maxY < sb.minY || b.minY > sb.maxY) continue;\n\t\t\t\tfor (const hit of segmentIntersections(seg, r)) if (hit.ta > 1e-9 && hit.ta < 1 - 1e-9) ts.push(hit.ta);\n\t\t\t}\n\t\t}\n\t\tts.sort((a, b) => a - b);\n\t\tfor (let k = 0; k < ts.length - 1; k++) {\n\t\t\tconst t0 = ts[k];\n\t\t\tconst t1 = ts[k + 1];\n\t\t\tif (t1 - t0 < 1e-9) continue;\n\t\t\tif (removed(segmentPoint(seg, (t0 + t1) / 2))) {\n\t\t\t\tany = true;\n\t\t\t\tif (cur.length) runs.push(cur);\n\t\t\t\tcur = [];\n\t\t\t} else cur.push({ seg: i, t0, t1 });\n\t\t}\n\t}\n\tif (cur.length) runs.push(cur);\n\tif (!any) return null;\n\t// A closed path's last and first runs meet at anchor 0.\n\tif (sp.closed && runs.length >= 2) {\n\t\tconst first = runs[0][0];\n\t\tconst lastRun = runs[runs.length - 1];\n\t\tconst last = lastRun[lastRun.length - 1];\n\t\tif (first.seg === 0 && first.t0 === 0 && last.seg === count - 1 && last.t1 === 1) lastRun.push(...runs.shift()!);\n\t}\n\tconst out: VectorSubpath[] = [];\n\tfor (const run of runs) {\n\t\tconst anchors: VectorAnchor[] = [];\n\t\tfor (const { seg, t0, t1 } of run) {\n\t\t\tconst c = subSegment(subpathSegment(sp, seg), t0, t1);\n\t\t\tconst line = c.length === 2;\n\t\t\tconst start = c[0];\n\t\t\tconst end = c[c.length - 1];\n\t\t\tif (!anchors.length) anchors.push({ x: start[0], y: start[1] });\n\t\t\tif (!line) anchors[anchors.length - 1].out = { x: c[1][0], y: c[1][1] };\n\t\t\tconst next: VectorAnchor = { x: end[0], y: end[1] };\n\t\t\tif (!line) next.in = { x: c[2][0], y: c[2][1] };\n\t\t\tanchors.push(next);\n\t\t}\n\t\tif (anchors.length < 2) continue;\n\t\tfor (const a of anchors) {\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t\tout.push({ anchors, closed: false });\n\t}\n\treturn out;\n}\n\n/** Bounds of a point list (for picking the paths a knife or eraser stroke can reach). */\nexport function polylineBounds(points: readonly Point[], pad = 0): { x: number; y: number; width: number; height: number } | null {\n\tif (!points.length) return null;\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const [x, y] of points) {\n\t\tminX = Math.min(minX, x);\n\t\tminY = Math.min(minY, y);\n\t\tmaxX = Math.max(maxX, x);\n\t\tmaxY = Math.max(maxY, y);\n\t}\n\treturn { x: minX - pad, y: minY - pad, width: maxX - minX + 2 * pad, height: maxY - minY + 2 * pad };\n}\n\n/** Ramer–Douglas–Peucker reduction of a polyline (keeps both ends). */\nexport function simplifyPolyline(points: readonly Point[], tolerance: number): Point[] {\n\tconst n = points.length;\n\tif (n < 3) return points.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ax, ay] = points[a];\n\t\tconst dx = points[b][0] - ax;\n\t\tconst dy = points[b][1] - ay;\n\t\tconst len = Math.hypot(dx, dy);\n\t\tlet far = -1;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [px, py] = points[i];\n\t\t\tconst d = len < 1e-12 ? Math.hypot(px - ax, py - ay) : Math.abs((px - ax) * dy - (py - ay) * dx) / len;\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (far >= 0 && farD > tolerance) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn points.filter((_, i) => keep[i]);\n}\n\n","/**\n * Pencil helpers: lazy-mouse smoothing (a pulled string between the pointer and the pen) and\n * ink-to-shape recognition (a hand-drawn stroke that is a line, rectangle, ellipse or polygon).\n *\n * Portions ported from (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md):\n * - photocraft-main/crates/paint/src/dynamics.rs (`Smoother`: pulled-string mode, `string`,\n * `finish` with catch-up on stroke end)\n * - wordcraft-main/crates/engine/src/cmd/ink_shape.rs (`recognise`, `ellipse_rms`,\n * `snap_square`, `corners`, `turning`, `rdp`, `upright`)\n */\nimport type { Point } from '../canvas/types.js';\n\n// ---------------------------------------------------------------------------\n// Lazy mouse\n// ---------------------------------------------------------------------------\n\n/**\n * Pulled-string smoothing: the pen stays put until the pointer is more than `length` away,\n * then follows it at that distance, so small wobbles never reach the stroke. Feed pointer\n * positions to `push`; it returns the pen positions to draw through (possibly none).\n */\nexport class LazyMouse {\n\tprivate pos: Point | null = null;\n\tprivate last: Point | null = null;\n\n\t/** `length` is the string length in the units of the points (0 turns smoothing off). */\n\tconstructor(readonly length: number) {}\n\n\tpush(p: Point): Point[] {\n\t\tthis.last = p;\n\t\tif (!(this.length > 0)) return [p];\n\t\tconst pos = this.pos;\n\t\tif (!pos) {\n\t\t\tthis.pos = p;\n\t\t\treturn [p];\n\t\t}\n\t\tconst dx = p[0] - pos[0];\n\t\tconst dy = p[1] - pos[1];\n\t\tconst d = Math.hypot(dx, dy);\n\t\tif (d <= this.length) return [];\n\t\tconst k = (d - this.length) / d;\n\t\tconst next: Point = [pos[0] + dx * k, pos[1] + dy * k];\n\t\tthis.pos = next;\n\t\treturn [next];\n\t}\n\n\t/** The string from the pen to the pointer while they are apart, else null. */\n\tstring(): [Point, Point] | null {\n\t\tconst { pos, last } = this;\n\t\tif (!(this.length > 0) || !pos || !last || (pos[0] === last[0] && pos[1] === last[1])) return null;\n\t\treturn [pos, last];\n\t}\n\n\t/** End of stroke: the pen catches up with the pointer (the point to add, if it lagged). */\n\tfinish(): Point[] {\n\t\tconst { pos, last } = this;\n\t\tif (!(this.length > 0) || !pos || !last || (pos[0] === last[0] && pos[1] === last[1])) return [];\n\t\tthis.pos = last;\n\t\treturn [last];\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Ink to shape\n// ---------------------------------------------------------------------------\n\n/** A shape recognised in a stroke, in the stroke's coordinates. */\nexport type VectorInkShape =\n\t| { kind: 'line'; a: Point; b: Point }\n\t| { kind: 'rect'; x: number; y: number; width: number; height: number }\n\t| { kind: 'ellipse'; x: number; y: number; width: number; height: number }\n\t| { kind: 'polygon'; points: Point[] };\n\nexport interface RecognizeInkOptions {\n\t/** Strokes whose longer side is smaller than this stay ink (default 6). */\n\tminSize?: number;\n}\n\n/** Most corners a recognised polygon may have. */\nexport const VECTOR_INK_MAX_CORNERS = 8;\nconst MAX_POINTS = 100_000;\n\n/** \"line\", \"square\", \"rectangle\", \"circle\", \"ellipse\", \"triangle\" or \"polygon\". */\nexport function vectorInkShapeName(shape: VectorInkShape): string {\n\tswitch (shape.kind) {\n\t\tcase 'line':\n\t\t\treturn 'line';\n\t\tcase 'rect':\n\t\t\treturn shape.width === shape.height ? 'square' : 'rectangle';\n\t\tcase 'ellipse':\n\t\t\treturn shape.width === shape.height ? 'circle' : 'ellipse';\n\t\tcase 'polygon':\n\t\t\treturn shape.points.length === 3 ? 'triangle' : 'polygon';\n\t}\n}\n\nconst dist = (a: Point, b: Point) => Math.hypot(b[0] - a[0], b[1] - a[1]);\n\nfunction bbox(pts: readonly Point[]): [number, number, number, number] {\n\tif (!pts.length) return [0, 0, 0, 0];\n\tlet [x0, y0] = pts[0];\n\tlet [x1, y1] = pts[0];\n\tfor (const [x, y] of pts) {\n\t\tx0 = Math.min(x0, x);\n\t\ty0 = Math.min(y0, y);\n\t\tx1 = Math.max(x1, x);\n\t\ty1 = Math.max(y1, y);\n\t}\n\treturn [x0, y0, x1 - x0, y1 - y0];\n}\n\nfunction segDistance(a: Point, b: Point, p: Point): number {\n\tconst dx = b[0] - a[0];\n\tconst dy = b[1] - a[1];\n\tconst len2 = dx * dx + dy * dy;\n\tconst t = len2 > 0 ? Math.min(1, Math.max(0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len2)) : 0;\n\treturn dist([a[0] + t * dx, a[1] + t * dy], p);\n}\n\nfunction polygonDistance(c: readonly Point[], p: Point): number {\n\tlet best = Infinity;\n\tfor (let i = 0; i < c.length; i++) best = Math.min(best, segDistance(c[i], c[(i + 1) % c.length], p));\n\treturn best;\n}\n\n/** RMS of each point's normalised radius minus one on the ellipse inscribed in the box (0 on it). */\nfunction ellipseRms(p: readonly Point[], x0: number, y0: number, w: number, h: number): number {\n\tconst rx = w / 2;\n\tconst ry = h / 2;\n\tif (rx <= 0 || ry <= 0 || !p.length) return Infinity;\n\tconst cx = x0 + rx;\n\tconst cy = y0 + ry;\n\tlet sum = 0;\n\tfor (const [x, y] of p) sum += (Math.hypot((x - cx) / rx, (y - cy) / ry) - 1) ** 2;\n\treturn Math.sqrt(sum / p.length);\n}\n\n/** A box drawn nearly square made square (same centre). */\nfunction snapSquare(x: number, y: number, w: number, h: number): [number, number, number, number] {\n\tif (Math.abs(w - h) <= 0.12 * Math.max(w, h)) {\n\t\tconst s = (w + h) / 2;\n\t\treturn [x + (w - s) / 2, y + (h - s) / 2, s, s];\n\t}\n\treturn [x, y, w, h];\n}\n\n/** How far the path turns at `b` coming from `a` towards `c`, in degrees (0 = straight on). */\nfunction turning(a: Point, b: Point, c: Point): number {\n\tconst u = [b[0] - a[0], b[1] - a[1]];\n\tconst v = [c[0] - b[0], c[1] - b[1]];\n\tconst lu = Math.hypot(u[0], u[1]);\n\tconst lv = Math.hypot(v[0], v[1]);\n\tif (lu <= 0 || lv <= 0) return 0;\n\treturn (Math.acos(Math.min(1, Math.max(-1, (u[0] * v[0] + u[1] * v[1]) / (lu * lv)))) * 180) / Math.PI;\n}\n\n/** Ramer–Douglas–Peucker reduction of an open polyline (iterative), keeping both ends. */\nfunction rdp(p: readonly Point[], eps: number): Point[] {\n\tconst n = p.length;\n\tif (n < 3) return p.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tlet far = a;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst d = segDistance(p[a], p[b], p[i]);\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (farD > eps) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn p.filter((_, i) => keep[i]);\n}\n\n/** Corners of the closed path through `p`: RDP split at the point farthest from the start, then flat and crowded corners merged away. */\nfunction corners(p: readonly Point[], diag: number): Point[] {\n\tconst eps = 0.05 * diag;\n\tconst start = p[0];\n\tlet far = 0;\n\tlet farD = 0;\n\tp.forEach((q, i) => {\n\t\tconst d = dist(start, q);\n\t\tif (d > farD) {\n\t\t\tfarD = d;\n\t\t\tfar = i;\n\t\t}\n\t});\n\tconst a = p.slice(0, far);\n\tconst b = p.slice(far);\n\tconst ring = rdp([...a, ...b.slice(0, 1)], eps);\n\tconst back = rdp([...b, start], eps);\n\t// The halves share the far point and the start.\n\tring.pop();\n\tback.pop();\n\tring.push(...back);\n\twhile (ring.length > 3) {\n\t\tconst n = ring.length;\n\t\tconst turn = (i: number) => turning(ring[(i + n - 1) % n], ring[i], ring[(i + 1) % n]);\n\t\tlet flat = 0;\n\t\tlet flatT = Infinity;\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst t = turn(i);\n\t\t\tif (t < flatT) {\n\t\t\t\tflatT = t;\n\t\t\t\tflat = i;\n\t\t\t}\n\t\t}\n\t\tlet short = -1;\n\t\tfor (let j = 0; j < n; j++) {\n\t\t\tif (dist(ring[j], ring[(j + 1) % n]) < 0.1 * diag) {\n\t\t\t\tshort = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (flatT < 30) ring.splice(flat, 1);\n\t\telse if (short >= 0) {\n\t\t\t// Of the two crowded corners keep the sharper.\n\t\t\tconst k = turn(short) < turn((short + 1) % n) ? short : (short + 1) % n;\n\t\t\tring.splice(k, 1);\n\t\t} else break;\n\t}\n\treturn ring;\n}\n\n/** A quadrilateral whose sides run (nearly) across and down, alternately. */\nfunction upright(c: readonly Point[]): boolean {\n\tconst n = c.length;\n\tconst dirs = c.map((a, i) => {\n\t\tconst b = c[(i + 1) % n];\n\t\tconst deg = ((((Math.atan2(b[1] - a[1], b[0] - a[0]) * 180) / Math.PI) % 180) + 180) % 180;\n\t\tif (deg <= 15 || deg >= 165) return 'across';\n\t\tif (deg >= 75 && deg <= 105) return 'down';\n\t\treturn null;\n\t});\n\treturn dirs.every((d) => d !== null) && dirs.every((d, i) => d !== dirs[(i + 1) % n]);\n}\n\n/**\n * The shape a hand-drawn stroke draws, if it is one: an open stroke is a line when it stays\n * close to the chord between its ends; a closed one is an ellipse when its points sit on the\n * ellipse inscribed in their bounds, else a polygon of 3–8 corners when that polygon stays\n * close to every point (an upright four-cornered one is a rectangle). Nearly square boxes\n * become squares and circles. Anything else (scribbles, curves, letters) is null.\n */\nexport function recognizeInkShape(points: readonly Point[], options: RecognizeInkOptions = {}): VectorInkShape | null {\n\tconst minSize = options.minSize ?? 6;\n\tconst p: Point[] = [];\n\tfor (const q of points.slice(0, MAX_POINTS)) {\n\t\tif (!Number.isFinite(q[0]) || !Number.isFinite(q[1]) || Math.abs(q[0]) >= 1e9 || Math.abs(q[1]) >= 1e9) continue;\n\t\tconst last = p[p.length - 1];\n\t\tif (!last || last[0] !== q[0] || last[1] !== q[1]) p.push([q[0], q[1]]);\n\t}\n\tif (p.length < 2) return null;\n\tconst first = p[0];\n\tconst last = p[p.length - 1];\n\tconst [x0, y0, w, h] = bbox(p);\n\tconst size = Math.max(w, h);\n\tconst diag = Math.hypot(w, h);\n\tif (size < minSize) return null;\n\tlet length = 0;\n\tfor (let i = 1; i < p.length; i++) length += dist(p[i - 1], p[i]);\n\tconst gap = dist(first, last);\n\t// A line: the stroke barely leaves the chord between its ends and doesn't double back.\n\tif (gap > 0.85 * length && gap >= minSize) {\n\t\tconst off = Math.max(...p.map((q) => segDistance(first, last, q)));\n\t\tif (off <= Math.max(0.06 * gap, (1.5 * minSize) / 6)) return { kind: 'line', a: first, b: last };\n\t}\n\t// Other shapes are closed: the stroke ends near where it began and goes around.\n\tif (gap > 0.2 * size || length < 2 * size) return null;\n\tconst rms = ellipseRms(p, x0, y0, w, h);\n\tconst roundish = w > 0.2 * size && h > 0.2 * size;\n\tconst ellipse = (): VectorInkShape => {\n\t\tconst [x, y, sw, sh] = snapSquare(x0, y0, w, h);\n\t\treturn { kind: 'ellipse', x, y, width: sw, height: sh };\n\t};\n\tif (roundish && rms < 0.06) return ellipse();\n\tconst c = corners(p, diag);\n\tconst fits = c.length >= 3 && p.every((q) => polygonDistance(c, q) <= 0.08 * diag);\n\tif (fits && c.length === 4 && upright(c)) {\n\t\tconst [bx, by, bw, bh] = bbox(c);\n\t\tconst [x, y, sw, sh] = snapSquare(bx, by, bw, bh);\n\t\treturn { kind: 'rect', x, y, width: sw, height: sh };\n\t}\n\tif (fits && c.length <= VECTOR_INK_MAX_CORNERS) return { kind: 'polygon', points: c };\n\t// A wobbly round stroke is still an ellipse.\n\treturn roundish && rms < 0.1 ? ellipse() : null;\n}\n","/**\n * Pathfinder operands, the Shape Builder and fill regions over a vector document.\n *\n * Everything works in document space: each path is mapped through its own transform and its\n * parents', with live corners cut (`subpathsToBezier`), so rotated nodes and nodes inside\n * rotated groups take part as drawn. The controller maps results back into the space of the node\n * that receives them.\n *\n * - **Pathfinder operands**: a filled path is its fill area (every subpath closed); an unfilled\n * path with a stroke is the area its stroke paints (alignment, caps, joins and arrowheads\n * included) and results from it are filled with the stroke's paint; for Divide an unfilled open\n * path is a cutting line instead.\n * - **Shape Builder**: the planar map of the selected paths (`PlanarMap`). Closed subpaths bound\n * faces whatever their paint (a stroke-only shape's inside is a face), filled open subpaths that\n * enclose an area are closed by an invisible edge, and unfilled open paths cut the faces they\n * cross; their pieces between junctions can be erased. Merging faces unites them along the\n * map's own edges and takes the area away from every shape covering them. Erasing (Alt) also\n * takes the edges of the other outlines, cut where paths meet: a closed subpath opens there,\n * an open one splits, and an edge bounding a face deleted in the same gesture goes with it.\n * - **Fill regions** (paint bucket): the planar map of every visible outline; the region around a\n * point is traced from a ray (`PlanarMap.regionAt`).\n *\n * The Shape Builder follows vectorcraft-main/crates/tools/src/builder.rs (`BuilderMap`, `hit`,\n * `sides`, `line_between`, `erased_edges`, `Hit::Edge`, `shape_builder_shapes`, `sample_polyline`)\n * and crates/engine/src/cmd/buildcmds.rs (`sb_merge`), with figcraft-main/crates/engine/src/shapebuilder.rs\n * (strokes as their outlined area). MIT OR Apache-2.0, © ArtCraft Team and contributors. See\n * THIRD_PARTY_NOTICES.md.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcontourSignedArea,\n\tcloseContour,\n\tdistanceToBezierPath,\n\tpathToContours,\n\tsegmentPoint,\n\tsegmentTangent,\n\tcontoursToPath,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport { PlanarMap, cutOutPiece, type PlanarChain } from '../canvas/pathops/planar.js';\nimport type { PathfinderOperation, PathfinderShape } from '../canvas/pathops/pathfinder.js';\nimport { hasPaint, multiplyMatrices, nodeMatrix, subpathsToBezier, vectorPathWorldBezier, vectorStrokeOutline, IDENTITY_MATRIX, type AffineMatrix } from './geometry.js';\nimport { expandVectorAppearance } from './appearance.js';\nimport type { Vec2, VectorDocument, VectorNode, VectorPaint, VectorPathNode, VectorSubpath } from './types.js';\n\n/** A path node with the matrix of its parent space (parent → document). */\nexport interface VectorPathEntry {\n\tnode: VectorPathNode;\n\tparent: AffineMatrix;\n}\n\n/**\n * The path nodes inside `roots` (or every node when `roots` is null), bottom to top, with their\n * parent matrices. Hidden nodes are skipped, and locked ones unless `locked` is true. Live nodes\n * (path effects, live booleans) take part as drawn (`expandVectorAppearance`: their entries are\n * the expanded paths, whose ids may not be in the document) unless `expand` is false.\n */\nexport function vectorPathEntries(doc: VectorDocument, roots: readonly string[] | null, options: { locked?: boolean; expand?: boolean } = {}): VectorPathEntry[] {\n\tconst out: VectorPathEntry[] = [];\n\tconst visit = (stored: VectorNode, parent: AffineMatrix, inside: boolean) => {\n\t\tif (stored.visible === false || (stored.locked && !options.locked)) return;\n\t\tconst node = options.expand === false ? stored : expandVectorAppearance(stored);\n\t\tconst picked = inside || roots === null || roots.includes(node.id);\n\t\tif (node.type === 'group') {\n\t\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\t\tfor (const c of node.children) visit(c, m, picked);\n\t\t} else if (picked) out.push({ node, parent });\n\t};\n\tfor (const n of doc.nodes) visit(n, IDENTITY_MATRIX, false);\n\treturn out;\n}\n\nconst usable = (sp: VectorSubpath) => sp.anchors.length > 1;\n\n/** The entry's outline in document space with the given subpaths. */\nfunction worldOf(entry: VectorPathEntry, subpaths: VectorSubpath[]): BezierPath {\n\treturn vectorPathWorldBezier({ ...entry.node, subpaths }, entry.parent);\n}\n\n/** Whether a subpath, closed, encloses an area (rather than retracing itself). */\nexport function subpathEnclosesArea(sp: VectorSubpath): boolean {\n\tconst contour = pathToContours(subpathsToBezier([{ ...sp, closed: true }]))[0];\n\tif (!contour) return false;\n\tconst segs = closeContour(contour, true);\n\tconst b = bezierPathBounds(contoursToPath([{ segments: segs, closed: true }]));\n\tif (!b) return false;\n\tconst w = b.maxX - b.minX;\n\tconst h = b.maxY - b.minY;\n\treturn Math.abs(contourSignedArea(segs)) > 1e-9 * (w * w + h * h);\n}\n\n/** How an operand takes part in a Pathfinder operation: its fill, its stroke's area, a cutting line or its bare outline. */\nexport type VectorPathfinderPaint = 'fill' | 'stroke' | 'line' | 'outline';\n\nconst paintKey = (paint: VectorPaint | undefined) => (typeof paint === 'string' ? paint.trim().toLowerCase() : JSON.stringify(paint ?? null));\n\n/** The Pathfinder shape of a path (document space), and what it stands for. */\nexport function vectorPathfinderShape(entry: VectorPathEntry, op: PathfinderOperation): PathfinderShape & { paint: VectorPathfinderPaint } {\n\tconst { node } = entry;\n\tconst subpaths = node.subpaths.filter(usable);\n\tconst closed = subpaths.map((s) => ({ ...s, closed: true }));\n\tconst fillRule = node.fillRule ?? 'nonzero';\n\tif (hasPaint(node.fill)) return { path: worldOf(entry, closed), fillRule, key: `fill:${paintKey(node.fill)}`, paint: 'fill' };\n\tconst open = subpaths.length > 0 && subpaths.every((s) => !s.closed);\n\tif (op === 'divide' && open) return { path: worldOf(entry, subpaths), line: true, paint: 'line' };\n\tif (hasPaint(node.stroke) && (node.strokeWidth ?? 1) > 0) {\n\t\t// Node transforms are rigid, so the stroke laid out in document space keeps its width.\n\t\tconst path = vectorStrokeOutline({ ...node, subpaths }, entry.parent);\n\t\treturn { path, fillRule: 'nonzero', key: `fill:${paintKey(node.stroke)}`, paint: 'stroke' };\n\t}\n\treturn { path: worldOf(entry, closed), fillRule, key: 'none', paint: 'outline' };\n}\n\nconst STROKE_KEYS = [\n\t'stroke',\n\t'strokeWidth',\n\t'strokeLinecap',\n\t'strokeLinejoin',\n\t'strokeDasharray',\n\t'strokeAlign',\n\t'startArrow',\n\t'endArrow',\n\t'arrowAlign',\n\t'startArrowScale',\n\t'endArrowScale',\n\t'strokeWidthProfile'\n] as const;\n\n/**\n * Style of a Pathfinder or Shape Builder result taken from `node`: the node's own style for a\n * filled area, the stroke's paint as a fill for a stroke's area, or (for Outline edges) a stroke\n * in the paint of the area the edge bounds. Never carries the node's id, transform or geometry.\n */\nexport function vectorResultStyle(node: VectorPathNode, paint: VectorPathfinderPaint, edge = false): Omit<VectorPathNode, 'id' | 'subpaths'> {\n\tconst { id: _id, subpaths: _s, transform: _t, effects: _e, booleanOperation: _b, ...rest } = node;\n\tconst base: Omit<VectorPathNode, 'id' | 'subpaths'> = { ...rest, fillRule: 'nonzero' };\n\tif (edge) {\n\t\tfor (const k of STROKE_KEYS) delete (base as Record<string, unknown>)[k];\n\t\tconst stroke = paint === 'stroke' || !hasPaint(node.fill) ? node.stroke : node.fill;\n\t\treturn { ...base, fill: null, stroke: stroke ?? '#000000', strokeWidth: node.strokeWidth ?? 1 };\n\t}\n\tif (paint === 'stroke') {\n\t\tfor (const k of STROKE_KEYS) delete (base as Record<string, unknown>)[k];\n\t\treturn { ...base, fill: node.stroke ?? null, stroke: null };\n\t}\n\treturn base;\n}\n\n// ---------------------------------------------------------------------------\n// Shape Builder\n// ---------------------------------------------------------------------------\n\n/**\n * A run of a path between the points where other paths meet it (or it ends): a piece of an\n * unfilled open path, or an edge of another path's outline.\n */\nexport interface VectorBuilderLinePiece {\n\tpath: BezierPath;\n\tsegments: BezierSegment[];\n\t/** A loop with no junction on it (the whole subpath). */\n\tclosed: boolean;\n\t/** Index of the entry it belongs to (the front-most where outlines coincide). */\n\tsource: number;\n\tbounds: { minX: number; minY: number; maxX: number; maxY: number };\n}\n\n/** The Shape Builder's planar map of a set of paths. */\nexport interface VectorShapeBuilderMap {\n\tentries: VectorPathEntry[];\n\tmap: PlanarMap;\n\t/** Entries with no closed subpath (cutting lines; their pieces can be erased). */\n\tlines: boolean[];\n\tpieces: VectorBuilderLinePiece[];\n\t/** The edges of the other entries' outlines, cut where paths meet (built on first use: erasing). */\n\treadonly edges: VectorBuilderLinePiece[];\n\t/** How far an edge may lie from the outline it came from (document units). */\n\ttolerance: number;\n}\n\n/** What a Shape Builder gesture touches at a point. */\nexport type VectorBuilderHit = { face: number } | { line: number } | { edge: number };\n\n/** The faces, line pieces and edges a gesture touched, in the order touched. */\nexport interface VectorBuilderTouched {\n\tfaces: number[];\n\tlines: number[];\n\tedges: number[];\n}\n\n/**\n * The Shape Builder map of `entries` (bottom to top). Filled open subpaths that enclose an area\n * are closed. Null when nothing can be mapped.\n */\nexport function vectorShapeBuilderMap(entries: readonly VectorPathEntry[]): VectorShapeBuilderMap | null {\n\tconst lines: boolean[] = [];\n\tconst inputs = entries.map((entry) => {\n\t\tconst filled = hasPaint(entry.node.fill);\n\t\tconst subpaths = entry.node.subpaths.filter(usable).map((sp) => (!sp.closed && filled && subpathEnclosesArea(sp) ? { ...sp, closed: true } : sp));\n\t\tlines.push(!subpaths.some((s) => s.closed));\n\t\treturn { path: worldOf(entry, subpaths), fillRule: entry.node.fillRule ?? 'nonzero' };\n\t});\n\tconst map = PlanarMap.build(inputs);\n\tif (!map) return null;\n\tlet chains: PlanarChain[] | null = null;\n\tconst runs = (line: boolean) =>\n\t\t(chains ??= map.chains())\n\t\t\t.filter((c) => lines[c.source] === line && !(line && c.closed))\n\t\t\t.map((c) => {\n\t\t\t\tconst path = contoursToPath([{ segments: c.segments, closed: c.closed }]);\n\t\t\t\treturn { path, segments: c.segments, closed: c.closed, source: c.source, bounds: bezierPathBounds(path)! };\n\t\t\t});\n\tconst pieces = lines.some(Boolean) ? runs(true) : [];\n\tlet edges: VectorBuilderLinePiece[] | null = null;\n\tlet size = 0;\n\tfor (const input of inputs) {\n\t\tconst b = bezierPathBounds(input.path);\n\t\tif (b) size = Math.max(size, b.maxX - b.minX, b.maxY - b.minY);\n\t}\n\treturn {\n\t\tentries: [...entries],\n\t\tmap,\n\t\tlines,\n\t\tpieces,\n\t\tget edges() {\n\t\t\treturn (edges ??= runs(false));\n\t\t},\n\t\ttolerance: 0.2 * Math.max(size / 2000, 0.25)\n\t};\n}\n\n/** The run of `pieces` nearest `p` within `tol`, with its distance. */\nfunction pieceNear(pieces: readonly VectorBuilderLinePiece[], p: Vec2, tol: number): { index: number; d: number } | null {\n\tconst point: Point = [p.x, p.y];\n\tlet best: { index: number; d: number } | null = null;\n\tpieces.forEach((piece, index) => {\n\t\tconst b = piece.bounds;\n\t\tif (p.x < b.minX - tol || p.x > b.maxX + tol || p.y < b.minY - tol || p.y > b.maxY + tol) return;\n\t\tconst d = distanceToBezierPath(piece.path, point);\n\t\tif (d <= tol && (!best || d < best.d)) best = { index, d };\n\t});\n\treturn best;\n}\n\n/**\n * The face under `p`, or with `lineTolerance` (erasing) first the nearer of the line piece and\n * the outline edge that close.\n */\nexport function vectorShapeBuilderHit(m: VectorShapeBuilderMap, p: Vec2, lineTolerance: number | null = null): VectorBuilderHit | null {\n\tif (lineTolerance !== null && lineTolerance > 0) {\n\t\tconst line = pieceNear(m.pieces, p, lineTolerance);\n\t\tconst edge = pieceNear(m.edges, p, lineTolerance);\n\t\tif (edge && (!line || edge.d < line.d)) return { edge: edge.index };\n\t\tif (line) return { line: line.index };\n\t}\n\tconst face = m.map.faceAt([p.x, p.y]);\n\treturn face >= 0 ? { face } : null;\n}\n\n/** Points along a polyline no more than `step` apart (the pointer's path through faces). */\nexport function samplePolyline(points: readonly Vec2[], step: number): Vec2[] {\n\tconst out: Vec2[] = [];\n\tconst s = Math.max(step, 1e-3);\n\tpoints.forEach((p, i) => {\n\t\tif (i > 0) {\n\t\t\tconst a = points[i - 1];\n\t\t\tconst n = Math.min(4000, Math.ceil(Math.hypot(p.x - a.x, p.y - a.y) / s));\n\t\t\tfor (let k = 1; k < n; k++) out.push({ x: a.x + ((p.x - a.x) * k) / n, y: a.y + ((p.y - a.y) * k) / n });\n\t\t}\n\t\tout.push(p);\n\t});\n\treturn out;\n}\n\n/** Adds what a point hits to `touched` (each face or piece once). */\nexport function addBuilderHit(touched: VectorBuilderTouched, hit: VectorBuilderHit | null): boolean {\n\tif (!hit) return false;\n\tconst [list, i] = 'face' in hit ? [touched.faces, hit.face] : 'line' in hit ? [touched.lines, hit.line] : [touched.edges, hit.edge];\n\tif (list.includes(i)) return false;\n\tlist.push(i);\n\treturn true;\n}\n\n/** The faces just either side of the middle of a line piece (-1 outside every face). */\nfunction sides(m: VectorShapeBuilderMap, piece: VectorBuilderLinePiece): [number, number] {\n\tconst seg = piece.segments[Math.floor(piece.segments.length / 2)];\n\tconst mid = segmentPoint(seg, 0.5);\n\tconst t = segmentTangent(seg, 0.5);\n\tconst chord = Math.hypot(seg[seg.length - 1][0] - seg[0][0], seg[seg.length - 1][1] - seg[0][1]);\n\tconst off = Math.max(1e-6, Math.min(0.05, 0.05 * chord));\n\treturn [m.map.faceAt([mid[0] - t[1] * off, mid[1] + t[0] * off]), m.map.faceAt([mid[0] + t[1] * off, mid[1] - t[0] * off])];\n}\n\n/**\n * The edges a gesture deletes: those it touched that bound none of the faces it touched (an edge\n * of a deleted or merged face goes with the face, so an erase drag that crosses an edge into a\n * face deletes the face).\n */\nexport function vectorBuilderErasedEdges(m: VectorShapeBuilderMap, touched: VectorBuilderTouched): number[] {\n\tif (!touched.edges.length) return [];\n\tconst faces = new Set(touched.faces);\n\treturn touched.edges.filter((k) => m.edges[k] && !sides(m, m.edges[k]).some((f) => f >= 0 && faces.has(f)));\n}\n\n/**\n * What becomes of one entry: unchanged (absent), removed (`null`), or new outlines (document\n * space). `fill`: what is left of its area, filled non-zero (subpaths an erased edge opened stay\n * open); `outline`: its own outline with erased edges cut out, its fill rule kept; `pieces`: the\n * pieces of a cutting line that stay, each its own path.\n */\nexport type VectorBuilderReplacement = { kind: 'fill'; path: BezierPath } | { kind: 'outline'; path: BezierPath } | { kind: 'pieces'; paths: BezierPath[] } | null;\n\nexport interface VectorShapeBuilderPlan {\n\treplace: Map<number, VectorBuilderReplacement>;\n\t/** The merged shape (document space), styled like entry `style`; `currentFill` when only outlines enclosed it. */\n\tmerged: { path: BezierPath; style: number; currentFill: boolean } | null;\n}\n\n/**\n * What a gesture does: merging (or with `erase`, deleting) the touched faces takes them away\n * from every shape covering them; line pieces touched (erasing) or lying between touched faces\n * go; erased edges (`vectorBuilderErasedEdges`) are cut out of every outline they lie on;\n * merging adds the union of the faces as a new shape styled like the top-most shape over the\n * first face touched (or, for a face only outlines enclose, the top-most shape with the current\n * fill).\n */\nexport function planShapeBuilder(m: VectorShapeBuilderMap, touched: VectorBuilderTouched, erase: boolean): VectorShapeBuilderPlan {\n\tconst replace = new Map<number, VectorBuilderReplacement>();\n\tconst picked = new Set(touched.faces);\n\tconst faces = m.map.faces;\n\tconst sourcesOf = faces.map((_, i) => m.map.faceSources(i));\n\tconst cuts = erase ? vectorBuilderErasedEdges(m, touched).map((k) => m.edges[k]) : [];\n\tm.entries.forEach((entry, i) => {\n\t\tif (m.lines[i]) {\n\t\t\tconst own = m.pieces.flatMap((piece, k) => (piece.source === i ? [k] : []));\n\t\t\tconst keep = own.filter((k) => !touched.lines.includes(k) && !sides(m, m.pieces[k]).every((f) => f >= 0 && picked.has(f)));\n\t\t\tif (keep.length === own.length) return;\n\t\t\treplace.set(i, keep.length ? { kind: 'pieces', paths: keep.map((k) => m.pieces[k].path) } : null);\n\t\t\treturn;\n\t\t}\n\t\tconst inUnion = touched.faces.some((f) => sourcesOf[f].includes(i));\n\t\tif (!inUnion && !cuts.length) return;\n\t\tlet rest: BezierPath;\n\t\tif (inUnion) {\n\t\t\tconst kept = faces.flatMap((_, f) => (sourcesOf[f].includes(i) && !picked.has(f) ? [f] : []));\n\t\t\trest = kept.length ? m.map.merge(kept) : [];\n\t\t} else rest = worldOf(entry, entry.node.subpaths.filter(usable));\n\t\t// Each erased edge comes off every outline it lies on (shared edges from each shape).\n\t\tconst fillCloses = hasPaint(entry.node.fill);\n\t\tlet cut = false;\n\t\tfor (const piece of cuts) {\n\t\t\tconst r = rest.length ? cutOutPiece(rest, piece, fillCloses, m.tolerance) : null;\n\t\t\tif (r) {\n\t\t\t\trest = r;\n\t\t\t\tcut = true;\n\t\t\t}\n\t\t}\n\t\tif (!inUnion && !cut) return;\n\t\treplace.set(i, rest.length ? { kind: inUnion ? 'fill' : 'outline', path: rest } : null);\n\t});\n\tlet merged: VectorShapeBuilderPlan['merged'] = null;\n\tif (!erase && touched.faces.length) {\n\t\tconst path = m.map.merge(touched.faces);\n\t\tconst covered = touched.faces.map((f) => sourcesOf[f]).find((s) => s.length);\n\t\tconst lastShape = m.lines.lastIndexOf(false);\n\t\tconst style = covered ? covered[covered.length - 1] : lastShape >= 0 ? lastShape : m.entries.length - 1;\n\t\tif (path.length) merged = { path, style, currentFill: !covered };\n\t}\n\treturn { replace, merged };\n}\n\n// ---------------------------------------------------------------------------\n// Fill regions\n// ---------------------------------------------------------------------------\n\n/**\n * The planar map of every visible path's outline as drawn (locked ones included), for the paint\n * bucket. `gap` closes gaps up to that distance between loose ends.\n */\nexport function vectorFillMap(doc: VectorDocument, gap = 0): PlanarMap | null {\n\tconst entries = vectorPathEntries(doc, null, { locked: true });\n\treturn PlanarMap.build(\n\t\tentries.map((e) => ({ path: worldOf(e, e.node.subpaths.filter(usable)), fills: false })),\n\t\t{ gap, maxSegments: 20000 }\n\t);\n}\n","import { HistoryManager } from '../history/HistoryManager.js';\nimport type { Command } from '../history/types.js';\nimport { fitCubics } from '../canvas/curveFit.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { pathfinder as runPathfinder } from '../canvas/pathops/pathfinder.js';\nimport type { PlanarMap } from '../canvas/pathops/planar.js';\nimport { bezierPathBounds, bezierPathToSvg, transformBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierToSubpaths,\n\tboundsFromPoints,\n\tboundsIntersect,\n\tcloneVectorDocument,\n\tcloneVectorNode,\n\tcollectPathNodes,\n\tconvertAnchor,\n\tellipseSubpath,\n\tfindVectorNode,\n\thitTestVectorNode,\n\thitTestVectorNodes,\n\tinsertAnchor,\n\tlineSubpath,\n\tlocateVectorNode,\n\tmoveAnchorHandle,\n\tnearestSegment,\n\thasPaint,\n\tnodeMatrix,\n\tinvertMatrix,\n\tapplyMatrix,\n\tapplyMatrixLinear,\n\tmultiplyMatrices,\n\tmatrixRotation,\n\tvectorWorldMatrix,\n\tvectorParentMatrix,\n\tvectorPathWorldBezier,\n\tIDENTITY_MATRIX,\n\tpolygonSubpath,\n\trectSubpath,\n\tremoveAnchors,\n\treverseSubpath,\n\trotateMatrix,\n\tscaleMatrix,\n\tstarSubpath,\n\tsubpathsToBezier,\n\ttransformVectorNode,\n\ttranslateAnchor,\n\ttranslateMatrix,\n\tunionBounds,\n\tvectorNodeBounds,\n\twalkVectorNodes,\n\ttype AffineMatrix\n} from './geometry.js';\nimport {\n\tcornerBisectorPoint,\n\tcornerRadiusChange,\n\tfitCornerRadius,\n\tnextVectorCornerKind,\n\tsetAnchorCorner,\n\tsetSubpathCorners,\n\tvectorCorners,\n\ttype VectorCornerInfo\n} from './corners.js';\nimport { strokeWidthProfileOf, vectorStrokeOutlinePath, vectorStrokeParts } from './stroke.js';\nimport { nearestStrokePosition, strokePositionPoint } from './varstroke.js';\nimport {\n\tgenerateWidthProfile,\n\tinsertWidthPoint,\n\tpressureWidthProfile,\n\tremoveWidthPoints,\n\treverseWidthProfile,\n\tsanitizeWidthProfile,\n\tsetWidthPoint,\n\twidthProfileAt,\n\twidthProfileMaxScale,\n\twidthProfilePreset,\n\ttype VectorTaperOptions,\n\ttype VectorWaveOptions,\n\ttype VectorWidthPreset,\n\tVECTOR_WIDTH_PROFILE_MAX_POINTS,\n\tVECTOR_WIDTH_SAME_T\n} from './width.js';\nimport { parseVectorSvg, vectorDocumentToSvg, vectorPathLocalBounds, type VectorSvgExportOptions } from './svg.js';\nimport {\n\tapplyVectorGradientPatch,\n\tdefaultVectorGradient,\n\tinsertVectorGradientStop,\n\tisVectorGradient,\n\tmoveVectorGradientHandle,\n\tmoveVectorGradientStop,\n\tremoveVectorGradientStop,\n\tsetVectorGradientVector,\n\tsortedVectorGradientStops,\n\tvectorGradientMidpointFromPosition,\n\ttype VectorGradientHandle,\n\ttype VectorGradientPatch\n} from './gradient.js';\nimport {\n\tgetVectorGradientAnnotator,\n\thitVectorGradientAnnotator,\n\tvectorGradientBarPosition,\n\tVECTOR_GRADIENT_OFF_BAR,\n\tVECTOR_GRADIENT_STOP_GAP,\n\ttype VectorGradientAnnotator,\n\ttype VectorGradientPart,\n\ttype VectorGradientTarget\n} from './gradientTool.js';\nimport {\n\texpandVectorBlend,\n\tisVectorBlendGroup,\n\trefreshVectorBlends,\n\treleaseVectorBlend,\n\tvectorBlendKeyTargets\n} from './blendGroup.js';\nimport {\n\tcreateVectorEffect,\n\texpandVectorAppearance,\n\thasOwnVectorAppearance,\n\thasVectorAppearance,\n\tisVectorLiveBoolean,\n\tnormalizeVectorEffectParams,\n\tvectorAppearanceOutline,\n\tvectorEnteredGroups,\n\tvectorEnvelopeFrame,\n\tvectorNodeEnvelope,\n\ttype VectorEnvelopeParams,\n\tVECTOR_EFFECT_LABELS\n} from './appearance.js';\nimport { applyVectorHomography, vectorHomography, vectorHomographyKeepsQuad } from './perspective.js';\nimport { distortVectorNode, vectorBoxCorners, vectorDistortQuad, vectorShearForSide, vectorSkewMatrix, VECTOR_DISTORT_TOLERANCE, type VectorDistortMode } from './distort.js';\nimport {\n\tdragVectorMeshPoint,\n\tpullVectorMesh,\n\tresizeVectorMesh,\n\tvectorMeshEditPoints,\n\tvectorMeshFromOutline,\n\tvectorMeshOutline,\n\tvectorMeshParamAt\n} from './warp.js';\nimport { constrainToLeave, VECTOR_CONSTRUCTION_ANGLES, VectorSnapTargets, type VectorSnapGuides, type VectorSnapLeave } from './snap.js';\nimport {\n\tbendSegment as bendSubpathSegment,\n\tcurvatureMoveAnchor,\n\tcutSubpathAt,\n\tjoinSubpaths,\n\tremoveAnchorsKeepingShape,\n\tremoveRedundantPoints as removeRedundantSubpathPoints,\n\tsmoothSubpath,\n\tsplitSubpathAt\n} from './pathEdit.js';\nimport { eraseFromFill, eraseFromOutline, eraserRegion, knifePath, polylineBounds, simplifyPolyline } from './pathCut.js';\nimport { LazyMouse, recognizeInkShape, vectorInkShapeName, type VectorInkShape } from './ink.js';\nimport {\n\taddBuilderHit,\n\tplanShapeBuilder,\n\tsamplePolyline,\n\tvectorFillMap,\n\tvectorPathEntries,\n\tvectorPathfinderShape,\n\tvectorResultStyle,\n\tvectorBuilderErasedEdges,\n\tvectorShapeBuilderHit,\n\tvectorShapeBuilderMap,\n\ttype VectorBuilderTouched,\n\ttype VectorShapeBuilderMap\n} from './builder.js';\nimport type { VectorGradient, VectorWarpMesh } from './types.js';\nimport type {\n\tVec2,\n\tVectorEffect,\n\tVectorEffectType,\n\tVectorAlign,\n\tVectorAnchor,\n\tVectorAnchorRef,\n\tVectorAnchorType,\n\tVectorArrange,\n\tVectorAverageAxis,\n\tVectorBlend,\n\tVectorBlendOptions,\n\tVectorBooleanOperation,\n\tVectorBounds,\n\tVectorCornerKind,\n\tVectorDefaults,\n\tVectorDistribute,\n\tVectorDocument,\n\tVectorGroupNode,\n\tVectorHandleRef,\n\tVectorModifiers,\n\tVectorNode,\n\tVectorPathfinderOperation,\n\tVectorPathNode,\n\tVectorSegmentRef,\n\tVectorStyle,\n\tVectorSubpath,\n\tVectorTool,\n\tVectorTransformHandle,\n\tVectorViewport,\n\tVectorWidthPoint\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface VectorSnapOptions {\n\t/** Grid size in document units (0 = off, default 0). Points and boxes that snap to no object snap to it. */\n\tgrid: number;\n\t/**\n\t * Snap to other objects (default true): anchors, paths and their intersections, bounding-box\n\t * edges and centres, the artboard, construction angles, equal spacing and matching sizes.\n\t */\n\tobjects: boolean;\n\t/** Show smart guide lines and labels while snapping (default true). */\n\tguides: boolean;\n\t/** How near a target pulls, in screen pixels (default 5). */\n\tthreshold: number;\n\t/** Construction guide angles through the point a drawn point leaves from, in degrees (default 0, 45, 90, 135). */\n\tangles: readonly number[];\n}\n\n/** Snap options new editors start with. Hold Cmd / Ctrl (`mod`) during a drag to bypass snapping. */\nexport const DEFAULT_VECTOR_SNAP: Readonly<VectorSnapOptions> = { grid: 0, objects: true, guides: true, threshold: 5, angles: VECTOR_CONSTRUCTION_ANGLES };\n\n/** How path-editing gestures and the pencil, knife and eraser behave. */\nexport interface VectorPathEditOptions {\n\t/**\n\t * Deleting anchors refits the neighbouring handles so the shape stays (default true). Off,\n\t * the neighbours are joined with their handles as they are.\n\t */\n\tkeepShapeOnDelete: boolean;\n\t/**\n\t * Dragging one anchor with the direct tool bends its two segments like the Curvature tool,\n\t * keeping the segments beyond still (default false). Alt held during the drag flips it.\n\t */\n\tcurvatureMoves: boolean;\n\t/** Pencil lazy-mouse smoothing, 0–1: the pulled string is up to 100 screen pixels long (default 0, off). */\n\tpencilSmoothing: number;\n\t/** Pencil strokes that look like a line, rectangle, ellipse or polygon become that shape (default false). */\n\trecognizeShapes: boolean;\n\t/** Eraser diameter in document units (default 10). */\n\teraserSize: number;\n\t/**\n\t * Record pointer pressure on pencil strokes as a width profile: `pen` (default) for pen input\n\t * only, `all` for any pointer that reports pressure, `off` never.\n\t */\n\tpencilPressure: 'pen' | 'all' | 'off';\n\t/**\n\t * Paint bucket: gaps up to this distance (document units) between loose ends of outlines are\n\t * closed when finding the region to fill (default 0, off).\n\t */\n\tfillGap: number;\n}\n\n/** The gap the toolbars' \"Close gaps\" toggle sets (document units). */\nexport const VECTOR_FILL_GAP = 6;\n\n/** Path-editing options new editors start with. */\nexport const DEFAULT_VECTOR_PATH_EDIT: Readonly<VectorPathEditOptions> = {\n\tkeepShapeOnDelete: true,\n\tcurvatureMoves: false,\n\tpencilSmoothing: 0,\n\trecognizeShapes: false,\n\teraserSize: 10,\n\tpencilPressure: 'pen',\n\tfillGap: 0\n};\n\n/** Longest pencil lazy-mouse string (at smoothing 1), in screen pixels. */\nexport const VECTOR_PENCIL_STRING_PX = 100;\n\nexport interface VectorEditorOptions {\n\tdocument?: VectorDocument;\n\t/** History to record into, e.g. one shared with the rest of the app (default: a new one). */\n\thistory?: HistoryManager;\n\t/** Starting tool (default `select`). */\n\ttool?: VectorTool;\n\t/** Style and settings for new shapes and paths. */\n\tdefaults?: VectorDefaults;\n\tviewport?: Partial<VectorViewport>;\n\tsnap?: Partial<VectorSnapOptions>;\n\tediting?: Partial<VectorPathEditOptions>;\n\t/** Pick distance for anchors, handles and outlines in screen pixels (default 6). */\n\thitRadius?: number;\n\t/** Id factory for new nodes. */\n\tcreateId?: () => string;\n\t/** Called after the document changes (edits, undo, redo, load). */\n\tonChange?: (document: VectorDocument) => void;\n\t/** Start in Free Distort mode (see `setFreeDistort`). */\n\tfreeDistort?: boolean;\n}\n\n/** A pointer event as the controller needs it. Positions are in screen pixels relative to the canvas. */\nexport interface VectorPointerInput extends VectorModifiers {\n\t/** 0 = primary, 1 = middle (pans), 2 = secondary. Default 0. */\n\tbutton?: number;\n\t/** `PointerEvent.pressure` (0–1), recorded on pencil strokes. */\n\tpressure?: number;\n\t/** `PointerEvent.pointerType` (`mouse`, `pen`, `touch`). */\n\tpointerType?: string;\n}\n\n/** One width point of a path's stroke profile; `subpath` is the subpath it is shown on. */\nexport interface VectorWidthPointRef {\n\tnodeId: string;\n\tindex: number;\n\tsubpath: number;\n}\n\n/** A spot on a stroke (width tool): where a drag would add a width point. Positions in document units. */\nexport interface VectorStrokeSpot {\n\tnodeId: string;\n\tsubpath: number;\n\t/** Position along the subpath by length, 0–1. */\n\tt: number;\n\tpoint: Vec2;\n\t/** Ends of the stroke's width across the path there. */\n\tleft: Vec2;\n\tright: Vec2;\n}\n\n/**\n * The width point being edited numerically (double-click with the width tool): `index` is the\n * point's, or null for a new point at `t` (a double-click on a stroke away from its points).\n * `left` / `right` are side widths in document units (how far the stroke reaches on each side),\n * `point` is where it sits on the path, in document space.\n */\nexport interface VectorWidthPointEdit {\n\tnodeId: string;\n\tsubpath: number;\n\tindex: number | null;\n\tt: number;\n\tleft: number;\n\tright: number;\n\tpoint: Vec2;\n}\n\n/** A key press as the controller needs it. */\nexport interface VectorKeyInput extends VectorModifiers {\n\t/** `KeyboardEvent.key`. */\n\tkey: string;\n}\n\n/** What the pointer is over. */\nexport interface VectorHover {\n\tnodeId: string | null;\n\tanchor?: VectorAnchorRef;\n\thandle?: VectorHandleRef;\n\t/** A segment under the pointer (direct tool and scissors); `point` is in document space. */\n\tsegment?: { nodeId: string; subpath: number; segment: number; t: number; point: Vec2 };\n\ttransformHandle?: VectorTransformHandle;\n\t/** A live corner widget (direct tool): the corner's anchor. */\n\tcorner?: VectorAnchorRef;\n\t/** A width point (width tool): its centre or the end of its left / right side. */\n\twidthPoint?: VectorWidthPointRef & { part: 'center' | 'left' | 'right' };\n\t/** A spot on a stroke away from its width points (width tool). */\n\tstrokeSpot?: VectorStrokeSpot;\n\t/** A part of the gradient annotator (gradient tool). */\n\tgradient?: VectorGradientPart;\n\t/** A control point of the selected envelope's mesh (`index`), or a spot inside it (`index` null): Envelope tool. */\n\tenvelope?: { nodeId: string; index: number | null };\n}\n\n/** The drag in progress, for overlays and status text. */\nexport type VectorInteraction =\n\t| { type: 'marquee'; bounds: VectorBounds }\n\t| { type: 'move'; dx: number; dy: number }\n\t| { type: 'scale'; handle: VectorTransformHandle; sx: number; sy: number }\n\t| { type: 'rotate'; angle: number }\n\t| { type: 'anchors'; dx: number; dy: number }\n\t| { type: 'handle'; ref: VectorHandleRef }\n\t| { type: 'bend'; ref: VectorSegmentRef }\n\t| { type: 'corner'; ref: VectorAnchorRef; radius: number }\n\t| { type: 'draw'; tool: VectorTool; nodeId: string; bounds: VectorBounds; string?: [Vec2, Vec2] }\n\t| { type: 'stroke'; tool: 'knife' | 'eraser'; points: Vec2[]; width: number }\n\t| { type: 'builder'; mode: 'merge' | 'erase'; points: Vec2[] }\n\t| { type: 'width'; ref: VectorWidthPointRef; mode: 'width' | 'move' | 'copy'; width: number }\n\t| { type: 'pen'; nodeId: string }\n\t/** A gradient tool drag: drawing a new vector, or a handle, stop, midpoint or the bar (`removing`: a stop dragged off the bar). */\n\t| { type: 'gradient'; part: 'create' | VectorGradientPart['kind']; handle?: VectorGradientHandle; removing?: boolean }\n\t/** Free Distort: the selection box's corners as dragged so far (document space, clockwise from the top left). */\n\t| { type: 'distort'; mode: VectorDistortMode | 'skew'; corners: Vec2[] }\n\t/** Envelope tool: a mesh point (`index`) or the surface (`index` null) being dragged. */\n\t| { type: 'envelope'; nodeId: string; index: number | null }\n\t| { type: 'pan' };\n\n/** A snapshot of the editor. The same object is returned until something changes. */\nexport interface VectorEditorState {\n\tdocument: VectorDocument;\n\ttool: VectorTool;\n\t/** Selected node ids (top-level nodes or group members picked with the direct tool). */\n\tselection: readonly string[];\n\t/** Selected anchors (direct tool). */\n\tselectedAnchors: readonly VectorAnchorRef[];\n\t/** The selected width points (width tool, all on one path); Delete removes them. */\n\tselectedWidthPoints: readonly VectorWidthPointRef[];\n\t/** The width point open for numeric editing (double-click with the width tool), if any. */\n\twidthPointEdit: VectorWidthPointEdit | null;\n\t/** The path whose anchors are being edited, if any. */\n\teditingId: string | null;\n\t/** Axis-aligned bounds of the selected nodes in document units. */\n\tselectionBounds: VectorBounds | null;\n\t/** The selection box, rotated with the selection when its nodes share a rotation. */\n\tselectionFrame: VectorSelectionFrame | null;\n\tviewport: VectorViewport;\n\tdefaults: Readonly<Required<Pick<VectorDefaults, 'polygonSides' | 'starPoints' | 'starInnerRatio' | 'cornerRadius'>> & Pick<VectorDefaults, 'cornerKind'> & VectorStyle>;\n\tsnap: VectorSnapOptions;\n\tediting: VectorPathEditOptions;\n\t/** Smart guides of the snap in progress, in document units (null when there are none). */\n\tguides: VectorSnapGuides | null;\n\thitRadius: number;\n\thover: VectorHover | null;\n\t/** A CSS cursor for the canvas. */\n\tcursor: string;\n\tinteraction: VectorInteraction | null;\n\t/** The path the pen tool is adding to. */\n\tpen: { nodeId: string; subpath: number } | null;\n\t/** Last pointer position in document units (for the pen preview), or null when outside. */\n\tpointer: Vec2 | null;\n\t/** Shape Builder and paint bucket highlight: faces, line pieces and the gesture's trail. */\n\tbuilder: VectorBuilderPreview | null;\n\t/** The Blend tool's first click: the shape (and anchor of its first subpath) the next click blends from. */\n\tblendStart: VectorBlendStart | null;\n\t/** Options new blends get. */\n\tblendDefaults: VectorBlendOptions;\n\t/** The paint the gradient tool and gradient editor work on, and the selected stop (index into the sorted stops). */\n\tgradientEdit: { target: VectorGradientTarget; stop: number | null };\n\t/**\n\t * Free Distort mode of the selection box: dragging a corner distorts in perspective (each corner\n\t * on its own; Shift+Alt+Mod: symmetric perspective), a side moves its two corners, and Mod-dragging\n\t * a side skews along it (Alt: about the centre).\n\t */\n\tfreeDistort: boolean;\n\tcanUndo: boolean;\n\tcanRedo: boolean;\n\tundoLabel: string;\n\tredoLabel: string;\n\t/** Bumped on every change. */\n\trevision: number;\n}\n\nexport type VectorActionResult = { ok: true } | { ok: false; message: string };\n\n/** The shape the Blend tool blends from (its first click). */\nexport interface VectorBlendStart {\n\tnodeId: string;\n\t/** The clicked anchor of its first subpath, or null for the shape as a whole. */\n\tanchor: number | null;\n}\n\n/** Blend settings and options of `VectorEditorController.blend`. */\nexport interface VectorBlendInput extends VectorBlendOptions {\n\t/** Nodes to blend (default: the selection), in stacking order unless `keepOrder`. */\n\tids?: readonly string[];\n\t/** Blend in the order given instead of stacking order. */\n\tkeepOrder?: boolean;\n\t/** Start anchor of each key's first subpath, by key id. */\n\tstarts?: Record<string, number>;\n\tname?: string;\n}\n\nconst BLEND_OPTION_KEYS = ['spacing', 'steps', 'distance', 'orientToSpine', 'linear'] as const;\n\n/** The blend options in `input`, valid ones only. */\nfunction blendOptionsOf(input: Partial<VectorBlendOptions>): VectorBlendOptions {\n\tconst out: VectorBlendOptions = {};\n\tif (input.spacing === 'steps' || input.spacing === 'distance' || input.spacing === 'smoothColor') out.spacing = input.spacing;\n\tif (typeof input.steps === 'number' && Number.isFinite(input.steps)) out.steps = Math.min(1000, Math.max(1, Math.round(input.steps)));\n\tif (typeof input.distance === 'number' && Number.isFinite(input.distance) && input.distance > 0) out.distance = input.distance;\n\tif (typeof input.orientToSpine === 'boolean') out.orientToSpine = input.orientToSpine;\n\tif (typeof input.linear === 'boolean') out.linear = input.linear;\n\treturn out;\n}\n\n/**\n * What the Shape Builder or paint bucket highlights, in document units: the faces (filled paths\n * as SVG path data) under the pointer or touched by the drag, the line pieces an erase would\n * delete, and the drag's trail. `mode` is `merge`, `erase` (Alt) or `fill` (paint bucket).\n */\nexport interface VectorBuilderPreview {\n\tmode: 'merge' | 'erase' | 'fill';\n\tfaces: BezierPath[];\n\tlines: BezierPath[];\n\ttrail: Vec2[] | null;\n}\n\n/** Result of a Shape Builder gesture. */\nexport interface VectorShapeBuilderResult {\n\tok: boolean;\n\tmessage?: string;\n\t/** Id of the merged shape (none when erasing). */\n\tmerged: string | null;\n\tfaces: number;\n\tlines: number;\n\t/** Outline edges erased (cut out of the paths they lie on). */\n\tedges: number;\n}\n\n/** A face of the Shape Builder map (document units). */\nexport interface VectorShapeBuilderFace {\n\tindex: number;\n\t/** SVG path data. */\n\td: string;\n\tarea: number;\n\t/** Ids of the paths whose fill covers it, bottom to top (empty for an area only outlines enclose). */\n\tsources: string[];\n\t/** A point inside it. */\n\tpoint: Vec2 | null;\n}\n\nexport interface AddVectorNodeOptions {\n\t/** Group to add into (default: the root). */\n\tparentId?: string;\n\t/** Position in the parent's list (default: on top). */\n\tindex?: number;\n\t/** Select the new node (default true). */\n\tselect?: boolean;\n\t/** Undo step label. */\n\tlabel?: string;\n}\n\n/** A shape description for `addShape` (and the agent command of the same name). */\nexport interface VectorShapeInput extends VectorStyle {\n\tkind: 'rect' | 'ellipse' | 'polygon' | 'star' | 'line';\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\t/** Live corner radius of a rectangle, polygon or star (default: the editor default). */\n\tcornerRadius?: number;\n\tcornerKind?: VectorCornerKind;\n\tsides?: number;\n\tpoints?: number;\n\tinnerRatio?: number;\n\tname?: string;\n}\n\n/** Every field of `VectorStyle`, in the order style panels and commands list them. */\nexport const VECTOR_STYLE_KEYS = [\n\t'fill',\n\t'stroke',\n\t'strokeWidth',\n\t'strokeLinecap',\n\t'strokeLinejoin',\n\t'strokeDasharray',\n\t'fillRule',\n\t'strokeAlign',\n\t'startArrow',\n\t'endArrow',\n\t'arrowAlign',\n\t'startArrowScale',\n\t'endArrowScale',\n\t'strokeWidthProfile'\n] as const satisfies readonly (keyof VectorStyle)[];\n\n/** Clipboard payload type written by `copy()`. */\nexport const VECTOR_CLIPBOARD_TYPE = 'pixerate/vector';\n\nconst DEFAULT_DEFAULTS = {\n\tfill: '#d4d4d8',\n\tstroke: '#18181b',\n\tstrokeWidth: 2,\n\tpolygonSides: 6,\n\tstarPoints: 5,\n\tstarInnerRatio: 0.5,\n\tcornerRadius: 0\n};\n\nconst MIN_ZOOM = 0.05;\nconst MAX_ZOOM = 64;\n/** Screen distance of the rotation handle above the selection box. */\nexport const VECTOR_ROTATE_HANDLE_OFFSET = 24;\n\n// ---------------------------------------------------------------------------\n// Helpers shared with the render module\n// ---------------------------------------------------------------------------\n\nconst sameRef = (a: VectorAnchorRef, b: VectorAnchorRef) => a.nodeId === b.nodeId && a.subpath === b.subpath && a.index === b.index;\n\n/** Ids of the path nodes whose anchors are shown (the edited path plus selected paths). */\nexport function getEditablePathIds(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen'>): string[] {\n\tif (state.tool !== 'direct' && state.tool !== 'pen') return [];\n\tconst ids = new Set<string>();\n\tif (state.pen) ids.add(state.pen.nodeId);\n\tif (state.tool === 'direct') {\n\t\tif (state.editingId) ids.add(state.editingId);\n\t\tfor (const id of state.selection) {\n\t\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) ids.add(p.id);\n\t\t}\n\t}\n\treturn [...ids].filter((id) => findVectorNode(state.document.nodes, id)?.type === 'path');\n}\n\n/** Every anchor drawn on the canvas. */\nexport function getVisibleAnchors(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen'>): VectorAnchorRef[] {\n\tconst out: VectorAnchorRef[] = [];\n\tfor (const id of getEditablePathIds(state)) {\n\t\tconst node = findVectorNode(state.document.nodes, id) as VectorPathNode;\n\t\tnode.subpaths.forEach((sp, s) => sp.anchors.forEach((_, i) => out.push({ nodeId: id, subpath: s, index: i })));\n\t}\n\treturn out;\n}\n\n/**\n * Handles drawn on the canvas: those of selected anchors and of the segments next to them\n * (direct tool), or of the last anchor of the pen path.\n */\nexport function getVisibleHandles(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen' | 'selectedAnchors'>\n): VectorHandleRef[] {\n\tconst out: VectorHandleRef[] = [];\n\tconst seen = new Set<string>();\n\tconst push = (node: VectorPathNode, s: number, i: number, handle: 'in' | 'out') => {\n\t\tconst sp = node.subpaths[s];\n\t\tconst a = sp?.anchors[i];\n\t\tif (!a || !a[handle]) return;\n\t\tconst key = `${node.id}:${s}:${i}:${handle}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tout.push({ nodeId: node.id, subpath: s, index: i, handle });\n\t};\n\tif (state.tool === 'pen' && state.pen) {\n\t\tconst node = findVectorNode(state.document.nodes, state.pen.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[state.pen.subpath] : undefined;\n\t\tif (node?.type === 'path' && sp) {\n\t\t\tconst last = sp.anchors.length - 1;\n\t\t\tpush(node, state.pen.subpath, last, 'in');\n\t\t\tpush(node, state.pen.subpath, last, 'out');\n\t\t}\n\t\treturn out;\n\t}\n\tif (state.tool !== 'direct') return out;\n\tconst editable = new Set(getEditablePathIds(state));\n\tfor (const ref of state.selectedAnchors) {\n\t\tif (!editable.has(ref.nodeId)) continue;\n\t\tconst node = findVectorNode(state.document.nodes, ref.nodeId) as VectorPathNode;\n\t\tconst sp = node.subpaths[ref.subpath];\n\t\tif (!sp) continue;\n\t\tconst n = sp.anchors.length;\n\t\tpush(node, ref.subpath, ref.index, 'in');\n\t\tpush(node, ref.subpath, ref.index, 'out');\n\t\tconst prev = ref.index > 0 ? ref.index - 1 : sp.closed ? n - 1 : -1;\n\t\tconst next = ref.index < n - 1 ? ref.index + 1 : sp.closed ? 0 : -1;\n\t\tif (prev >= 0) push(node, ref.subpath, prev, 'out');\n\t\tif (next >= 0) push(node, ref.subpath, next, 'in');\n\t}\n\treturn out;\n}\n\n/** Live corner widgets sit at least this far inside their corner (screen px along each side of a right angle). */\nexport const VECTOR_CORNER_WIDGET_INSET = 10;\n\n/** A live corner widget of the direct tool: drag it to round the corners, Alt-click to change their kind. */\nexport interface VectorCornerWidget {\n\tref: VectorAnchorRef;\n\t/** Document position of the widget. */\n\tx: number;\n\ty: number;\n\t/** The radius stored on the anchor and the radius drawn (no larger than fits). */\n\tradius: number;\n\tdrawnRadius: number;\n\tkind: VectorCornerKind;\n\t/** The corner in its node's own space. */\n\tcorner: VectorCornerInfo;\n}\n\n/**\n * The live corner widgets the direct tool shows: on each editable path, at its selected corner\n * anchors (or at every corner when none of its anchors is selected). Corners whose sides are\n * shorter than three insets on screen hide theirs. Dragging one sets the radius of all of them.\n * Ported from ArtCraft vectorcraft `crates/tools/src/corners.rs` (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md), as is the `corner` drag below.\n */\nexport function getVectorCornerWidgets(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen' | 'selectedAnchors' | 'viewport'>\n): VectorCornerWidget[] {\n\tif (state.tool !== 'direct' || state.pen) return [];\n\tconst zoom = state.viewport.zoom;\n\tconst out: VectorCornerWidget[] = [];\n\tfor (const id of getEditablePathIds(state)) {\n\t\tconst node = findVectorNode(state.document.nodes, id) as VectorPathNode;\n\t\tconst picked = state.selectedAnchors.filter((r) => r.nodeId === id);\n\t\tconst m = vectorWorldMatrix(state.document.nodes, id) ?? IDENTITY_MATRIX;\n\t\tfor (const c of vectorCorners(node.subpaths)) {\n\t\t\tif (picked.length && !picked.some((r) => r.subpath === c.subpath && r.index === c.index)) continue;\n\t\t\tconst side = Math.min(c.lu, c.lv);\n\t\t\tif (side * zoom < 3 * VECTOR_CORNER_WIDGET_INSET) continue;\n\t\t\tconst a = node.subpaths[c.subpath].anchors[c.index];\n\t\t\tconst radius = a.corner?.radius ?? 0;\n\t\t\tconst drawn = fitCornerRadius(c, radius);\n\t\t\t// On the bisector at the centre of the arc as drawn, at least the inset in and at most half the shorter side.\n\t\t\tconst k = Math.min(Math.max(drawn / c.sin, VECTOR_CORNER_WIDGET_INSET / (zoom * Math.sqrt(1 + c.cos))), side / 2);\n\t\t\tconst p = applyMatrix(m, cornerBisectorPoint(c, k));\n\t\t\tout.push({ ref: { nodeId: id, subpath: c.subpath, index: c.index }, x: p.x, y: p.y, radius, drawnRadius: drawn, kind: a.corner?.kind ?? 'round', corner: c });\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * The line a path's stroke follows (node space; shortened under `tip` arrowheads) and the\n * distance a side scale of 1 reaches from it (half the drawn width: twice the stroke width for\n * inside / outside strokes). Null for paths without a visible stroke.\n */\nexport function vectorStrokeWidthGeometry(node: VectorPathNode): { line: BezierPath; unit: number } | null {\n\tif (!hasPaint(node.stroke) || !((node.strokeWidth ?? 1) > 0)) return null;\n\tconst parts = vectorStrokeParts(subpathsToBezier(node.subpaths), node);\n\treturn parts.line.length ? { line: parts.line, unit: parts.drawWidth / 2 } : null;\n}\n\n/** A width point of the width tool, in document units. */\nexport interface VectorWidthHandle {\n\tref: VectorWidthPointRef;\n\t/** The point on the path. */\n\tx: number;\n\ty: number;\n\t/** Ends of its left and right sides. */\n\tleft: Vec2;\n\tright: Vec2;\n\tt: number;\n\t/** Side scales (multiples of half the stroke width). */\n\tleftScale: number;\n\trightScale: number;\n\tselected: boolean;\n}\n\n/**\n * Moves the points at `indices` of `profile` by `dt` along the path (kept in 0–1) and re-sorts\n * it (stably, so steps keep their order); `renumber` maps each old index to its new one.\n */\nfunction shiftWidthPoints(profile: readonly VectorWidthPoint[], indices: readonly number[], dt: number): { points: VectorWidthPoint[]; renumber: Map<number, number> } {\n\tconst moving = new Set(indices);\n\tconst tagged = profile.map((p, i) => ({ p: moving.has(i) ? { ...p, t: Math.min(Math.max(p.t + dt, 0), 1) } : { ...p }, i }));\n\ttagged.sort((a, b) => a.p.t - b.p.t || a.i - b.i);\n\treturn { points: tagged.map((x) => x.p), renumber: new Map(tagged.map((x, k) => [x.i, k])) };\n}\n\n/**\n * The width points the width tool shows: every profile point on every subpath of the stroke\n * under the pointer, the selected paths and the stroke being edited. Ported from ArtCraft\n * vectorcraft `crates/tools/src/distort/width.rs` (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md), as are the `width` drag and hover below.\n */\nexport function getVectorWidthHandles(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'tool' | 'hover' | 'interaction' | 'selectedWidthPoints'>\n): VectorWidthHandle[] {\n\tif (state.tool !== 'width') return [];\n\tconst ids = new Set<string>();\n\tfor (const id of state.selection) {\n\t\tconst n = findVectorNode(state.document.nodes, id);\n\t\tif (n) for (const p of collectPathNodes(n)) ids.add(p.id);\n\t}\n\tif (state.hover?.nodeId) ids.add(state.hover.nodeId);\n\tif (state.interaction?.type === 'width') ids.add(state.interaction.ref.nodeId);\n\tfor (const r of state.selectedWidthPoints) ids.add(r.nodeId);\n\tconst out: VectorWidthHandle[] = [];\n\tfor (const id of ids) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node?.type !== 'path' || node.visible === false || !node.strokeWidthProfile?.length) continue;\n\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\tif (!g) continue;\n\t\tconst profile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\tconst m = vectorWorldMatrix(state.document.nodes, id) ?? IDENTITY_MATRIX;\n\t\tconst contours = node.subpaths.length;\n\t\tfor (let sp = 0; sp < contours; sp++) {\n\t\t\tprofile.forEach((w, index) => {\n\t\t\t\tconst at = strokePositionPoint(g.line, sp, w.t);\n\t\t\t\tif (!at) return;\n\t\t\t\tconst n = { x: at.tangent[1], y: -at.tangent[0] };\n\t\t\t\tconst c = { x: at.point[0], y: at.point[1] };\n\t\t\t\tconst p = applyMatrix(m, c);\n\t\t\t\tconst l = applyMatrix(m, { x: c.x + n.x * w.left * g.unit, y: c.y + n.y * w.left * g.unit });\n\t\t\t\tconst r = applyMatrix(m, { x: c.x - n.x * w.right * g.unit, y: c.y - n.y * w.right * g.unit });\n\t\t\t\tout.push({\n\t\t\t\t\tref: { nodeId: id, index, subpath: sp },\n\t\t\t\t\tx: p.x,\n\t\t\t\t\ty: p.y,\n\t\t\t\t\tleft: l,\n\t\t\t\t\tright: r,\n\t\t\t\t\tt: w.t,\n\t\t\t\t\tleftScale: w.left,\n\t\t\t\t\trightScale: w.right,\n\t\t\t\t\tselected: state.selectedWidthPoints.some((r) => r.nodeId === id && r.index === index)\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Looks up an anchor (positions in its node's own space). */\nexport function getAnchor(doc: VectorDocument, ref: VectorAnchorRef): VectorAnchor | undefined {\n\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\treturn node?.type === 'path' ? node.subpaths[ref.subpath]?.anchors[ref.index] : undefined;\n}\n\n/** An anchor with its position and handles in document space (its node's transforms applied). */\nexport function getAnchorWorld(doc: VectorDocument, ref: VectorAnchorRef): { x: number; y: number; in?: Vec2; out?: Vec2; type?: VectorAnchorType } | undefined {\n\tconst a = getAnchor(doc, ref);\n\tif (!a) return undefined;\n\tconst m = vectorWorldMatrix(doc.nodes, ref.nodeId) ?? IDENTITY_MATRIX;\n\tconst p = applyMatrix(m, a);\n\treturn { x: p.x, y: p.y, ...(a.in ? { in: applyMatrix(m, a.in) } : {}), ...(a.out ? { out: applyMatrix(m, a.out) } : {}), ...(a.type ? { type: a.type } : {}) };\n}\n\n/**\n * The selection box: `angle` is the shared rotation of the selected nodes (0 when they\n * differ), `x / y / width / height` the bounds in the box's own frame (document space\n * rotated by −angle). A frame point `q` is at `rotateMatrix(angle)` applied to `q`.\n */\nexport interface VectorSelectionFrame {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\tangle: number;\n}\n\n/** The selection frame of nodes `ids` (see `VectorSelectionFrame`), or null when they have no points. */\nexport function getVectorSelectionFrame(doc: VectorDocument, ids: readonly string[]): VectorSelectionFrame | null {\n\tconst nodes = ids.map((id) => ({ node: findVectorNode(doc.nodes, id), parent: vectorParentMatrix(doc.nodes, id) ?? IDENTITY_MATRIX })).filter((n) => n.node);\n\tif (!nodes.length) return null;\n\tconst angles = nodes.map((n) => matrixRotation(multiplyMatrices(nodeMatrix(n.node!), n.parent)));\n\tconst same = angles.every((a) => Math.abs(normalizeAngle(a - angles[0])) < 1e-6);\n\tconst angle = same ? angles[0] : 0;\n\tconst unrotate = rotateMatrix(-angle);\n\tconst b = unionBounds(nodes.map((n) => vectorNodeBounds(n.node!, multiplyMatrices(n.parent, unrotate))));\n\treturn b ? { ...b, angle } : null;\n}\n\nconst normalizeAngle = (a: number) => ((((a + 180) % 360) + 360) % 360) - 180;\n\n/** Screen positions of the selection box handles for a box given in screen pixels. */\nexport function getTransformHandlePositions(box: VectorBounds): { handle: VectorTransformHandle; x: number; y: number }[] {\n\tconst { x, y, width: w, height: h } = box;\n\treturn [\n\t\t{ handle: 'nw', x, y },\n\t\t{ handle: 'n', x: x + w / 2, y },\n\t\t{ handle: 'ne', x: x + w, y },\n\t\t{ handle: 'e', x: x + w, y: y + h / 2 },\n\t\t{ handle: 'se', x: x + w, y: y + h },\n\t\t{ handle: 's', x: x + w / 2, y: y + h },\n\t\t{ handle: 'sw', x, y: y + h },\n\t\t{ handle: 'w', x, y: y + h / 2 },\n\t\t{ handle: 'rotate', x: x + w / 2, y: y - VECTOR_ROTATE_HANDLE_OFFSET }\n\t];\n}\n\n/**\n * Screen geometry of a selection box. `box` and each handle's `x / y` are the unrotated box\n * in screen pixels; draw them inside a group with `transform` (a `rotate(angle cx cy)`),\n * or use `screen` for the true on-screen positions (hit-testing).\n */\nexport interface VectorSelectionBoxGeometry {\n\tbox: VectorBounds;\n\tangle: number;\n\ttransform: string;\n\thandles: { handle: VectorTransformHandle; x: number; y: number; screen: Vec2 }[];\n\t/** The four corners on screen, clockwise from the top left. */\n\tcorners: Vec2[];\n}\n\nexport function getVectorSelectionBoxGeometry(frame: VectorSelectionFrame, viewport: VectorViewport): VectorSelectionBoxGeometry {\n\tconst z = viewport.zoom;\n\tconst box = { x: frame.x * z + viewport.x, y: frame.y * z + viewport.y, width: frame.width * z, height: frame.height * z };\n\tconst rot = rotateMatrix(frame.angle, { x: viewport.x, y: viewport.y });\n\tconst toScreen = (p: Vec2): Vec2 => (frame.angle ? applyMatrix(rot, p) : { x: p.x, y: p.y });\n\tconst handles = getTransformHandlePositions(box).map((h) => ({ ...h, screen: toScreen(h) }));\n\tconst corners = [\n\t\t{ x: box.x, y: box.y },\n\t\t{ x: box.x + box.width, y: box.y },\n\t\t{ x: box.x + box.width, y: box.y + box.height },\n\t\t{ x: box.x, y: box.y + box.height }\n\t].map(toScreen);\n\tconst r = (n: number) => Math.round(n * 1000) / 1000;\n\treturn { box, angle: frame.angle, transform: frame.angle ? `rotate(${r(frame.angle)} ${r(viewport.x)} ${r(viewport.y)})` : '', handles, corners };\n}\n\n/**\n * The node the Envelope tool edits: the one selected node with an enabled envelope, with the\n * envelope's mesh and box (node space) and the node → document matrix. Null otherwise.\n */\nexport function getVectorEnvelopeTarget(\n\tdoc: VectorDocument,\n\tselection: readonly string[]\n): { node: VectorNode; frame: { effectId: string; bounds: VectorBounds; mesh: VectorWarpMesh }; world: AffineMatrix } | null {\n\tif (selection.length !== 1) return null;\n\tconst node = findVectorNode(doc.nodes, selection[0]);\n\tif (!node || !vectorNodeEnvelope(node)) return null;\n\tconst frame = vectorEnvelopeFrame(node);\n\treturn frame ? { node, frame, world: vectorWorldMatrix(doc.nodes, node.id) ?? IDENTITY_MATRIX } : null;\n}\n\nconst RESIZE_CURSOR_ORDER = ['ew-resize', 'nwse-resize', 'ns-resize', 'nesw-resize'];\nconst HANDLE_ANGLES: Partial<Record<VectorTransformHandle, number>> = { e: 0, se: 45, s: 90, sw: 135, w: 180, nw: 225, n: 270, ne: 315 };\n\n/** The resize cursor for a handle of a box rotated by `angle` degrees. */\nexport function vectorResizeCursor(handle: VectorTransformHandle, angle = 0): string {\n\tif (handle === 'rotate') return 'grab';\n\tconst a = (((HANDLE_ANGLES[handle]! + angle) % 180) + 180) % 180;\n\treturn RESIZE_CURSOR_ORDER[Math.round(a / 45) % 4];\n}\n\n\nconst TOOL_LABELS: Record<VectorTool, string> = {\n\tselect: 'Select',\n\tdirect: 'Direct Select',\n\tpen: 'Pen',\n\tpencil: 'Pencil',\n\trect: 'Rectangle',\n\tellipse: 'Ellipse',\n\tpolygon: 'Polygon',\n\tstar: 'Star',\n\tline: 'Line',\n\tscissors: 'Scissors',\n\tknife: 'Knife',\n\teraser: 'Eraser',\n\twidth: 'Width',\n\tshapeBuilder: 'Shape Builder',\n\tpaintBucket: 'Paint Bucket',\n\tblend: 'Blend',\n\tgradient: 'Gradient',\n\tenvelope: 'Envelope Mesh'\n};\n\nconst TOOL_KEYS: Record<string, VectorTool> = {\n\tv: 'select',\n\ta: 'direct',\n\tp: 'pen',\n\tn: 'pencil',\n\tr: 'rect',\n\to: 'ellipse',\n\ty: 'polygon',\n\ts: 'star',\n\tl: 'line',\n\tc: 'scissors',\n\tk: 'knife',\n\te: 'eraser',\n\tw: 'width',\n\tm: 'shapeBuilder',\n\tb: 'paintBucket',\n\tj: 'blend',\n\tg: 'gradient',\n\tu: 'envelope'\n};\n\nexport function vectorToolLabel(tool: VectorTool): string {\n\treturn TOOL_LABELS[tool];\n}\n\n/** Keyboard shortcut of each tool (single letters, no modifiers). */\nexport const VECTOR_TOOL_SHORTCUTS: Readonly<Record<VectorTool, string>> = {\n\tselect: 'V',\n\tdirect: 'A',\n\tpen: 'P',\n\tpencil: 'N',\n\trect: 'R',\n\tellipse: 'O',\n\tpolygon: 'Y',\n\tstar: 'S',\n\tline: 'L',\n\tscissors: 'C',\n\tknife: 'K',\n\teraser: 'E',\n\twidth: 'W',\n\tshapeBuilder: 'M',\n\tpaintBucket: 'B',\n\tblend: 'J',\n\tgradient: 'G',\n\tenvelope: 'U'\n};\n\n/** Short glyphs for tool buttons (pair them with `vectorToolLabel` for the accessible name). */\nexport const VECTOR_TOOL_GLYPHS: Readonly<Record<VectorTool, string>> = {\n\tselect: '↖',\n\tdirect: '⌖',\n\tpen: '✒',\n\tpencil: '✎',\n\trect: '▭',\n\tellipse: '◯',\n\tpolygon: '⬡',\n\tstar: '☆',\n\tline: '╱',\n\tscissors: '✂',\n\tknife: '⟋',\n\teraser: '⌫',\n\twidth: '⇹',\n\tshapeBuilder: '⊕',\n\tpaintBucket: '◍',\n\tblend: '⧓',\n\tgradient: '◐',\n\tenvelope: '⌗'\n};\n\n/** Tools that drag out a shape (they snap while hovering). */\nconst SHAPE_TOOLS: ReadonlySet<VectorTool> = new Set(['rect', 'ellipse', 'polygon', 'star', 'line']);\n\nconst BOOLEAN_OPS: Record<VectorBooleanOperation, 'union' | 'difference' | 'intersection' | 'xor'> = {\n\tunion: 'union',\n\tsubtract: 'difference',\n\tintersect: 'intersection',\n\texclude: 'xor'\n};\n\nconst BOOLEAN_LABELS: Record<VectorBooleanOperation, string> = { union: 'Union', subtract: 'Subtract', intersect: 'Intersect', exclude: 'Exclude' };\n\n/** Names of the Pathfinder operations (undo steps, groups and buttons). */\nexport const VECTOR_PATHFINDER_LABELS: Readonly<Record<VectorPathfinderOperation, string>> = {\n\tdivide: 'Divide',\n\ttrim: 'Trim',\n\tmerge: 'Merge',\n\tcrop: 'Crop',\n\toutline: 'Outline',\n\tminusBack: 'Minus Back'\n};\n\n/** Replaces nodes by id anywhere in the tree (structural sharing for untouched branches). */\nfunction mapTree(nodes: readonly VectorNode[], fn: (node: VectorNode) => VectorNode | null): VectorNode[] {\n\tlet changed = false;\n\tconst out: VectorNode[] = [];\n\tfor (const node of nodes) {\n\t\tlet next = fn(node);\n\t\tif (next && next.type === 'group') {\n\t\t\tconst children = mapTree(next.children, fn);\n\t\t\tif (children !== next.children) next = { ...next, children };\n\t\t}\n\t\tif (next !== node) changed = true;\n\t\tif (next) out.push(next);\n\t}\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\n/** Replaces node `id` anywhere in the tree with `replacements` (none removes it). */\nfunction spliceTree(nodes: readonly VectorNode[], id: string, replacements: readonly VectorNode[]): VectorNode[] {\n\tlet changed = false;\n\tconst out: VectorNode[] = [];\n\tfor (const node of nodes) {\n\t\tif (node.id === id) {\n\t\t\tchanged = true;\n\t\t\tout.push(...replacements);\n\t\t\tcontinue;\n\t\t}\n\t\tif (node.type === 'group') {\n\t\t\tconst children = spliceTree(node.children, id, replacements);\n\t\t\tif (children !== node.children) {\n\t\t\t\tchanged = true;\n\t\t\t\tout.push({ ...node, children });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tout.push(node);\n\t}\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\nconst toPoint = (p: Vec2): Point => [p.x, p.y];\n\n/** A node's place and state (transform, visibility, lock, operand operation), for a node taking its place. */\nconst placementOf = (n: VectorNode) => ({\n\t...(n.transform ? { transform: n.transform } : {}),\n\t...(n.visible === false ? { visible: false } : {}),\n\t...(n.locked ? { locked: true } : {}),\n\t...(n.booleanOperation ? { booleanOperation: n.booleanOperation } : {})\n});\n\nconst isRoot = (m: AffineMatrix) => m === IDENTITY_MATRIX || (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0);\n\nlet idCounter = 0;\nconst defaultCreateId = () => `vn-${Date.now().toString(36)}${(++idCounter).toString(36)}`;\n\n// ---------------------------------------------------------------------------\n// Controller\n// ---------------------------------------------------------------------------\n\ninterface Snapshot {\n\tdoc: VectorDocument;\n\tselection: string[];\n\tanchors: VectorAnchorRef[];\n\teditingId: string | null;\n\tpen: { nodeId: string; subpath: number } | null;\n}\n\n/** Snap targets of a drag, gathered on its first move that needs them. */\ntype DragTargets = { targets?: VectorSnapTargets };\n\ntype Drag =\n\t| ({ kind: 'move'; start: Vec2; origin: VectorBounds | null; before: Snapshot; base: VectorDocument; moved: boolean; duplicated: boolean; clickId: string | null } & DragTargets)\n\t| ({ kind: 'scale'; handle: VectorTransformHandle; start: Vec2; frame: VectorSelectionFrame; before: Snapshot; base: VectorDocument; op?: string } & DragTargets)\n\t| {\n\t\t\tkind: 'envelope';\n\t\t\tnodeId: string;\n\t\t\teffectId: string;\n\t\t\t/** The mesh at the start (node space) and the document it belongs to. */\n\t\t\tbase: VectorWarpMesh;\n\t\t\tbaseDoc: VectorDocument;\n\t\t\tbefore: Snapshot;\n\t\t\tindex: number | null;\n\t\t\ts: number;\n\t\t\tt: number;\n\t\t\tstart: Vec2;\n\t\t\tmoved: boolean;\n\t }\n\t| { kind: 'rotate'; start: Vec2; center: Vec2; before: Snapshot; base: VectorDocument }\n\t| { kind: 'marquee'; start: Vec2; base: string[]; baseAnchors: VectorAnchorRef[]; anchorsMode: boolean }\n\t| ({ kind: 'anchors'; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean; clickRef: VectorAnchorRef | null; lead: VectorAnchorRef | null } & DragTargets)\n\t| ({ kind: 'handle'; ref: VectorHandleRef; before: Snapshot; base: VectorDocument } & DragTargets)\n\t| { kind: 'bend'; ref: VectorSegmentRef; t: number; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean }\n\t| { kind: 'corner'; widget: VectorCornerWidget; refs: VectorAnchorRef[]; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean; alt: boolean; shift: boolean }\n\t| { kind: 'stroke'; tool: 'knife' | 'eraser'; points: Vec2[]; before: Snapshot }\n\t| { kind: 'builder'; erase: boolean; points: Vec2[]; touched: VectorBuilderTouched; map: VectorShapeBuilderMap }\n\t| { kind: 'pull'; ref: VectorAnchorRef; before: Snapshot; base: VectorDocument; label: string; outOnly: boolean; closing: boolean; altBreaks: boolean }\n\t| ({ kind: 'shape'; tool: VectorTool; start: Vec2; nodeId: string; before: Snapshot } & DragTargets)\n\t| { kind: 'pencil'; nodeId: string; points: Point[]; before: Snapshot; lazy: LazyMouse; pressures: number[] | null; pressure: number }\n\t| {\n\t\t\tkind: 'width';\n\t\t\tref: VectorWidthPointRef;\n\t\t\t/** `copy`: Alt-drag a centre to slide a copy of the point. */\n\t\t\tmode: 'width' | 'move' | 'copy';\n\t\t\tside: 'both' | 'left' | 'right';\n\t\t\t/** The index the drag started on (the source of a copy). */\n\t\t\tsource: number;\n\t\t\t/** Other selected points of the path that move or widen with it (indices into `profile`). */\n\t\t\tgroup: number[];\n\t\t\t/** Shift-click (adding the point): a click without a move keeps the other selected points. */\n\t\t\tshift: boolean;\n\t\t\t/** Old index → new index after a group move re-sorted the profile. */\n\t\t\trenumber: Map<number, number> | null;\n\t\t\t/** The stroke line's point and left normal where the drag started (node space). */\n\t\t\torigin: Vec2;\n\t\t\tnormal: Vec2;\n\t\t\t/** Half the drawn stroke width: side scale 1 reaches this far. */\n\t\t\tunit: number;\n\t\t\tprofile: VectorWidthPoint[];\n\t\t\tbefore: Snapshot;\n\t\t\tbase: VectorDocument;\n\t\t\tstart: Vec2;\n\t\t\tmoved: boolean;\n\t\t\tcreated: boolean;\n\t }\n\t| {\n\t\t\tkind: 'gradient';\n\t\t\t/** What was grabbed: null draws a new vector over `targets`. */\n\t\t\tpart: VectorGradientPart | null;\n\t\t\tnodeId: string | null;\n\t\t\ttargets: string[];\n\t\t\tannotator: VectorGradientAnnotator | null;\n\t\t\tstart: Vec2;\n\t\t\tstartDoc: Vec2;\n\t\t\tbefore: Snapshot;\n\t\t\tbase: VectorDocument;\n\t\t\tmoved: boolean;\n\t\t\t/** The dragged stop's index now (null once dragged off the bar). */\n\t\t\tstop: number | null;\n\t }\n\t| { kind: 'pan'; start: Vec2; viewport: VectorViewport };\n\n/**\n * Headless state for a vector editor: a document of paths and groups, select / direct /\n * pen / pencil / shape tools driven by pointer and key events, undo, transforms, boolean\n * operations, alignment, grouping, SVG import / export and a viewport. Any UI forwards\n * pointer events (in canvas pixels) and renders `getState()`; `getState()` returns the same\n * object until something changes, so it works with `useSyncExternalStore` and Svelte runes.\n */\nexport class VectorEditorController {\n\treadonly history: HistoryManager;\n\tprivate doc: VectorDocument;\n\tprivate selection: string[] = [];\n\tprivate anchors: VectorAnchorRef[] = [];\n\tprivate widthPoints: VectorWidthPointRef[] = [];\n\tprivate widthEdit: VectorWidthPointEdit | null = null;\n\tprivate editingId: string | null = null;\n\tprivate pen: { nodeId: string; subpath: number } | null = null;\n\tprivate tool: VectorTool;\n\tprivate defaults: VectorEditorState['defaults'];\n\tprivate viewport: VectorViewport;\n\tprivate snap: VectorSnapOptions;\n\tprivate editing: VectorPathEditOptions;\n\tprivate hitRadius: number;\n\tprivate hover: VectorHover | null = null;\n\tprivate pointer: Vec2 | null = null;\n\tprivate drag: Drag | null = null;\n\tprivate interaction: VectorInteraction | null = null;\n\tprivate guides: VectorSnapGuides | null = null;\n\t/** Whether the last `snapDrawn` landed on an object (guides may be hidden). */\n\tprivate snappedToObject = false;\n\t/** Drawing targets for hovering the pen and shape tools, kept while the document and the excluded path stay the same. */\n\tprivate hoverTargets: { doc: VectorDocument; exclude: string; targets: VectorSnapTargets } | null = null;\n\tprivate spaceHeld = false;\n\tprivate clipboard: VectorNode[] | null = null;\n\t/** Shape Builder map of the selection, kept while the document and the selection stay the same. */\n\tprivate builderCache: { doc: VectorDocument; key: string; map: VectorShapeBuilderMap | null } | null = null;\n\t/** Paint bucket map of the visible outlines. */\n\tprivate fillCache: { doc: VectorDocument; gap: number; map: PlanarMap | null } | null = null;\n\tprivate builderPreview: VectorBuilderPreview | null = null;\n\tprivate blendStart: VectorBlendStart | null = null;\n\t/** Options new blends get (the toolbars edit them along with the selected blend's). */\n\tprivate blendDefaults: VectorBlendOptions = {};\n\tprivate gradientEdit: VectorEditorState['gradientEdit'] = { target: 'fill', stop: null };\n\tprivate freeDistort = false;\n\t/** What the highlight shows, to skip notifying when the pointer stays over the same face. */\n\tprivate builderHoverKey: string | null = null;\n\tprivate readonly createId: () => string;\n\tprivate readonly onChange?: (document: VectorDocument) => void;\n\tprivate readonly listeners = new Set<(state: VectorEditorState) => void>();\n\tprivate readonly cleanups: Array<() => void> = [];\n\tprivate applying = false;\n\t/** Set while a commit records a change that was already applied, so `restore` still reports it. */\n\tprivate committing = false;\n\tprivate revision = 0;\n\tprivate state!: VectorEditorState;\n\n\tconstructor(options: VectorEditorOptions = {}) {\n\t\tthis.history = options.history ?? new HistoryManager();\n\t\tthis.doc = options.document ? cloneVectorDocument(options.document) : { width: 800, height: 600, nodes: [] };\n\t\tthis.doc = this.refreshed(this.doc);\n\t\tthis.tool = options.tool ?? 'select';\n\t\tthis.defaults = { ...DEFAULT_DEFAULTS, ...(options.defaults ?? {}) } as VectorEditorState['defaults'];\n\t\tthis.viewport = { x: 0, y: 0, zoom: 1, ...(options.viewport ?? {}) };\n\t\tthis.snap = { ...DEFAULT_VECTOR_SNAP, ...(options.snap ?? {}) };\n\t\tthis.editing = { ...DEFAULT_VECTOR_PATH_EDIT, ...(options.editing ?? {}) };\n\t\tthis.hitRadius = options.hitRadius ?? 6;\n\t\tthis.createId = options.createId ?? defaultCreateId;\n\t\tthis.onChange = options.onChange;\n\t\tthis.freeDistort = !!options.freeDistort;\n\t\tthis.state = this.computeState();\n\t\tthis.connect();\n\t}\n\n\t/** Listens to the history (once; again after `destroy`). */\n\tprivate connect(): void {\n\t\tif (this.cleanups.length) return;\n\t\tthis.cleanups.push(\n\t\t\tthis.history.subscribe((h) => {\n\t\t\t\tif (!this.applying && this.historyDiffers(h)) this.notify();\n\t\t\t})\n\t\t);\n\t\t// Catch up on history changes made while disconnected.\n\t\tif (this.historyDiffers(this.history.getState())) this.state = this.computeState();\n\t}\n\n\tprivate historyDiffers(h: ReturnType<HistoryManager['getState']>): boolean {\n\t\tconst s = this.state;\n\t\treturn s.canUndo !== h.canUndo || s.canRedo !== h.canRedo || s.undoLabel !== h.undoName || s.redoLabel !== h.redoName;\n\t}\n\n\t/**\n\t * Stops listening to the history and drops all listeners. A later `subscribe` reconnects, so a\n\t * controller torn down by React StrictMode's double effect keeps working when it is reused.\n\t */\n\tdestroy(): void {\n\t\tthis.cleanups.splice(0).forEach((fn) => fn());\n\t\tthis.listeners.clear();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// State\n\t// -------------------------------------------------------------------------\n\n\t/** The current snapshot (stable until the next change). */\n\tgetState = (): VectorEditorState => this.state;\n\n\t/** Calls `listener` after every change. Returns an unsubscribe function. */\n\tsubscribe = (listener: (state: VectorEditorState) => void): (() => void) => {\n\t\tthis.connect();\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t};\n\n\tgetDocument(): VectorDocument {\n\t\treturn this.doc;\n\t}\n\n\tgetNode(id: string): VectorNode | undefined {\n\t\treturn findVectorNode(this.doc.nodes, id);\n\t}\n\n\tprivate computeState(): VectorEditorState {\n\t\tconst h = this.history.getState();\n\t\treturn {\n\t\t\tdocument: this.doc,\n\t\t\ttool: this.tool,\n\t\t\tselection: this.selection,\n\t\t\tselectedAnchors: this.anchors,\n\t\t\tselectedWidthPoints: this.widthPoints,\n\t\t\twidthPointEdit: this.widthEdit,\n\t\t\teditingId: this.editingId,\n\t\t\tselectionBounds: this.boundsOf(this.selection),\n\t\t\tselectionFrame: this.frameOf(this.selectedRoots()),\n\t\t\tviewport: this.viewport,\n\t\t\tdefaults: this.defaults,\n\t\t\tsnap: this.snap,\n\t\t\tediting: this.editing,\n\t\t\tguides: this.guides,\n\t\t\thitRadius: this.hitRadius,\n\t\t\thover: this.hover,\n\t\t\tcursor: this.cursorFor(),\n\t\t\tinteraction: this.interaction,\n\t\t\tpen: this.pen,\n\t\t\tpointer: this.pointer,\n\t\t\tbuilder: this.builderPreview,\n\t\t\tblendStart: this.blendStart,\n\t\t\tblendDefaults: this.blendDefaults,\n\t\t\tgradientEdit: this.gradientEdit,\n\t\t\tfreeDistort: this.freeDistort,\n\t\t\tcanUndo: h.canUndo,\n\t\t\tcanRedo: h.canRedo,\n\t\t\tundoLabel: h.undoName,\n\t\t\tredoLabel: h.redoName,\n\t\t\trevision: this.revision\n\t\t};\n\t}\n\n\t/** `doc` with its blends' steps brought up to date (the same object when they already are). */\n\tprivate refreshed(doc: VectorDocument): VectorDocument {\n\t\tconst nodes = refreshVectorBlends(doc.nodes);\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\tprivate notify(docChanged = false) {\n\t\t// Blends regenerate their steps after every edit of a key (drags included).\n\t\tconst fresh = this.refreshed(this.doc);\n\t\tif (fresh !== this.doc) this.doc = fresh;\n\t\tif (this.blendStart && !this.getNode(this.blendStart.nodeId)) this.blendStart = null;\n\t\tthis.revision++;\n\t\tthis.state = this.computeState();\n\t\tif (docChanged) this.onChange?.(this.doc);\n\t\tconst state = this.state;\n\t\tthis.listeners.forEach((listener) => {\n\t\t\ttry {\n\t\t\t\tlistener(state);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[VectorEditorController] Error in state listener:', error);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate boundsOf(ids: readonly string[]): VectorBounds | null {\n\t\treturn unionBounds(\n\t\t\tids.map((id) => {\n\t\t\t\tconst n = this.getNode(id);\n\t\t\t\treturn n ? vectorNodeBounds(n, vectorParentMatrix(this.doc.nodes, id) ?? IDENTITY_MATRIX) : null;\n\t\t\t})\n\t\t);\n\t}\n\n\tprivate frameOf(ids: readonly string[]): VectorSelectionFrame | null {\n\t\treturn getVectorSelectionFrame(this.doc, ids);\n\t}\n\n\t/** Local → document matrix of a node in `doc` (default: the current document). */\n\tprivate worldOf(id: string, doc: VectorDocument = this.doc): AffineMatrix {\n\t\treturn vectorWorldMatrix(doc.nodes, id) ?? IDENTITY_MATRIX;\n\t}\n\n\t/** A document point in node `id`'s own space. */\n\tprivate toLocal(id: string, p: Vec2, doc: VectorDocument = this.doc): Vec2 {\n\t\treturn applyMatrix(invertMatrix(this.worldOf(id, doc)), p);\n\t}\n\n\tprivate cursorFor(): string {\n\t\tif (this.drag?.kind === 'pan' || this.spaceHeld) return this.drag ? 'grabbing' : 'grab';\n\t\tif (this.drag?.kind === 'rotate') return 'grabbing';\n\t\tif (this.drag?.kind === 'move') return 'move';\n\t\tconst h = this.hover;\n\t\tswitch (this.tool) {\n\t\t\tcase 'select':\n\t\t\t\tif (h?.transformHandle && this.freeDistort && h.transformHandle !== 'rotate') return 'crosshair';\n\t\t\t\tif (h?.transformHandle) return vectorResizeCursor(h.transformHandle, this.frameOf(this.selectedRoots())?.angle ?? 0);\n\t\t\t\treturn h?.nodeId ? 'move' : 'default';\n\t\t\tcase 'envelope':\n\t\t\t\tif (this.drag?.kind === 'envelope') return 'grabbing';\n\t\t\t\tif (h?.envelope) return h.envelope.index === null ? 'grab' : 'pointer';\n\t\t\t\treturn h?.nodeId ? 'pointer' : 'default';\n\t\t\tcase 'direct':\n\t\t\t\tif (h?.anchor || h?.handle || h?.corner) return 'pointer';\n\t\t\t\tif (h?.segment) return 'copy';\n\t\t\t\treturn h?.nodeId ? 'move' : 'default';\n\t\t\tcase 'pen':\n\t\t\t\treturn h?.anchor ? 'pointer' : 'crosshair';\n\t\t\tcase 'width':\n\t\t\t\tif (this.drag?.kind === 'width') return this.drag.mode === 'width' ? 'ew-resize' : 'grabbing';\n\t\t\t\tif (h?.widthPoint) return h.widthPoint.part === 'center' ? 'grab' : 'ew-resize';\n\t\t\t\treturn h?.strokeSpot ? 'copy' : 'default';\n\t\t\tcase 'shapeBuilder':\n\t\t\t\tif (!this.builderPreview?.faces.length && !this.builderPreview?.lines.length) return 'crosshair';\n\t\t\t\treturn this.builderPreview.mode === 'erase' ? 'not-allowed' : 'cell';\n\t\t\tcase 'paintBucket':\n\t\t\t\treturn this.builderPreview ? 'cell' : 'crosshair';\n\t\t\tcase 'blend':\n\t\t\t\treturn h?.nodeId ? (this.blendStart && this.blendStart.nodeId !== h.nodeId ? 'copy' : 'pointer') : 'crosshair';\n\t\t\tcase 'gradient': {\n\t\t\t\tconst part = this.drag?.kind === 'gradient' ? this.drag.part : h?.gradient;\n\t\t\t\tif (!part) return 'crosshair';\n\t\t\t\tif (part.kind === 'bar') return this.drag ? 'grabbing' : 'copy';\n\t\t\t\tif (part.kind === 'handle' && part.handle === 'start') return this.drag ? 'grabbing' : 'move';\n\t\t\t\treturn 'pointer';\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn 'crosshair';\n\t\t}\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Undoable changes\n\t// -------------------------------------------------------------------------\n\n\tprivate snapshot(): Snapshot {\n\t\treturn { doc: this.doc, selection: this.selection, anchors: this.anchors, editingId: this.editingId, pen: this.pen };\n\t}\n\n\tprivate restore(s: Snapshot) {\n\t\tconst docChanged = s.doc !== this.doc || this.committing;\n\t\t// Undo / redo can renumber width points: drop the ones that are gone and close the editor.\n\t\tif (!this.committing) this.widthEdit = null;\n\t\tthis.committing = false;\n\t\tthis.applying = true;\n\t\ttry {\n\t\t\tthis.doc = s.doc;\n\t\t\tthis.selection = s.selection.filter((id) => this.getNode(id));\n\t\t\tthis.anchors = s.anchors.filter((r) => getAnchor(this.doc, r));\n\t\t\tthis.editingId = s.editingId && this.getNode(s.editingId) ? s.editingId : null;\n\t\t\tthis.pen = s.pen && (this.getNode(s.pen.nodeId) as VectorPathNode | undefined)?.subpaths?.[s.pen.subpath] ? s.pen : null;\n\t\t\tif (this.widthPoints.length) {\n\t\t\t\tconst kept = this.widthPoints.filter((r) => {\n\t\t\t\t\tconst n = this.getNode(r.nodeId);\n\t\t\t\t\treturn n?.type === 'path' && !!n.strokeWidthProfile?.[r.index];\n\t\t\t\t});\n\t\t\t\tif (kept.length !== this.widthPoints.length) this.widthPoints = kept;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.applying = false;\n\t\t}\n\t\tthis.notify(docChanged);\n\t}\n\n\t/**\n\t * Records the change from `before` to the current state as one undo step. Consecutive\n\t * changes with the same `merge` key (a slider drag) fold into one step.\n\t */\n\tprivate commit(name: string, before: Snapshot, merge?: string) {\n\t\tthis.doc = this.refreshed(this.doc);\n\t\tconst after = this.snapshot();\n\t\tif (before.doc === after.doc) {\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst command: Command = {\n\t\t\tname,\n\t\t\texecute: () => this.restore(after),\n\t\t\tundo: () => this.restore(before),\n\t\t\tredo: () => this.restore(after),\n\t\t\t...(merge ? { tag: merge } : {})\n\t\t};\n\t\tthis.committing = true;\n\t\tif (merge) this.history.executeMerged(command, { key: merge });\n\t\telse this.history.execute(command);\n\t\tthis.committing = false;\n\t}\n\n\t/** Runs `fn` (which updates fields) and records it as one undo step (merged by `merge` key). */\n\tprivate change(name: string, fn: () => void, merge?: string): void {\n\t\tconst before = this.snapshot();\n\t\tfn();\n\t\tthis.commit(name, before, merge);\n\t}\n\n\t/** Ends a merged edit (a slider released): the next change starts a new undo step. */\n\tendMergedEdit(): void {\n\t\tthis.history.endGesture();\n\t}\n\n\tprivate setDoc(nodes: VectorNode[]) {\n\t\tif (nodes !== this.doc.nodes) this.doc = { ...this.doc, nodes };\n\t}\n\n\tprivate replaceNode(id: string, next: VectorNode | null) {\n\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === id ? next : n)));\n\t}\n\n\tprivate freshIds<T extends VectorNode>(node: T): T {\n\t\tconst copy = cloneVectorNode(node);\n\t\tconst used = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n) => used.add(n.id));\n\t\tconst next = () => {\n\t\t\tlet id = this.createId();\n\t\t\twhile (used.has(id)) id = this.createId();\n\t\t\tused.add(id);\n\t\t\treturn id;\n\t\t};\n\t\tconst assign = (n: VectorNode) => {\n\t\t\tn.id = next();\n\t\t\tif (n.type === 'group') n.children.forEach(assign);\n\t\t};\n\t\tassign(copy);\n\t\treturn copy;\n\t}\n\n\tprivate newId(): string {\n\t\tlet id = this.createId();\n\t\twhile (this.getNode(id)) id = this.createId();\n\t\treturn id;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Viewport\n\t// -------------------------------------------------------------------------\n\n\tscreenToDocument(p: Vec2): Vec2 {\n\t\tconst v = this.viewport;\n\t\treturn { x: (p.x - v.x) / v.zoom, y: (p.y - v.y) / v.zoom };\n\t}\n\n\tdocumentToScreen(p: Vec2): Vec2 {\n\t\tconst v = this.viewport;\n\t\treturn { x: p.x * v.zoom + v.x, y: p.y * v.zoom + v.y };\n\t}\n\n\tsetViewport(viewport: Partial<VectorViewport>): void {\n\t\tconst next = { ...this.viewport, ...viewport };\n\t\tnext.zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, next.zoom));\n\t\tif (next.x === this.viewport.x && next.y === this.viewport.y && next.zoom === this.viewport.zoom) return;\n\t\tthis.viewport = next;\n\t\tthis.notify();\n\t}\n\n\t/** Zooms by `factor` keeping the document point under `screen` in place. */\n\tzoomAt(screen: Vec2, factor: number): void {\n\t\tconst zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, this.viewport.zoom * factor));\n\t\tconst doc = this.screenToDocument(screen);\n\t\tthis.setViewport({ zoom, x: screen.x - doc.x * zoom, y: screen.y - doc.y * zoom });\n\t}\n\n\tpanBy(dx: number, dy: number): void {\n\t\tthis.setViewport({ x: this.viewport.x + dx, y: this.viewport.y + dy });\n\t}\n\n\t/** Fits the artboard (or `bounds`) into a canvas of `size` screen pixels. */\n\tzoomToFit(size: { width: number; height: number }, options: { padding?: number; bounds?: VectorBounds } = {}): void {\n\t\tconst padding = options.padding ?? 40;\n\t\tconst b = options.bounds ?? { x: 0, y: 0, width: this.doc.width, height: this.doc.height };\n\t\tconst zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min((size.width - padding * 2) / (b.width || 1), (size.height - padding * 2) / (b.height || 1))));\n\t\tthis.setViewport({ zoom, x: (size.width - b.width * zoom) / 2 - b.x * zoom, y: (size.height - b.height * zoom) / 2 - b.y * zoom });\n\t}\n\n\t/** Zoom at the canvas centre-ish: positive `delta` zooms out (wheel convention). Use with `wheel`. */\n\twheel(screen: Vec2, delta: { x: number; y: number }, mods: VectorModifiers = {}): void {\n\t\tif (mods.mod) this.zoomAt(screen, Math.exp(-delta.y * 0.01));\n\t\telse this.panBy(-(mods.shift ? delta.y : delta.x), -(mods.shift ? 0 : delta.y));\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Settings\n\t// -------------------------------------------------------------------------\n\n\tsetTool(tool: VectorTool): void {\n\t\tif (tool === this.tool) return;\n\t\tthis.finishPath();\n\t\tthis.cancelDrag();\n\t\tthis.tool = tool;\n\t\tthis.hover = null;\n\t\tthis.guides = null;\n\t\tthis.widthPoints = [];\n\t\tthis.widthEdit = null;\n\t\tthis.builderPreview = null;\n\t\tthis.builderHoverKey = null;\n\t\tthis.blendStart = null;\n\t\tif (tool !== 'direct') {\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t}\n\t\tthis.notify();\n\t}\n\n\tsetDefaults(defaults: Partial<VectorDefaults>): void {\n\t\tthis.defaults = { ...this.defaults, ...defaults };\n\t\tthis.notify();\n\t}\n\n\tsetSnap(snap: Partial<VectorSnapOptions>): void {\n\t\tthis.snap = { ...this.snap, ...snap };\n\t\tif (!this.snap.guides || !this.snap.objects) this.guides = null;\n\t\tthis.notify();\n\t}\n\n\t/** Changes how deleting, dragging anchors, the pencil and the eraser behave. */\n\tsetEditing(editing: Partial<VectorPathEditOptions>): void {\n\t\tconst next = { ...this.editing, ...editing };\n\t\tnext.pencilSmoothing = Math.min(1, Math.max(0, Number.isFinite(next.pencilSmoothing) ? next.pencilSmoothing : 0));\n\t\tif (!(next.eraserSize > 0)) next.eraserSize = this.editing.eraserSize;\n\t\tthis.editing = next;\n\t\tthis.notify();\n\t}\n\n\t/** Turns object snapping on or off (the toolbar's snapping toggle). */\n\ttoggleSnapping(on: boolean = !this.snap.objects): void {\n\t\tthis.setSnap({ objects: on });\n\t}\n\n\tprivate gridValue(v: number): number {\n\t\tconst g = this.snap.grid;\n\t\treturn g > 0 ? Math.round(v / g) * g : v;\n\t}\n\n\tprivate snapPoint(p: Vec2): Vec2 {\n\t\treturn { x: this.gridValue(p.x), y: this.gridValue(p.y) };\n\t}\n\n\t/** The pull distance in document units. */\n\tprivate snapTolerance(): number {\n\t\treturn this.snap.threshold / this.viewport.zoom;\n\t}\n\n\tprivate setGuides(guides: VectorSnapGuides | null) {\n\t\tthis.guides = guides && this.snap.guides && (guides.lines.length || guides.labels.length) ? guides : null;\n\t}\n\n\t/**\n\t * Where a drawn or dragged point `p` goes: onto the smart guide `targets` (gathered by\n\t * `gather` when missing), else onto the grid, kept to `leave`'s constraint. Cmd / Ctrl\n\t * bypasses snapping.\n\t */\n\tprivate snapDrawn(p: Vec2, leave: VectorSnapLeave | null, input: VectorModifiers, targets: () => VectorSnapTargets): Vec2 {\n\t\tthis.snappedToObject = false;\n\t\tif (input.mod) {\n\t\t\tthis.setGuides(null);\n\t\t\treturn constrainToLeave(leave, p);\n\t\t}\n\t\tif (this.snap.objects) {\n\t\t\tconst withAngles = leave ? { ...leave, angles: this.snap.angles } : null;\n\t\t\tconst res = targets().snapFrom(p, withAngles, this.snapTolerance());\n\t\t\tif (res.kind) {\n\t\t\t\tthis.snappedToObject = true;\n\t\t\t\tthis.setGuides(res);\n\t\t\t\t// An axis lined up with nothing still goes to the grid.\n\t\t\t\treturn leave?.constrain ? res.point : { x: res.x ? res.point.x : this.gridValue(res.point.x), y: res.y ? res.point.y : this.gridValue(res.point.y) };\n\t\t\t}\n\t\t}\n\t\tthis.setGuides(null);\n\t\treturn constrainToLeave(leave, this.snapPoint(p));\n\t}\n\n\t/** Drawing targets for the pen and shape tools, reused while the document stays the same. */\n\tprivate drawingTargets(exclude: string | null): VectorSnapTargets {\n\t\tconst key = exclude ?? '';\n\t\tconst cached = this.hoverTargets;\n\t\tif (cached && cached.doc === this.doc && cached.exclude === key) return cached.targets;\n\t\tconst targets = VectorSnapTargets.forDrawing(this.doc, exclude ? [exclude] : []);\n\t\tthis.hoverTargets = { doc: this.doc, exclude: key, targets };\n\t\treturn targets;\n\t}\n\n\t/** Where the pointer at `p` would place a point with the pen or a shape tool (and the guides showing why). */\n\tprivate hoverSnap(p: Vec2, input: VectorModifiers): Vec2 {\n\t\tif (this.tool === 'pen') {\n\t\t\tconst sp = this.pen ? (this.getNode(this.pen.nodeId) as VectorPathNode | undefined)?.subpaths[this.pen.subpath] : undefined;\n\t\t\tif (this.pen && sp && this.hover?.anchor) {\n\t\t\t\tthis.setGuides(null);\n\t\t\t\treturn p;\n\t\t\t}\n\t\t\tconst last = this.pen && sp ? getAnchorWorld(this.doc, { nodeId: this.pen.nodeId, subpath: this.pen.subpath, index: sp.anchors.length - 1 }) : undefined;\n\t\t\tconst leave = last ? { at: { x: last.x, y: last.y }, constrain: input.shift ? ('angle' as const) : null } : null;\n\t\t\treturn this.snapDrawn(p, leave, input, () => this.drawingTargets(this.pen?.nodeId ?? null));\n\t\t}\n\t\tif (SHAPE_TOOLS.has(this.tool)) return this.snapDrawn(p, null, input, () => this.drawingTargets(null));\n\t\tthis.setGuides(null);\n\t\treturn p;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Document\n\t// -------------------------------------------------------------------------\n\n\t/** Replaces the document. Undoable unless `{ history: false }` (then history is cleared). */\n\tsetDocument(doc: VectorDocument, options: { history?: boolean; label?: string } = {}): void {\n\t\tthis.cancelDrag();\n\t\tconst next = cloneVectorDocument(doc);\n\t\tif (options.history === false) {\n\t\t\tthis.doc = next;\n\t\t\tthis.selection = [];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t\tthis.pen = null;\n\t\t\tthis.history.clear();\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tthis.change(options.label ?? 'Replace Document', () => {\n\t\t\tthis.doc = next;\n\t\t\tthis.selection = [];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t\tthis.pen = null;\n\t\t});\n\t}\n\n\t/** Changes the artboard size or background. */\n\tsetArtboard(patch: Partial<Pick<VectorDocument, 'width' | 'height' | 'background'>>): void {\n\t\tthis.change('Change Artboard', () => {\n\t\t\tthis.doc = { ...this.doc, ...patch };\n\t\t});\n\t}\n\n\t/** Replaces the document with parsed SVG markup (one undo step). */\n\tloadSvg(svg: string, options: { history?: boolean } = {}): VectorActionResult {\n\t\ttry {\n\t\t\tconst doc = parseVectorSvg(svg, { createId: () => this.createId() });\n\t\t\tthis.setDocument(doc, { history: options.history, label: 'Import SVG' });\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\t/** Adds the nodes of SVG markup on top of the document, selected. */\n\timportSvg(svg: string): VectorActionResult {\n\t\ttry {\n\t\t\tconst parsed = parseVectorSvg(svg);\n\t\t\tconst nodes = parsed.nodes.map((n) => this.freshIds(n));\n\t\t\tif (!nodes.length) return { ok: false, message: 'The SVG has no shapes the editor can read.' };\n\t\t\tthis.change('Import SVG', () => {\n\t\t\t\tthis.setDoc([...this.doc.nodes, ...nodes]);\n\t\t\t\tthis.selection = nodes.map((n) => n.id);\n\t\t\t\tthis.anchors = [];\n\t\t\t});\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\ttoSvg(options?: VectorSvgExportOptions): string {\n\t\treturn vectorDocumentToSvg(this.doc, options);\n\t}\n\n\ttoJSON(): VectorDocument {\n\t\treturn cloneVectorDocument(this.doc);\n\t}\n\n\t/** Adds a node (ids are kept unless taken). Returns its id. */\n\taddNode(node: VectorNode, options: AddVectorNodeOptions = {}): string {\n\t\tconst taken = (() => {\n\t\t\tlet clash = false;\n\t\t\twalkVectorNodes([node], (n) => {\n\t\t\t\tif (this.getNode(n.id)) clash = true;\n\t\t\t});\n\t\t\treturn clash;\n\t\t})();\n\t\tconst next = taken ? this.freshIds(node) : cloneVectorNode(node);\n\t\tthis.change(options.label ?? `Add ${next.type === 'group' ? 'Group' : (next.name ?? 'Path')}`, () => {\n\t\t\tconst insert = (list: VectorNode[]) => {\n\t\t\t\tconst copy = list.slice();\n\t\t\t\tcopy.splice(options.index ?? copy.length, 0, next);\n\t\t\t\treturn copy;\n\t\t\t};\n\t\t\tif (options.parentId) {\n\t\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === options.parentId && n.type === 'group' ? { ...n, children: insert(n.children) } : n)));\n\t\t\t} else this.setDoc(insert(this.doc.nodes));\n\t\t\tif (options.select !== false) {\n\t\t\t\tthis.selection = [next.id];\n\t\t\t\tthis.anchors = [];\n\t\t\t}\n\t\t});\n\t\treturn next.id;\n\t}\n\n\t/** Builds a path node for a shape with the current defaults (not added). */\n\tcreateShapeNode(input: VectorShapeInput): VectorPathNode {\n\t\tconst b = { x: input.x, y: input.y, width: input.width, height: input.height };\n\t\tconst d = this.defaults;\n\t\tlet subpath: VectorSubpath;\n\t\tswitch (input.kind) {\n\t\t\tcase 'rect':\n\t\t\t\tsubpath = rectSubpath(b);\n\t\t\t\tbreak;\n\t\t\tcase 'ellipse':\n\t\t\t\tsubpath = ellipseSubpath(b);\n\t\t\t\tbreak;\n\t\t\tcase 'polygon':\n\t\t\t\tsubpath = polygonSubpath(b, input.sides ?? d.polygonSides);\n\t\t\t\tbreak;\n\t\t\tcase 'star':\n\t\t\t\tsubpath = starSubpath(b, input.points ?? d.starPoints, input.innerRatio ?? d.starInnerRatio);\n\t\t\t\tbreak;\n\t\t\tcase 'line':\n\t\t\t\tsubpath = lineSubpath({ x: b.x, y: b.y }, { x: b.x + b.width, y: b.y + b.height });\n\t\t\t\tbreak;\n\t\t}\n\t\tconst radius = input.cornerRadius ?? d.cornerRadius;\n\t\tconst kind = input.cornerKind ?? d.cornerKind;\n\t\t// Live corners: the shape keeps its sharp anchors, so the radius stays editable.\n\t\tif ((input.kind === 'rect' || input.kind === 'polygon' || input.kind === 'star') && radius > 0) subpath = setSubpathCorners(subpath, radius, kind);\n\t\tconst names = { rect: 'Rectangle', ellipse: 'Ellipse', polygon: 'Polygon', star: 'Star', line: 'Line' };\n\t\tconst style = this.styleFor(input.kind === 'line');\n\t\tconst own: VectorStyle = {};\n\t\tfor (const key of VECTOR_STYLE_KEYS) {\n\t\t\tif (input[key] !== undefined) (own as any)[key] = input[key];\n\t\t}\n\t\treturn { id: this.newId(), type: 'path', name: input.name ?? names[input.kind], ...style, ...own, subpaths: [subpath] };\n\t}\n\n\t/** Adds a shape drawn with the current defaults. Returns its id. */\n\taddShape(input: VectorShapeInput, options: AddVectorNodeOptions = {}): string {\n\t\tconst node = this.createShapeNode(input);\n\t\treturn this.addNode(node, { label: `Add ${node.name}`, ...options });\n\t}\n\n\t/** Adds a path from SVG path data. Returns its id. */\n\taddPath(d: string, style: VectorStyle & { name?: string } = {}, options: AddVectorNodeOptions = {}): string {\n\t\tconst subpaths = bezierToSubpaths(d);\n\t\tconst node: VectorPathNode = { id: this.newId(), type: 'path', name: style.name ?? 'Path', ...this.styleFor(false), ...style, subpaths };\n\t\treturn this.addNode(node, { label: 'Add Path', ...options });\n\t}\n\n\tprivate styleFor(open: boolean): VectorStyle {\n\t\tconst d = this.defaults;\n\t\tconst out: VectorStyle = { fill: open ? null : (d.fill ?? null), stroke: d.stroke ?? null, strokeWidth: d.strokeWidth ?? 1 };\n\t\tif (d.strokeLinecap) out.strokeLinecap = d.strokeLinecap;\n\t\tif (d.strokeLinejoin) out.strokeLinejoin = d.strokeLinejoin;\n\t\tif (d.strokeDasharray) out.strokeDasharray = d.strokeDasharray;\n\t\tif (d.fillRule) out.fillRule = d.fillRule;\n\t\tif (d.strokeAlign && d.strokeAlign !== 'center') out.strokeAlign = d.strokeAlign;\n\t\tfor (const key of ['startArrow', 'endArrow', 'arrowAlign', 'startArrowScale', 'endArrowScale'] as const) if (d[key]) (out as any)[key] = d[key];\n\t\tif (d.strokeWidthProfile?.length) out.strokeWidthProfile = d.strokeWidthProfile.map((p) => ({ ...p }));\n\t\treturn out;\n\t}\n\n\t/** Merges `patch` into a node (paths take style and geometry; groups name / visibility / opacity). */\n\tupdateNode(id: string, patch: Partial<VectorPathNode> | Partial<VectorGroupNode>, options: { label?: string } = {}): VectorActionResult {\n\t\tconst node = this.getNode(id);\n\t\tif (!node) return { ok: false, message: `There is no node \"${id}\".` };\n\t\tconst { id: _id, type: _type, ...rest } = patch as any;\n\t\tthis.change(options.label ?? 'Edit Node', () => this.replaceNode(id, { ...node, ...rest } as VectorNode));\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies style (and opacity) to the selected (or given) nodes; groups pass it to every path inside. */\n\tsetStyle(style: VectorStyle & { opacity?: number }, ids: readonly string[] = this.selection, options: { label?: string } = {}): VectorActionResult {\n\t\tconst targets = new Set<string>();\n\t\tfor (const id of ids) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (!node) return { ok: false, message: `There is no node \"${id}\".` };\n\t\t\tfor (const p of collectPathNodes(node)) targets.add(p.id);\n\t\t}\n\t\tif (!targets.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(options.label ?? 'Change Style', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (targets.has(n.id) ? withStyle(n as VectorPathNode, style) : n)));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Sets the variable-width profile of the selected (or given) paths: a preset id\n\t * (`uniform` removes the profile), points, or a parametric taper / wave. Returns an error for\n\t * an unknown preset.\n\t */\n\tsetWidthProfile(\n\t\tprofile: VectorWidthPreset | readonly VectorWidthPoint[] | { taper?: VectorTaperOptions; wave?: VectorWaveOptions } | null,\n\t\toptions: { ids?: readonly string[] } = {}\n\t): VectorActionResult {\n\t\tlet points: VectorWidthPoint[];\n\t\tif (profile === null) points = [];\n\t\telse if (typeof profile === 'string') {\n\t\t\tconst preset = widthProfilePreset(profile);\n\t\t\tif (!preset) return { ok: false, message: `There is no width profile \"${profile}\".` };\n\t\t\tpoints = preset;\n\t\t} else if (Array.isArray(profile)) points = sanitizeWidthProfile(profile);\n\t\telse {\n\t\t\tconst p = profile as { taper?: VectorTaperOptions; wave?: VectorWaveOptions };\n\t\t\tpoints = p.taper || p.wave ? generateWidthProfile(p) : [];\n\t\t}\n\t\tthis.widthPoints = [];\n\t\tthis.widthEdit = null;\n\t\treturn this.setStyle({ strokeWidthProfile: points.length ? points : null }, options.ids ?? this.selection, { label: points.length ? 'Width Profile' : 'Uniform Width' });\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Gradients\n\t// -------------------------------------------------------------------------\n\n\t/** Which paint (fill or stroke) the gradient tool and editor work on. */\n\tsetGradientTarget(target: VectorGradientTarget): void {\n\t\tif (target === this.gradientEdit.target) return;\n\t\tthis.gradientEdit = { target, stop: null };\n\t\tthis.notify();\n\t}\n\n\t/** Selects a stop of the gradient being edited (index into its sorted stops), or none. */\n\tselectGradientStop(index: number | null): void {\n\t\tif (index === this.gradientEdit.stop) return;\n\t\tthis.gradientEdit = { ...this.gradientEdit, stop: index };\n\t\tthis.notify();\n\t}\n\n\t/** The gradient tool's annotator for the selection (screen pixels), or null when its paint is not a gradient. */\n\tgetGradientAnnotator(): VectorGradientAnnotator | null {\n\t\treturn getVectorGradientAnnotator(this.doc, this.selection, this.viewport, this.gradientEdit.target);\n\t}\n\n\t/** Unlocked paths of `ids` (default: the selection). */\n\tprivate gradientPaths(ids: readonly string[] = this.selection): VectorPathNode[] {\n\t\tconst out = new Map<string, VectorPathNode>();\n\t\tfor (const id of ids) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) out.set(p.id, p);\n\t\t}\n\t\treturn [...out.values()];\n\t}\n\n\t/**\n\t * Edits the gradient of the `target` paint (default: the editor's) of the selected (or given)\n\t * paths with `patch`: a colour or no paint becomes a gradient (`patch.type`, default linear,\n\t * from the colour to white). Consecutive edits with the same `merge` key are one undo step.\n\t */\n\tsetGradient(patch: VectorGradientPatch, options: { ids?: readonly string[]; target?: VectorGradientTarget; label?: string; merge?: string } = {}): VectorActionResult {\n\t\tconst target = options.target ?? this.gradientEdit.target;\n\t\tconst paths = this.gradientPaths(options.ids ?? this.selection);\n\t\tif (!paths.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst next = new Map<string, VectorPathNode>();\n\t\tfor (const path of paths) {\n\t\t\tconst paint = path[target];\n\t\t\tconst base = isVectorGradient(paint) ? paint : defaultVectorGradient(patch.type ?? 'linear', paint);\n\t\t\tconst g = applyVectorGradientPatch(base, patch);\n\t\t\tif (!g) return { ok: false, message: 'That is not a valid gradient: it needs at least one stop with an offset and a colour.' };\n\t\t\tnext.set(path.id, { ...path, [target]: g });\n\t\t}\n\t\tthis.change(options.label ?? 'Gradient', () => this.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n)), options.merge);\n\t\tconst stops = (next.values().next().value?.[target] as { stops: unknown[] } | undefined)?.stops.length ?? 0;\n\t\tif (this.gradientEdit.stop !== null && this.gradientEdit.stop >= stops) this.gradientEdit = { ...this.gradientEdit, stop: null };\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies `fn` to every target gradient of the selection (paths whose paint is not a gradient are skipped). */\n\tprivate editGradients(label: string, fn: (stops: VectorGradient['stops']) => VectorGradient['stops'] | null, merge?: string): VectorActionResult {\n\t\tconst target = this.gradientEdit.target;\n\t\tconst paths = this.gradientPaths().filter((p) => isVectorGradient(p[target]));\n\t\tif (!paths.length) return { ok: false, message: 'The selection has no gradient.' };\n\t\tconst next = new Map<string, VectorPathNode>();\n\t\tfor (const path of paths) {\n\t\t\tconst g = path[target] as VectorGradient;\n\t\t\tconst stops = fn(sortedVectorGradientStops(g));\n\t\t\tif (!stops) return { ok: false, message: 'A gradient keeps at least two stops.' };\n\t\t\tnext.set(path.id, { ...path, [target]: { ...g, stops } });\n\t\t}\n\t\tthis.change(label, () => this.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n)), merge);\n\t\treturn { ok: true };\n\t}\n\n\t/** Changes stop `index` (colour, opacity, offset or midpoint) of the selection's gradients; selects it. */\n\tsetGradientStop(index: number, patch: { color?: string; opacity?: number; offset?: number; midpoint?: number }, options: { merge?: string } = {}): VectorActionResult {\n\t\tlet moved = index;\n\t\tconst result = this.editGradients(\n\t\t\t'Gradient Stop',\n\t\t\t(stops) => {\n\t\t\t\tif (!stops[index]) return stops;\n\t\t\t\tlet next = stops.map((s, i) => {\n\t\t\t\t\tif (i !== index) return s;\n\t\t\t\t\tconst out = { ...s };\n\t\t\t\t\tif (patch.color !== undefined) out.color = patch.color;\n\t\t\t\t\tif (patch.opacity !== undefined && Number.isFinite(patch.opacity)) {\n\t\t\t\t\t\tconst o = Math.min(1, Math.max(0, patch.opacity));\n\t\t\t\t\t\tif (o < 1) out.opacity = o;\n\t\t\t\t\t\telse delete out.opacity;\n\t\t\t\t\t}\n\t\t\t\t\tif (patch.midpoint !== undefined && Number.isFinite(patch.midpoint)) {\n\t\t\t\t\t\tconst m = Math.min(0.95, Math.max(0.05, patch.midpoint));\n\t\t\t\t\t\tif (Math.abs(m - 0.5) > 1e-3) out.midpoint = m;\n\t\t\t\t\t\telse delete out.midpoint;\n\t\t\t\t\t}\n\t\t\t\t\treturn out;\n\t\t\t\t});\n\t\t\t\tif (patch.offset !== undefined && Number.isFinite(patch.offset)) ({ stops: next, index: moved } = moveVectorGradientStop(next, index, patch.offset));\n\t\t\t\treturn next;\n\t\t\t},\n\t\t\toptions.merge\n\t\t);\n\t\tif (result.ok) this.selectGradientStop(moved);\n\t\treturn result;\n\t}\n\n\t/** Adds a stop at `offset` (painting what the gradient paints there) to the selection's gradients and selects it. */\n\taddGradientStop(offset: number): VectorActionResult {\n\t\tlet index = 0;\n\t\tconst target = this.gradientEdit.target;\n\t\tconst result = this.editGradients('Add Gradient Stop', (stops) => {\n\t\t\tconst path = this.gradientPaths().find((p) => isVectorGradient(p[target]));\n\t\t\tconst r = insertVectorGradientStop({ ...(path![target] as VectorGradient), stops }, offset);\n\t\t\tindex = r.index;\n\t\t\treturn r.stops;\n\t\t});\n\t\tif (result.ok) this.selectGradientStop(index);\n\t\treturn result;\n\t}\n\n\t/** Removes stop `index` of the selection's gradients (never below two stops). */\n\tremoveGradientStop(index: number): VectorActionResult {\n\t\tconst result = this.editGradients('Delete Gradient Stop', (stops) => removeVectorGradientStop(stops, index));\n\t\tif (result.ok) this.selectGradientStop(null);\n\t\treturn result;\n\t}\n\n\t/** Reverses the selection's gradients (stops and midpoints). */\n\treverseGradient(): VectorActionResult {\n\t\treturn this.setGradient({ reverse: true }, { label: 'Reverse Gradient' });\n\t}\n\n\t/** `doc` with path `id`'s `target` paint replaced. */\n\tprivate withGradient(doc: VectorDocument, id: string, target: VectorGradientTarget, g: VectorGradient): VectorDocument {\n\t\treturn { ...doc, nodes: mapTree(doc.nodes, (n) => (n.id === id ? ({ ...n, [target]: g } as VectorNode) : n)) };\n\t}\n\n\tprivate downGradient(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\tconst a = this.getGradientAnnotator();\n\t\tlet part = a ? hitVectorGradientAnnotator(a, screen) : null;\n\t\tif (a && part) {\n\t\t\t// Alt on a radial gradient's centre grabs its focal point (they sit together until moved).\n\t\t\tif (part.kind === 'handle' && part.handle === 'start' && input.alt && a.gradient.type === 'radial') part = { kind: 'handle', handle: 'focal' };\n\t\t\tif (part.kind === 'stop') this.gradientEdit = { ...this.gradientEdit, stop: part.index };\n\t\t\tthis.drag = { kind: 'gradient', part, nodeId: a.nodeId, targets: [a.nodeId], annotator: a, start: screen, startDoc: p, before, base: this.doc, moved: false, stop: part.kind === 'stop' ? part.index : null };\n\t\t\tthis.interaction = { type: 'gradient', part: part.kind, ...(part.kind === 'handle' ? { handle: part.handle } : {}) };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\t// Elsewhere a drag draws a new vector over the path under the pointer (selecting it) or the selection.\n\t\tconst hit = this.hitPath(p);\n\t\tif (hit && !this.gradientPaths().some((n) => n.id === hit.id)) {\n\t\t\tthis.selection = [hit.id];\n\t\t\tthis.gradientEdit = { ...this.gradientEdit, stop: null };\n\t\t}\n\t\tconst targets = this.gradientPaths().map((n) => n.id);\n\t\tif (!targets.length) {\n\t\t\tif (this.selection.length) this.clearSelection();\n\t\t\treturn;\n\t\t}\n\t\tthis.drag = { kind: 'gradient', part: null, nodeId: null, targets, annotator: null, start: screen, startDoc: p, before, base: this.doc, moved: false, stop: null };\n\t\tthis.interaction = { type: 'gradient', part: 'create' };\n\t\tthis.notify();\n\t}\n\n\tprivate moveGradient(drag: Extract<Drag, { kind: 'gradient' }>, screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tif (!drag.moved && Math.hypot(screen.x - drag.start.x, screen.y - drag.start.y) < 3) return;\n\t\tdrag.moved = true;\n\t\tconst target = this.gradientEdit.target;\n\t\tconst base = drag.base;\n\t\tconst constrained = (from: Vec2, to: Vec2) => {\n\t\t\tif (!input.shift) return to;\n\t\t\tconst ang = Math.round(Math.atan2(to.y - from.y, to.x - from.x) / (Math.PI / 4)) * (Math.PI / 4);\n\t\t\tconst len = Math.hypot(to.x - from.x, to.y - from.y);\n\t\t\treturn { x: from.x + Math.cos(ang) * len, y: from.y + Math.sin(ang) * len };\n\t\t};\n\t\tif (!drag.part) {\n\t\t\tconst end = constrained(drag.startDoc, p);\n\t\t\tlet doc = base;\n\t\t\tfor (const id of drag.targets) {\n\t\t\t\tconst node = findVectorNode(base.nodes, id) as VectorPathNode | undefined;\n\t\t\t\tif (!node) continue;\n\t\t\t\tconst paint = node[target];\n\t\t\t\tconst g = isVectorGradient(paint) ? paint : defaultVectorGradient('linear', paint);\n\t\t\t\tdoc = this.withGradient(doc, id, target, setVectorGradientVector(g, vectorPathLocalBounds(node), this.toLocal(id, drag.startDoc, base), this.toLocal(id, end, base)));\n\t\t\t}\n\t\t\tthis.doc = doc;\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tconst id = drag.nodeId!;\n\t\tconst node = findVectorNode(base.nodes, id) as VectorPathNode;\n\t\tconst g = node[target] as VectorGradient;\n\t\tconst bounds = vectorPathLocalBounds(node);\n\t\tconst local = (q: Vec2) => this.toLocal(id, q, base);\n\t\tconst part = drag.part;\n\t\tlet next: VectorGradient = g;\n\t\tif (part.kind === 'handle') {\n\t\t\tlet to = p;\n\t\t\t// Shift keeps the vector at 45° steps from the start.\n\t\t\tif (part.handle === 'end' || part.handle === 'radius') to = constrained(this.screenToDocument(drag.annotator!.start), p);\n\t\t\tnext = moveVectorGradientHandle(g, bounds, part.handle, local(to), local(drag.startDoc));\n\t\t} else if (part.kind === 'bar') {\n\t\t\tnext = moveVectorGradientHandle(g, bounds, 'start', local(p), local(drag.startDoc));\n\t\t} else {\n\t\t\tconst a = drag.annotator!;\n\t\t\tconst pos = vectorGradientBarPosition(a, screen);\n\t\t\tconst stops = sortedVectorGradientStops(g);\n\t\t\tif (part.kind === 'stop') {\n\t\t\t\tconst off = Math.abs(pos.across - VECTOR_GRADIENT_STOP_GAP) > VECTOR_GRADIENT_OFF_BAR;\n\t\t\t\tconst removed = off ? removeVectorGradientStop(stops, part.index) : null;\n\t\t\t\tif (removed) {\n\t\t\t\t\tnext = { ...g, stops: removed };\n\t\t\t\t\tdrag.stop = null;\n\t\t\t\t} else {\n\t\t\t\t\tconst r = moveVectorGradientStop(stops, part.index, Math.min(1, Math.max(0, pos.offset)));\n\t\t\t\t\tnext = { ...g, stops: r.stops };\n\t\t\t\t\tdrag.stop = r.index;\n\t\t\t\t}\n\t\t\t\tthis.interaction = { type: 'gradient', part: 'stop', ...(removed ? { removing: true } : {}) };\n\t\t\t\tthis.gradientEdit = { ...this.gradientEdit, stop: drag.stop };\n\t\t\t} else {\n\t\t\t\tconst m = vectorGradientMidpointFromPosition(stops, part.index, pos.offset);\n\t\t\t\tif (m !== null) next = { ...g, stops: stops.map((s, i) => (i !== part.index ? s : Math.abs(m - 0.5) < 1e-3 ? (({ midpoint: _m, ...rest }) => rest)(s) : { ...s, midpoint: m })) };\n\t\t\t}\n\t\t}\n\t\tthis.doc = this.withGradient(base, id, target, next);\n\t\tthis.notify(true);\n\t}\n\n\tprivate upGradient(drag: Extract<Drag, { kind: 'gradient' }>) {\n\t\tconst part = drag.part;\n\t\tif (!drag.moved) {\n\t\t\tif (part?.kind === 'bar') {\n\t\t\t\tthis.addGradientStop(part.offset);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst label = !part\n\t\t\t? 'Gradient'\n\t\t\t: part.kind === 'stop'\n\t\t\t\t? drag.stop === null\n\t\t\t\t\t? 'Delete Gradient Stop'\n\t\t\t\t\t: 'Move Gradient Stop'\n\t\t\t\t: part.kind === 'midpoint'\n\t\t\t\t\t? 'Gradient Midpoint'\n\t\t\t\t\t: part.kind === 'bar' || (part.kind === 'handle' && part.handle === 'start')\n\t\t\t\t\t\t? 'Move Gradient'\n\t\t\t\t\t\t: 'Gradient Handle';\n\t\treturn this.commit(label, drag.before);\n\t}\n\n\t/** Removes one width point of a path's profile. */\n\tremoveWidthPoint(ref: Pick<VectorWidthPointRef, 'nodeId' | 'index'>): VectorActionResult {\n\t\treturn this.removeWidthPoints([ref]);\n\t}\n\n\t/** Removes width points (default: the selected ones — the width tool's Delete), as one undo step. */\n\tremoveWidthPoints(refs: readonly Pick<VectorWidthPointRef, 'nodeId' | 'index'>[] = this.widthPoints): VectorActionResult {\n\t\tconst byNode = new Map<string, number[]>();\n\t\tfor (const r of refs) {\n\t\t\tconst node = this.getNode(r.nodeId);\n\t\t\tif (node?.type !== 'path' || !node.strokeWidthProfile?.[r.index]) continue;\n\t\t\tbyNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r.index]);\n\t\t}\n\t\tif (!byNode.size) return { ok: false, message: 'There is no such width point.' };\n\t\tconst count = [...byNode.values()].reduce((n, l) => n + new Set(l).size, 0);\n\t\tthis.widthPoints = [];\n\t\tthis.widthEdit = null;\n\t\tthis.change(count > 1 ? 'Delete Width Points' : 'Delete Width Point', () => {\n\t\t\tfor (const [id, indices] of byNode) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\tconst rest = removeWidthPoints(sanitizeWidthProfile(node.strokeWidthProfile), indices);\n\t\t\t\tthis.replaceNode(id, withStyle(node, { strokeWidthProfile: rest.length ? rest : null }));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Selects width points (width tool); points on other paths than the first are dropped. */\n\tselectWidthPoints(refs: readonly VectorWidthPointRef[]): void {\n\t\tconst first = refs[0]?.nodeId;\n\t\tconst next: VectorWidthPointRef[] = [];\n\t\tfor (const r of refs) {\n\t\t\tif (r.nodeId !== first || next.some((q) => q.index === r.index)) continue;\n\t\t\tconst n = this.getNode(r.nodeId);\n\t\t\tif (n?.type === 'path' && n.strokeWidthProfile?.[r.index]) next.push({ nodeId: r.nodeId, index: r.index, subpath: r.subpath ?? 0 });\n\t\t}\n\t\tthis.widthPoints = next;\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Sets one width point numerically: `index` names an existing point of path `nodeId`, null\n\t * (or left out) adds one at `values.t`. `left` / `right` are side widths in document units\n\t * (how far the stroke reaches on each side of the path), `t` the position along each subpath\n\t * (0–1). A point moved onto another one's `t` makes a step there. Selects the point and\n\t * refreshes an open width-point editor; one undo step. Ported from ArtCraft vectorcraft's\n\t * Width Point Edit dialog (`crates/tools/src/distort/width.rs`, MIT OR Apache-2.0).\n\t */\n\tsetWidthPoint(target: { nodeId: string; index?: number | null }, values: { t?: number; left?: number; right?: number }): VectorActionResult {\n\t\tconst node = this.getNode(target.nodeId);\n\t\tif (node?.type !== 'path') return { ok: false, message: 'There is no such path.' };\n\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\tif (!g || !(g.unit > 0)) return { ok: false, message: 'The path has no visible stroke.' };\n\t\tconst num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);\n\t\tconst t = num(values.t);\n\t\tconst left = num(values.left);\n\t\tconst right = num(values.right);\n\t\tconst scale = (w: number | undefined) => (w === undefined ? undefined : Math.max(0, w) / g.unit);\n\t\tconst profile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\tlet points: VectorWidthPoint[];\n\t\tlet index: number;\n\t\tconst existing = target.index ?? null;\n\t\tif (existing === null) {\n\t\t\tif (t === undefined) return { ok: false, message: 'A new width point needs a position t.' };\n\t\t\tif (profile.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) return { ok: false, message: 'The profile has too many width points.' };\n\t\t\t({ points, index } = insertWidthPoint(profile.length ? profile : null, t, { left: scale(left), right: scale(right) }, { step: true }));\n\t\t} else {\n\t\t\tconst p = profile[existing];\n\t\t\tif (!p) return { ok: false, message: 'There is no such width point.' };\n\t\t\tconst sides = { left: scale(left) ?? p.left, right: scale(right) ?? p.right };\n\t\t\tconst tt = t === undefined ? p.t : Math.min(Math.max(t, 0), 1);\n\t\t\tif (Math.abs(tt - p.t) <= VECTOR_WIDTH_SAME_T) {\n\t\t\t\tpoints = setWidthPoint(profile, existing, sides);\n\t\t\t\tindex = existing;\n\t\t\t} else {\n\t\t\t\t// Free to pass its neighbours: take it out and put it back at its new place.\n\t\t\t\tconst rest = removeWidthPoints(profile, [existing]);\n\t\t\t\tif (rest.length) ({ points, index } = insertWidthPoint(rest, tt, sides, { step: true }));\n\t\t\t\telse {\n\t\t\t\t\tpoints = [{ t: tt, ...sides }];\n\t\t\t\t\tindex = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst subpath = this.widthEdit?.nodeId === node.id ? this.widthEdit.subpath : this.widthPoints.find((r) => r.nodeId === node.id)?.subpath ?? 0;\n\t\tconst edit = this.widthEdit;\n\t\tthis.change('Width Point', () => this.replaceNode(node.id, withStyle(node, { strokeWidthProfile: points })));\n\t\tthis.widthPoints = [{ nodeId: node.id, index, subpath }];\n\t\tif (edit?.nodeId === node.id && (edit.index === existing || existing === null)) this.widthEdit = this.widthEditFor(node.id, subpath, index, null);\n\t\tthis.notify();\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Opens the width-point editor (what a double-click with the width tool does) on a width\n\t * point, or on a spot of a stroke (`t` without `index`: applying it adds a point there).\n\t * Returns false when the path has no visible stroke.\n\t */\n\topenWidthPointEdit(target: { nodeId: string; subpath?: number; index?: number | null; t?: number }): boolean {\n\t\tconst edit = this.widthEditFor(target.nodeId, target.subpath ?? 0, target.index ?? null, target.t ?? null);\n\t\tif (!edit) return false;\n\t\tthis.widthEdit = edit;\n\t\tthis.widthPoints = edit.index === null ? [] : [{ nodeId: edit.nodeId, index: edit.index, subpath: edit.subpath }];\n\t\tthis.notify();\n\t\treturn true;\n\t}\n\n\t/** Closes the width-point editor without changing anything. */\n\tcloseWidthPointEdit(): void {\n\t\tif (!this.widthEdit) return;\n\t\tthis.widthEdit = null;\n\t\tthis.notify();\n\t}\n\n\t/** Applies `values` to the width point being edited (see `setWidthPoint`) and closes the editor. */\n\tcommitWidthPointEdit(values: { t?: number; left?: number; right?: number }): VectorActionResult {\n\t\tconst edit = this.widthEdit;\n\t\tif (!edit) return { ok: false, message: 'No width point is being edited.' };\n\t\tconst r = this.setWidthPoint({ nodeId: edit.nodeId, index: edit.index }, edit.index === null ? { t: edit.t, ...values } : values);\n\t\tif (r.ok) this.closeWidthPointEdit();\n\t\treturn r;\n\t}\n\n\t/** The editor's view of point `index` (or of the stroke at `t` when index is null) of `nodeId`. */\n\tprivate widthEditFor(nodeId: string, subpath: number, index: number | null, t: number | null): VectorWidthPointEdit | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path') return null;\n\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\tif (!g) return null;\n\t\tconst profile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\tconst p = index === null ? null : profile[index];\n\t\tif (index !== null && !p) return null;\n\t\tconst tt = p ? p.t : Math.min(Math.max(t ?? 0, 0), 1);\n\t\tconst sides = p ?? widthProfileAt(profile.length ? profile : null, tt);\n\t\tconst sp = Math.min(Math.max(0, subpath), Math.max(0, node.subpaths.length - 1));\n\t\tconst at = strokePositionPoint(g.line, sp, tt);\n\t\tconst round = (v: number) => Math.round(v * 1e6) / 1e6;\n\t\tconst q = at ? applyMatrix(this.worldOf(nodeId), { x: at.point[0], y: at.point[1] }) : { x: 0, y: 0 };\n\t\tconst point = { x: round(q.x), y: round(q.y) };\n\t\treturn { nodeId, subpath: sp, index, t: round(tt), left: round(sides.left * g.unit), right: round(sides.right * g.unit), point };\n\t}\n\n\t/**\n\t * Sets the live corner radius (and optionally the kind) of anchors: `refs`, else the selected\n\t * anchors (direct tool), else every anchor of the `ids` / selected paths. Radius 0 makes the\n\t * corners sharp again. Corners shrink to fit when drawn, so any radius is accepted.\n\t */\n\tsetCornerRadius(radius: number, options: { kind?: VectorCornerKind; refs?: readonly VectorAnchorRef[]; ids?: readonly string[] } = {}): VectorActionResult {\n\t\tif (!Number.isFinite(radius) || radius < 0) return { ok: false, message: 'The radius must be a number of at least 0.' };\n\t\tconst refs = this.cornerTargets(options);\n\t\tif (!refs.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(radius > 0 ? 'Corner Radius' : 'Sharpen Corners', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, refs, (a) => setAnchorCorner(a, radius, options.kind));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Sets the live corner kind of the same anchors as `setCornerRadius`, keeping their radii. */\n\tsetCornerKind(kind: VectorCornerKind, options: { refs?: readonly VectorAnchorRef[]; ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst refs = this.cornerTargets(options);\n\t\tif (!refs.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change('Corner Kind', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, refs, (a) => setAnchorCorner(a, a.corner?.radius ?? 0, kind));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Anchors a corner change applies to (see `setCornerRadius`). */\n\tprivate cornerTargets(options: { refs?: readonly VectorAnchorRef[]; ids?: readonly string[] }): VectorAnchorRef[] {\n\t\tif (options.refs) return options.refs.filter((r) => getAnchor(this.doc, r));\n\t\tif (!options.ids && this.tool === 'direct' && this.anchors.length) return this.anchors.slice();\n\t\tconst out: VectorAnchorRef[] = [];\n\t\tfor (const id of options.ids ?? this.selection) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (!node) continue;\n\t\t\tfor (const p of collectPathNodes(node)) {\n\t\t\t\tif (p.locked) continue;\n\t\t\t\tp.subpaths.forEach((sp, s) => sp.anchors.forEach((_, i) => out.push({ nodeId: p.id, subpath: s, index: i })));\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * Outline Stroke: replaces each selected (or given) path's stroke with a filled path of the\n\t * area it paints (alignment, joins, caps, dashes and arrowheads included), placed above a copy\n\t * of the path that keeps the fill (left out when there is none). Returns the new paths' ids.\n\t */\n\toutlineStroke(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst paths: VectorPathNode[] = [];\n\t\tfor (const id of roots) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node) for (const p of collectPathNodes(node)) if (!p.locked && hasPaint(p.stroke) && (p.strokeWidth ?? 1) > 0) paths.push(p);\n\t\t}\n\t\tif (!paths.length) return [];\n\t\tconst created: string[] = [];\n\t\tconst replace = new Map<string, VectorNode[]>();\n\t\tfor (const p of paths) {\n\t\t\t// In the node's own space: the new paths keep its transform.\n\t\t\t// As drawn: path effects applied (the outline itself carries none).\n\t\t\tconst outline = bezierToSubpaths(vectorStrokeOutlinePath(vectorAppearanceOutline(p), p));\n\t\t\tif (!outline.length) continue;\n\t\t\tconst {\n\t\t\t\tstroke,\n\t\t\t\tstrokeWidth: _w,\n\t\t\t\tstrokeLinecap: _c,\n\t\t\t\tstrokeLinejoin: _j,\n\t\t\t\tstrokeDasharray: _d,\n\t\t\t\tstrokeAlign: _a,\n\t\t\t\tstartArrow: _s,\n\t\t\t\tendArrow: _e,\n\t\t\t\tarrowAlign: _al,\n\t\t\t\tstartArrowScale: _ss,\n\t\t\t\tendArrowScale: _es,\n\t\t\t\tstrokeWidthProfile: _wp,\n\t\t\t\teffects,\n\t\t\t\t...rest\n\t\t\t} = cloneVectorNode(p);\n\t\t\tconst id = this.newId();\n\t\t\tconst strokeNode: VectorPathNode = { ...rest, id, name: `${p.name ?? 'Path'} Stroke`, subpaths: outline, fill: stroke ?? null, stroke: null, fillRule: 'nonzero' };\n\t\t\tconst list: VectorNode[] = hasPaint(p.fill) ? [{ ...rest, ...(effects ? { effects } : {}), stroke: null }, strokeNode] : [strokeNode];\n\t\t\tcreated.push(id);\n\t\t\treplace.set(p.id, list);\n\t\t}\n\t\tif (!created.length) return [];\n\t\tthis.change('Outline Stroke', () => {\n\t\t\tlet nodes = this.doc.nodes;\n\t\t\tfor (const [id, list] of replace) nodes = spliceTree(nodes, id, list);\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn created;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Path effects\n\t// -------------------------------------------------------------------------\n\n\t/** Selected (or given) nodes that can carry effects: the roots of the selection. */\n\tprivate effectTargets(ids?: readonly string[]): VectorNode[] {\n\t\treturn (ids ?? this.selectedRoots()).map((id) => this.getNode(id)).filter((n): n is VectorNode => !!n && !n.blendStep);\n\t}\n\n\t/**\n\t * Adds an effect of `type` to the selected (or given) nodes, at the bottom of each stack (or\n\t * at `index`), with default parameters merged with `params`. A repeater's copies start one\n\t * shape width apart. One undo step; returns the new effect ids (one per node, in order).\n\t */\n\taddEffect(type: VectorEffectType, options: { ids?: readonly string[]; params?: Record<string, unknown>; index?: number } = {}): string[] {\n\t\tconst targets = this.effectTargets(options.ids);\n\t\tif (!targets.length || !createVectorEffect(type, '')) return [];\n\t\tconst created: string[] = [];\n\t\tconst next = new Map<string, VectorNode>();\n\t\tfor (const node of targets) {\n\t\t\tconst list = node.effects ?? [];\n\t\t\tlet k = list.length + 1;\n\t\t\twhile (list.some((e) => e.id === `fx${k}`)) k++;\n\t\t\tconst params: Record<string, unknown> = { ...(options.params ?? {}) };\n\t\t\tif (type === 'repeater' && params.position === undefined) {\n\t\t\t\tconst b = bezierPathBounds(vectorAppearanceOutline(node));\n\t\t\t\tif (b && b.maxX - b.minX > 0) params.position = { x: Math.round((b.maxX - b.minX) * 1.25 * 100) / 100, y: 0 };\n\t\t\t}\n\t\t\tconst effect = createVectorEffect(type, `fx${k}`, params)!;\n\t\t\tconst at = options.index === undefined ? list.length : Math.min(list.length, Math.max(0, Math.round(options.index)));\n\t\t\tnext.set(node.id, { ...node, effects: [...list.slice(0, at), effect, ...list.slice(at)] } as VectorNode);\n\t\t\tcreated.push(effect.id);\n\t\t}\n\t\tthis.change(`Add ${VECTOR_EFFECT_LABELS[type]}`, () => this.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n)));\n\t\treturn created;\n\t}\n\n\tprivate editEffects(nodeId: string, label: string, fn: (effects: VectorEffect[]) => VectorEffect[] | string, merge?: string): VectorActionResult {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (!node) return { ok: false, message: `There is no node \"${nodeId}\".` };\n\t\tconst result = fn(node.effects ?? []);\n\t\tif (typeof result === 'string') return { ok: false, message: result };\n\t\tthis.change(label, () => this.replaceNode(nodeId, (result.length ? { ...node, effects: result } : (({ effects: _e, ...rest }) => rest)(node)) as VectorNode), merge);\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Turns an effect on or off and changes its parameters (unknown or invalid values are\n\t * ignored). With `merge` (true, or a key of your own), consecutive updates of the same effect\n\t * fold into one undo step, as a slider drag should; call `endMergedEdit` when it ends.\n\t */\n\tupdateEffect(nodeId: string, effectId: string, patch: { enabled?: boolean; params?: Record<string, unknown> }, options: { merge?: boolean | string } = {}): VectorActionResult {\n\t\tconst merge = options.merge === true ? `effect:${nodeId}:${effectId}` : options.merge || undefined;\n\t\tconst node = this.getNode(nodeId);\n\t\tconst current = node?.effects?.find((e) => e.id === effectId);\n\t\tconst label = current ? VECTOR_EFFECT_LABELS[current.type] ?? 'Effect' : 'Effect';\n\t\treturn this.editEffects(\n\t\t\tnodeId,\n\t\t\t`Edit ${label}`,\n\t\t\t(list) => {\n\t\t\t\tconst i = list.findIndex((e) => e.id === effectId);\n\t\t\t\tif (i < 0) return `Node \"${nodeId}\" has no effect \"${effectId}\".`;\n\t\t\t\tconst e = list[i];\n\t\t\t\tconst raw = patch.params && e.type === 'envelope' && node ? this.envelopeParams(node, e, patch.params) : patch.params;\n\t\t\t\tconst params = raw ? normalizeVectorEffectParams(e.type, raw, e.params as never) : e.params;\n\t\t\t\tconst next = { ...e, params, ...(patch.enabled !== undefined ? { enabled: patch.enabled } : {}) } as VectorEffect;\n\t\t\t\tif (next.enabled !== false) delete (next as { enabled?: boolean }).enabled;\n\t\t\t\treturn list.map((x, j) => (j === i ? next : x));\n\t\t\t},\n\t\t\tmerge\n\t\t);\n\t}\n\n\t/** Removes an effect from a node's stack. */\n\tremoveEffect(nodeId: string, effectId: string): VectorActionResult {\n\t\treturn this.editEffects(nodeId, 'Remove Effect', (list) => (list.some((e) => e.id === effectId) ? list.filter((e) => e.id !== effectId) : `Node \"${nodeId}\" has no effect \"${effectId}\".`));\n\t}\n\n\t/** Moves an effect to position `index` of its stack (0 is applied first). */\n\tmoveEffect(nodeId: string, effectId: string, index: number): VectorActionResult {\n\t\treturn this.editEffects(nodeId, 'Reorder Effects', (list) => {\n\t\t\tconst i = list.findIndex((e) => e.id === effectId);\n\t\t\tif (i < 0) return `Node \"${nodeId}\" has no effect \"${effectId}\".`;\n\t\t\tconst to = Math.min(list.length - 1, Math.max(0, Math.round(index)));\n\t\t\tconst out = list.slice();\n\t\t\tconst [e] = out.splice(i, 1);\n\t\t\tout.splice(to, 0, e);\n\t\t\treturn out;\n\t\t});\n\t}\n\n\t/**\n\t * Expand Appearance: bakes the path effects and live booleans of the selected (or given)\n\t * nodes, and of everything inside them, into plain paths. A node keeps its id (a group when\n\t * it draws as several shapes); the shapes it made get new ids. Returns the ids of the expanded\n\t * nodes (empty when none was live).\n\t */\n\texpandAppearance(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst roots = (options.ids ?? this.selectedRoots()).map((id) => this.getNode(id)).filter((n): n is VectorNode => !!n && hasVectorAppearance(n));\n\t\tif (!roots.length) return [];\n\t\tconst fresh = (n: VectorNode): VectorNode => {\n\t\t\tconst id = n.id.includes('~fx') ? this.newId() : n.id;\n\t\t\treturn n.type === 'group' ? { ...n, id, children: n.children.map(fresh) } : { ...n, id };\n\t\t};\n\t\tconst bake = (n: VectorNode): VectorNode => {\n\t\t\tif (!hasVectorAppearance(n)) return n;\n\t\t\tif (!hasOwnVectorAppearance(n)) return { ...(n as VectorGroupNode), children: (n as VectorGroupNode).children.map(bake) };\n\t\t\tlet e = expandVectorAppearance(n);\n\t\t\t// A live group that draws as one shape becomes that path, in the group's place.\n\t\t\tif (e.type === 'group' && e.children.length === 1 && e.children[0].type === 'path') {\n\t\t\t\tconst { id: _id, opacity, name, ...child } = e.children[0];\n\t\t\t\tconst k = (e.opacity ?? 1) * (opacity ?? 1);\n\t\t\t\te = { ...child, id: e.id, name: e.name ?? name, ...placementOf(e), ...(k < 1 ? { opacity: k } : {}) } as VectorPathNode;\n\t\t\t}\n\t\t\treturn fresh(e);\n\t\t};\n\t\tconst next = new Map(roots.map((n) => [n.id, bake(n)]));\n\t\tthis.change('Expand Appearance', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n));\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn roots.map((n) => n.id);\n\t}\n\n\trename(id: string, name: string): VectorActionResult {\n\t\treturn this.updateNode(id, { name }, { label: 'Rename' });\n\t}\n\n\tsetVisible(id: string, visible: boolean): VectorActionResult {\n\t\treturn this.updateNode(id, { visible }, { label: visible ? 'Show' : 'Hide' });\n\t}\n\n\tsetLocked(id: string, locked: boolean): VectorActionResult {\n\t\tconst result = this.updateNode(id, { locked }, { label: locked ? 'Lock' : 'Unlock' });\n\t\tif (locked && result.ok && this.selection.includes(id)) {\n\t\t\tthis.selection = this.selection.filter((s) => s !== id);\n\t\t\tthis.notify();\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Removes nodes by id. */\n\tremoveNodes(ids: readonly string[], options: { label?: string } = {}): VectorActionResult {\n\t\tconst drop = new Set(ids.filter((id) => this.getNode(id)));\n\t\tif (!drop.size) return { ok: false, message: 'Nothing to delete.' };\n\t\tthis.change(options.label ?? 'Delete', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = this.selection.filter((id) => !drop.has(id) && this.getNode(id));\n\t\t\tthis.anchors = this.anchors.filter((r) => getAnchor(this.doc, r));\n\t\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Selection\n\t// -------------------------------------------------------------------------\n\n\tselect(ids: readonly string[], options: { add?: boolean; toggle?: boolean } = {}): void {\n\t\tconst valid = ids.filter((id) => this.getNode(id));\n\t\tlet next: string[];\n\t\tif (options.toggle) {\n\t\t\tconst set = new Set(this.selection);\n\t\t\tfor (const id of valid) set.has(id) ? set.delete(id) : set.add(id);\n\t\t\tnext = [...set];\n\t\t} else next = options.add ? [...new Set([...this.selection, ...valid])] : valid;\n\t\tthis.selection = next;\n\t\tif (!options.add && !options.toggle) this.anchors = this.anchors.filter((r) => next.includes(r.nodeId));\n\t\tthis.notify();\n\t}\n\n\tselectAll(): void {\n\t\tif (this.tool === 'direct' && this.editingId) {\n\t\t\tthis.anchors = getVisibleAnchors(this.view());\n\t\t} else {\n\t\t\tthis.selection = this.doc.nodes.filter((n) => !n.locked && n.visible !== false).map((n) => n.id);\n\t\t}\n\t\tthis.notify();\n\t}\n\n\tclearSelection(): void {\n\t\tif (!this.selection.length && !this.anchors.length && !this.editingId) return;\n\t\tthis.selection = [];\n\t\tthis.anchors = [];\n\t\tthis.editingId = null;\n\t\tthis.notify();\n\t}\n\n\tselectAnchors(refs: readonly VectorAnchorRef[], options: { add?: boolean } = {}): void {\n\t\tconst valid = refs.filter((r) => getAnchor(this.doc, r));\n\t\tthis.anchors = options.add ? [...this.anchors, ...valid.filter((r) => !this.anchors.some((a) => sameRef(a, r)))] : valid;\n\t\tif (valid.length && !this.editingId) this.editingId = valid[0].nodeId;\n\t\tthis.notify();\n\t}\n\n\t/** Top-level ids of the selection (members of selected groups are covered by the group). */\n\tprivate selectedRoots(): string[] {\n\t\treturn this.selection.filter((id) => {\n\t\t\tlet covered = false;\n\t\t\tconst loc = locateVectorNode(this.doc.nodes, id);\n\t\t\tlet parent = loc?.parent ?? null;\n\t\t\twhile (parent) {\n\t\t\t\tif (this.selection.includes(parent.id)) covered = true;\n\t\t\t\tparent = locateVectorNode(this.doc.nodes, parent.id)?.parent ?? null;\n\t\t\t}\n\t\t\treturn !covered;\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Transforms\n\t// -------------------------------------------------------------------------\n\n\t/** `m`, given in a frame rotated by `angle`, as a document-space matrix. */\n\tprivate inFrame(angle: number, m: AffineMatrix): AffineMatrix {\n\t\tif (!angle) return m;\n\t\treturn multiplyMatrices(multiplyMatrices(rotateMatrix(-angle), m), rotateMatrix(angle));\n\t}\n\n\t/** The selection frame's corners in document space, clockwise from the top left. */\n\tprivate frameCorners(frame: VectorSelectionFrame): Vec2[] {\n\t\tconst rot = rotateMatrix(frame.angle);\n\t\treturn vectorBoxCorners(frame).map((c) => (frame.angle ? applyMatrix(rot, c) : c));\n\t}\n\n\t/** `doc` with nodes `ids` sent through `f` (a map of document space), each in its own space (see `distortVectorNode`). */\n\tprivate distorted(doc: VectorDocument, ids: ReadonlySet<string>, f: (p: Vec2) => Vec2, tolerance = VECTOR_DISTORT_TOLERANCE): VectorDocument {\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix): VectorNode[] => {\n\t\t\tlet changed = false;\n\t\t\tconst out = list.map((n) => {\n\t\t\t\tlet next = n;\n\t\t\t\tif (ids.has(n.id) && !n.locked) next = distortVectorNode(n, parent, f, tolerance);\n\t\t\t\telse if (n.type === 'group') {\n\t\t\t\t\tconst children = visit(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (children !== n.children) next = { ...n, children };\n\t\t\t\t}\n\t\t\t\tif (next !== n) changed = true;\n\t\t\t\treturn next;\n\t\t\t});\n\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t};\n\t\tconst nodes = visit(doc.nodes, IDENTITY_MATRIX);\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\t/**\n\t * Free Distort mode of the selection box (`state.freeDistort`): dragging a corner distorts the\n\t * selection in perspective, each corner on its own (Shift+Alt+Mod: symmetric perspective, the\n\t * corner beside it moving the other way); dragging a side moves its two corners; Mod-dragging a\n\t * side skews along it (Alt: about the centre). Each drag is one undo step.\n\t */\n\tsetFreeDistort(on: boolean): void {\n\t\tif (this.freeDistort === on) return;\n\t\tthis.freeDistort = on;\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Distorts the selected (or given) nodes so the corners of their selection box (clockwise from\n\t * the top left, in the box's own rotation) land on `corners` (document space): a projective map,\n\t * so straight lines stay straight. Curves are followed within `tolerance` (document units).\n\t * One undo step.\n\t */\n\tdistort(corners: readonly Vec2[], options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst frame = this.frameOf(ids);\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tif (!(frame.width > 0 && frame.height > 0)) return { ok: false, message: 'The selection has no area to distort.' };\n\t\tconst from = this.frameCorners(frame);\n\t\tconst h = corners.length === 4 ? vectorHomography(from, corners) : null;\n\t\tif (!h || !vectorHomographyKeepsQuad(h, from)) return { ok: false, message: 'The four corners must make a convex quadrilateral, clockwise from the top left.' };\n\t\tthis.change('Distort', () => {\n\t\t\tthis.doc = this.distorted(this.doc, new Set(ids), (p) => applyVectorHomography(h, p) ?? p, options.tolerance);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Skews the selected (or given) nodes along the selection box's own axes by `ax` degrees\n\t * horizontally (x' = x + tan(ax)·y: vertical lines lean right for positive angles) and `ay`\n\t * vertically, about `origin` (default: the box centre, document space). One undo step.\n\t */\n\tskew(ax: number, ay = 0, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tif (![ax, ay].every((v) => Number.isFinite(v) && Math.abs(v) < 89.9)) return { ok: false, message: 'Skew angles must be between −89.9° and 89.9°.' };\n\t\tconst origin = applyMatrix(rotateMatrix(-frame.angle), options.origin ?? this.frameCenter(frame));\n\t\treturn this.transform(this.inFrame(frame.angle, vectorSkewMatrix(ax, ay, origin)), { ids: options.ids, label: 'Skew' });\n\t}\n\n\t/** A selection box handle dragged in Free Distort mode. */\n\tprivate moveDistort(drag: Extract<Drag, { kind: 'scale' }>, p: Vec2, input: VectorPointerInput) {\n\t\tconst angle = drag.frame.angle;\n\t\tconst unrotate = (v: Vec2) => (angle ? applyMatrix(rotateMatrix(-angle), v) : v);\n\t\tconst q = unrotate(p);\n\t\tconst q0 = unrotate(drag.start);\n\t\tconst d = { x: q.x - q0.x, y: q.y - q0.y };\n\t\tconst ids = new Set(this.selectedRoots());\n\t\tconst from = this.frameCorners(drag.frame);\n\t\tconst corner = drag.handle.length === 2;\n\t\tthis.setGuides(null);\n\t\tif (!corner && input.mod) {\n\t\t\tconst m = this.inFrame(angle, vectorShearForSide(drag.frame, drag.handle, d, !!input.alt));\n\t\t\tdrag.op = 'Skew';\n\t\t\tthis.doc = this.transformed(drag.base, ids, m);\n\t\t\tthis.interaction = { type: 'distort', mode: 'skew', corners: from.map((c) => applyMatrix(m, c)) };\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tconst mode: VectorDistortMode = corner && input.mod && input.alt && input.shift ? 'perspective' : 'distort';\n\t\tconst rot = rotateMatrix(angle);\n\t\tconst quad = vectorDistortQuad(drag.frame, drag.handle, d, mode).map((c) => (angle ? applyMatrix(rot, c) : c));\n\t\tconst h = vectorHomography(from, quad);\n\t\t// A quad that folds over keeps the last good shape.\n\t\tif (!h || !vectorHomographyKeepsQuad(h, from)) return;\n\t\tdrag.op = mode === 'perspective' ? 'Perspective' : 'Distort';\n\t\tthis.doc = this.distorted(drag.base, ids, (pt) => applyVectorHomography(h, pt) ?? pt);\n\t\tthis.interaction = { type: 'distort', mode, corners: quad };\n\t\tthis.notify(true);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Envelopes\n\t// -------------------------------------------------------------------------\n\n\t/** Selected (or given) roots that can carry an envelope. */\n\tprivate envelopeTargets(ids?: readonly string[]): VectorNode[] {\n\t\treturn this.effectTargets(ids).filter((n) => !n.locked);\n\t}\n\n\t/** Envelope parameters for `node` after `patch`: a preset switched to a mesh becomes the mesh it stood for. */\n\tprivate envelopeParams(node: VectorNode, current: Extract<VectorEffect, { type: 'envelope' }> | null, patch: Record<string, unknown>): Record<string, unknown> {\n\t\tif (patch.style !== 'mesh' || patch.mesh !== undefined || !current || current.params.style === 'mesh') return patch;\n\t\tconst frame = vectorEnvelopeFrame(node, current.id);\n\t\tif (!frame) return patch;\n\t\tconst rows = typeof patch.rows === 'number' ? patch.rows : current.params.rows;\n\t\tconst columns = typeof patch.columns === 'number' ? patch.columns : current.params.columns;\n\t\treturn { ...patch, mesh: resizeVectorMesh(frame.mesh, columns, rows) };\n\t}\n\n\t/**\n\t * Gives the selected (or given) nodes an envelope distortion, or changes the one they have: a\n\t * warp preset (`style` with `bend`, `horizontal` and `vertical` in percent and `orientation`) or\n\t * a mesh (`style: 'mesh'` with `rows` and `columns`, and optionally its `mesh` points). The\n\t * envelope stays live (an `envelope` effect: edit it with the Envelope tool, Expand Appearance\n\t * bakes it). One undo step (with `merge`, consecutive changes fold into one, as a slider drag\n\t * should). Returns the envelope of each node.\n\t */\n\tenvelope(params: Partial<VectorEnvelopeParams> = {}, options: { ids?: readonly string[]; merge?: boolean } = {}): { nodeId: string; effectId: string }[] {\n\t\tconst targets = this.envelopeTargets(options.ids);\n\t\tif (!targets.length) return [];\n\t\tconst out: { nodeId: string; effectId: string }[] = [];\n\t\tconst next = new Map<string, VectorNode>();\n\t\tconst raw = params as Record<string, unknown>;\n\t\tfor (const node of targets) {\n\t\t\tconst list = node.effects ?? [];\n\t\t\tconst current = (list.find((e) => e.type === 'envelope') as Extract<VectorEffect, { type: 'envelope' }> | undefined) ?? null;\n\t\t\tif (current) {\n\t\t\t\tconst p = normalizeVectorEffectParams('envelope', this.envelopeParams(node, current, raw), current.params)!;\n\t\t\t\tconst { enabled: _e, ...rest } = current;\n\t\t\t\tnext.set(node.id, { ...node, effects: list.map((e) => (e === current ? { ...rest, params: p } : e)) } as VectorNode);\n\t\t\t\tout.push({ nodeId: node.id, effectId: current.id });\n\t\t\t} else {\n\t\t\t\tlet k = list.length + 1;\n\t\t\t\twhile (list.some((e) => e.id === `fx${k}`)) k++;\n\t\t\t\tconst effect = createVectorEffect('envelope', `fx${k}`, raw)!;\n\t\t\t\tnext.set(node.id, { ...node, effects: [...list, effect] } as VectorNode);\n\t\t\t\tout.push({ nodeId: node.id, effectId: effect.id });\n\t\t\t}\n\t\t}\n\t\tconst made = out.some((o) => !targets.find((n) => n.id === o.nodeId)?.effects?.some((e) => e.id === o.effectId));\n\t\tconst merge = options.merge ? `envelope:${out.map((o) => o.nodeId).join(',')}` : undefined;\n\t\tthis.change(made ? (params.style === 'mesh' ? 'Make Envelope with Mesh' : 'Make Envelope with Warp') : 'Edit Envelope', () => this.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n)), merge);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Make with Top Object: the topmost selected object's outline (a closed path) becomes the envelope\n\t * of the other selected objects (grouped when there are several; they must share a parent), as a\n\t * mesh of `columns × rows` patches whose border follows the outline. The top object is used up.\n\t * One undo step; returns the id of the enveloped node.\n\t */\n\tmakeEnvelopeWithTopObject(options: { ids?: readonly string[]; rows?: number; columns?: number } = {}): VectorActionResult & { nodeId?: string } {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (ids.length < 2) return { ok: false, message: 'Select the objects and, on top of them, the shape to use as the envelope.' };\n\t\tconst order = new Map<string, number>();\n\t\twalkVectorNodes(this.doc.nodes, (n) => order.set(n.id, order.size));\n\t\tconst sorted = ids.filter((id) => order.has(id)).sort((a, b) => order.get(a)! - order.get(b)!);\n\t\tconst topId = sorted[sorted.length - 1];\n\t\tconst top = this.getNode(topId);\n\t\tconst outline = top?.type === 'path' ? top.subpaths.find((sp) => sp.closed && sp.anchors.length > 1) : undefined;\n\t\tif (!top || !outline) return { ok: false, message: 'The top object must be a path with a closed outline.' };\n\t\tconst contents = sorted.slice(0, -1).map((id) => this.getNode(id)!);\n\t\tif (contents.some((n) => n.locked)) return { ok: false, message: 'Locked objects cannot be enveloped.' };\n\t\tconst parents = contents.map((n) => locateVectorNode(this.doc.nodes, n.id)?.parent?.id ?? null);\n\t\tif (parents.some((p) => p !== parents[0])) return { ok: false, message: 'The objects to envelope must be in the same group.' };\n\t\t// The node that gets the envelope: the one object, or a new group of them in place of the topmost.\n\t\tconst target: VectorNode =\n\t\t\tcontents.length === 1 ? contents[0] : { id: this.newId(), type: 'group', name: 'Envelope', children: contents.map((n) => n) };\n\t\tconst parentToDoc = parents[0] ? this.worldOf(parents[0]) : IDENTITY_MATRIX;\n\t\tconst targetToDoc = multiplyMatrices(nodeMatrix(target), parentToDoc);\n\t\tconst toLocal = multiplyMatrices(this.worldOf(topId), invertMatrix(targetToDoc));\n\t\tconst local = {\n\t\t\tclosed: true,\n\t\t\tanchors: outline.anchors.map((a) => ({\n\t\t\t\t...applyMatrix(toLocal, a),\n\t\t\t\t...(a.in ? { in: applyMatrix(toLocal, a.in) } : {}),\n\t\t\t\t...(a.out ? { out: applyMatrix(toLocal, a.out) } : {})\n\t\t\t}))\n\t\t};\n\t\tconst mesh = vectorMeshFromOutline(local, options.columns ?? 4, options.rows ?? 4);\n\t\tif (!mesh) return { ok: false, message: 'The top object’s outline is too small to use as an envelope.' };\n\t\tconst list = target.effects ?? [];\n\t\tlet k = list.length + 1;\n\t\twhile (list.some((e) => e.id === `fx${k}`)) k++;\n\t\tconst effect = createVectorEffect('envelope', `fx${k}`, { style: 'mesh', mesh })!;\n\t\tconst enveloped = { ...target, effects: [...list, effect] } as VectorNode;\n\t\tthis.change('Make Envelope with Top Object', () => {\n\t\t\tlet nodes = spliceTree(this.doc.nodes, topId, []);\n\t\t\tif (contents.length === 1) nodes = spliceTree(nodes, target.id, [enveloped]);\n\t\t\telse {\n\t\t\t\tconst last = contents[contents.length - 1].id;\n\t\t\t\tfor (const n of contents.slice(0, -1)) nodes = spliceTree(nodes, n.id, []);\n\t\t\t\tnodes = spliceTree(nodes, last, [enveloped]);\n\t\t\t}\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.selection = [target.id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn { ok: true, nodeId: target.id };\n\t}\n\n\t/**\n\t * Release: the selected (or given) nodes lose their envelope, and its shape (the mesh's border)\n\t * comes back as a path above each of them. One undo step; returns the new paths' ids.\n\t */\n\treleaseEnvelope(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst targets = this.envelopeTargets(options.ids).filter((n) => n.effects?.some((e) => e.type === 'envelope'));\n\t\tif (!targets.length) return [];\n\t\tconst created: string[] = [];\n\t\tconst replace = new Map<string, VectorNode[]>();\n\t\tfor (const node of targets) {\n\t\t\tconst effect = node.effects!.find((e) => e.type === 'envelope')!;\n\t\t\tconst frame = vectorEnvelopeFrame(node, effect.id);\n\t\t\tconst rest = node.effects!.filter((e) => e !== effect);\n\t\t\tconst { effects: _e, ...plain } = node;\n\t\t\tconst kept = (rest.length ? { ...plain, effects: rest } : plain) as VectorNode;\n\t\t\tif (!frame) {\n\t\t\t\treplace.set(node.id, [kept]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst id = this.newId();\n\t\t\tcreated.push(id);\n\t\t\tconst shape: VectorPathNode = {\n\t\t\t\tid,\n\t\t\t\ttype: 'path',\n\t\t\t\tname: 'Envelope',\n\t\t\t\t...(node.transform ? { transform: node.transform } : {}),\n\t\t\t\tsubpaths: [vectorMeshOutline(frame.mesh)],\n\t\t\t\tfill: null,\n\t\t\t\tstroke: '#808080',\n\t\t\t\tstrokeWidth: 1\n\t\t\t};\n\t\t\treplace.set(node.id, [kept, shape]);\n\t\t}\n\t\tthis.change('Release Envelope', () => {\n\t\t\tlet nodes = this.doc.nodes;\n\t\t\tfor (const [id, list] of replace) nodes = spliceTree(nodes, id, list);\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.selection = [...targets.map((n) => n.id), ...created];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn created;\n\t}\n\n\t/** The selected node the Envelope tool edits, with its mesh (node space) and node → document matrix. */\n\tprivate envelopeTarget() {\n\t\tconst target = getVectorEnvelopeTarget(this.doc, this.selection);\n\t\treturn target && !target.node.locked ? target : null;\n\t}\n\n\t/** The envelope mesh point under `screen` (handles first), or a spot inside the mesh. */\n\tprivate hitEnvelope(screen: Vec2, p: Vec2): { target: NonNullable<ReturnType<VectorEditorController['envelopeTarget']>>; index: number | null; s: number; t: number } | null {\n\t\tconst target = this.envelopeTarget();\n\t\tif (!target) return null;\n\t\tconst { mesh } = target.frame;\n\t\tconst pts = vectorMeshEditPoints(mesh);\n\t\tlet best: number | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const index of [...pts.handles.map((h) => h.index), ...pts.anchors]) {\n\t\t\tconst s = this.documentToScreen(applyMatrix(target.world, mesh.points[index]));\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\t// Handles come first, so an anchor wins only when it is clearly nearer.\n\t\t\tif (d <= this.hitRadius && d < bestD - 0.5) {\n\t\t\t\tbest = index;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\tif (best !== null) return { target, index: best, s: 0, t: 0 };\n\t\tconst local = applyMatrix(invertMatrix(target.world), p);\n\t\tconst at = vectorMeshParamAt(mesh, local);\n\t\tif (at.distance > this.tolerance()) return null;\n\t\treturn { target, index: null, s: at.s, t: at.t };\n\t}\n\n\tprivate downEnvelope(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst hit = this.hitEnvelope(screen, p);\n\t\tif (hit) {\n\t\t\tconst { node, frame } = hit.target;\n\t\t\tthis.drag = {\n\t\t\t\tkind: 'envelope',\n\t\t\t\tnodeId: node.id,\n\t\t\t\teffectId: frame.effectId,\n\t\t\t\tbase: frame.mesh,\n\t\t\t\tbaseDoc: this.doc,\n\t\t\t\tbefore: this.snapshot(),\n\t\t\t\tindex: hit.index,\n\t\t\t\ts: hit.s,\n\t\t\t\tt: hit.t,\n\t\t\t\tstart: this.toLocal(node.id, p),\n\t\t\t\tmoved: false\n\t\t\t};\n\t\t\tthis.interaction = { type: 'envelope', nodeId: node.id, index: hit.index };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\t// Elsewhere: pick the object to edit.\n\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance(), { entered: this.enteredGroups() });\n\t\tif (node) this.selection = input.shift ? (this.selection.includes(node.id) ? this.selection.filter((id) => id !== node.id) : [...this.selection, node.id]) : [node.id];\n\t\telse if (!input.shift) this.selection = [];\n\t\tthis.anchors = [];\n\t\tthis.notify();\n\t}\n\n\tprivate moveEnvelope(drag: Extract<Drag, { kind: 'envelope' }>, p: Vec2) {\n\t\tconst local = this.toLocal(drag.nodeId, p, drag.baseDoc);\n\t\tconst d = { x: local.x - drag.start.x, y: local.y - drag.start.y };\n\t\tif (!drag.moved && Math.hypot(d.x, d.y) * this.viewport.zoom < 1) return;\n\t\tdrag.moved = true;\n\t\tconst mesh = drag.index !== null ? dragVectorMeshPoint(drag.base, drag.index, d) : pullVectorMesh(drag.base, drag.s, drag.t, d);\n\t\tconst nodes = mapTree(drag.baseDoc.nodes, (n) => {\n\t\t\tif (n.id !== drag.nodeId) return n;\n\t\t\tconst effects = (n.effects ?? []).map((e) =>\n\t\t\t\te.id === drag.effectId && e.type === 'envelope'\n\t\t\t\t\t? { ...e, params: { ...e.params, style: 'mesh' as const, mesh, columns: mesh.us.length - 1, rows: mesh.vs.length - 1 } }\n\t\t\t\t\t: e\n\t\t\t);\n\t\t\treturn { ...n, effects } as VectorNode;\n\t\t});\n\t\tthis.doc = { ...drag.baseDoc, nodes };\n\t\tthis.notify(true);\n\t}\n\n\t/** Applies a matrix to the selected (or given) nodes as one undo step. */\n\ttransform(matrix: AffineMatrix, options: { ids?: readonly string[]; label?: string } = {}): VectorActionResult {\n\t\tconst ids = new Set(options.ids ?? this.selectedRoots());\n\t\tif (!ids.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(options.label ?? 'Transform', () => {\n\t\t\tthis.doc = this.transformed(this.doc, ids, matrix);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** `doc` with nodes `ids` moved by `m`, given in document space. */\n\tprivate transformed(doc: VectorDocument, ids: ReadonlySet<string>, m: AffineMatrix): VectorDocument {\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix): VectorNode[] => {\n\t\t\tlet changed = false;\n\t\t\tconst out = list.map((n) => {\n\t\t\t\tlet next = n;\n\t\t\t\tif (ids.has(n.id) && !n.locked) {\n\t\t\t\t\t// `m` in the node's parent space: parent → document, m, document → parent.\n\t\t\t\t\tconst local = isRoot(parent) ? m : multiplyMatrices(multiplyMatrices(parent, m), invertMatrix(parent));\n\t\t\t\t\tnext = transformVectorNode(n, local);\n\t\t\t\t} else if (n.type === 'group') {\n\t\t\t\t\tconst children = visit(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (children !== n.children) next = { ...n, children };\n\t\t\t\t}\n\t\t\t\tif (next !== n) changed = true;\n\t\t\t\treturn next;\n\t\t\t});\n\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t};\n\t\tconst nodes = visit(doc.nodes, IDENTITY_MATRIX);\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\ttranslate(dx: number, dy: number, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tif (this.tool === 'direct' && this.anchors.length && !options.ids) {\n\t\t\tthis.change('Move Points', () => {\n\t\t\t\tthis.doc = this.movedAnchors(this.doc, this.anchors, dx, dy);\n\t\t\t});\n\t\t\treturn { ok: true };\n\t\t}\n\t\treturn this.transform(translateMatrix(dx, dy), { ids: options.ids, label: 'Move' });\n\t}\n\n\t/** The selection frame's centre in document space. */\n\tprivate frameCenter(frame: VectorSelectionFrame): Vec2 {\n\t\treturn applyMatrix(rotateMatrix(frame.angle), { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 });\n\t}\n\n\t/**\n\t * Scales along the selection box's own axes (rotated with the selection when its nodes\n\t * share a rotation) around `origin` (default: the box centre, in document space).\n\t */\n\tscale(sx: number, sy: number = sx, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst origin = applyMatrix(rotateMatrix(-frame.angle), options.origin ?? this.frameCenter(frame));\n\t\treturn this.transform(this.inFrame(frame.angle, scaleMatrix(sx, sy, origin)), { ids: options.ids, label: 'Scale' });\n\t}\n\n\t/** Rotates clockwise by `degrees` around `origin` (default: the selection centre). */\n\trotate(degrees: number, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst origin = options.origin ?? this.frameCenter(frame);\n\t\treturn this.transform(rotateMatrix(degrees, origin), { ids: options.ids, label: 'Rotate' });\n\t}\n\n\t/** Sets each selected (or given) node's rotation to `degrees`, turning it around its own centre. */\n\tsetRotation(degrees: number, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change('Set Rotation', () => {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst frame = this.frameOf([id]);\n\t\t\t\tif (!frame) continue;\n\t\t\t\tconst delta = normalizeAngle(degrees - frame.angle);\n\t\t\t\tif (Math.abs(delta) > 1e-9) this.doc = this.transformed(this.doc, new Set([id]), rotateMatrix(delta, this.frameCenter(frame)));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Mirrors along the selection box's own axes. */\n\tflip(axis: 'horizontal' | 'vertical', options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst c = { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 };\n\t\tconst m = axis === 'horizontal' ? scaleMatrix(-1, 1, c) : scaleMatrix(1, -1, c);\n\t\treturn this.transform(this.inFrame(frame.angle, m), { ids: options.ids, label: axis === 'horizontal' ? 'Flip Horizontal' : 'Flip Vertical' });\n\t}\n\n\t/**\n\t * Aligns the selected nodes to their combined bounds, or to the artboard when one node is\n\t * selected (or `to: 'artboard'`).\n\t */\n\talign(edge: VectorAlign, options: { ids?: readonly string[]; to?: 'selection' | 'artboard' } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst target = options.to === 'artboard' || ids.length === 1 ? { x: 0, y: 0, width: this.doc.width, height: this.doc.height } : this.boundsOf(ids)!;\n\t\tthis.change(`Align ${edge[0].toUpperCase()}${edge.slice(1)}`, () => {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst b = this.boundsOf([id]);\n\t\t\t\tif (!b) continue;\n\t\t\t\tlet dx = 0;\n\t\t\t\tlet dy = 0;\n\t\t\t\tif (edge === 'left') dx = target.x - b.x;\n\t\t\t\tif (edge === 'center') dx = target.x + target.width / 2 - (b.x + b.width / 2);\n\t\t\t\tif (edge === 'right') dx = target.x + target.width - (b.x + b.width);\n\t\t\t\tif (edge === 'top') dy = target.y - b.y;\n\t\t\t\tif (edge === 'middle') dy = target.y + target.height / 2 - (b.y + b.height / 2);\n\t\t\t\tif (edge === 'bottom') dy = target.y + target.height - (b.y + b.height);\n\t\t\t\tif (dx || dy) this.doc = this.transformed(this.doc, new Set([id]), translateMatrix(dx, dy));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Spaces three or more selected nodes evenly (equal gaps). */\n\tdistribute(direction: VectorDistribute, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst items = ids.map((id) => ({ id, b: this.boundsOf([id]) })).filter((i): i is { id: string; b: VectorBounds } => !!i.b);\n\t\tif (items.length < 3) return { ok: false, message: 'Select at least three objects to distribute.' };\n\t\tconst horizontal = direction === 'horizontal';\n\t\tconst pos = (b: VectorBounds) => (horizontal ? b.x : b.y);\n\t\tconst size = (b: VectorBounds) => (horizontal ? b.width : b.height);\n\t\titems.sort((a, b) => pos(a.b) - pos(b.b));\n\t\tconst first = items[0].b;\n\t\tconst last = items[items.length - 1].b;\n\t\tconst total = pos(last) + size(last) - pos(first);\n\t\tconst gap = (total - items.reduce((s, i) => s + size(i.b), 0)) / (items.length - 1);\n\t\tthis.change(horizontal ? 'Distribute Horizontally' : 'Distribute Vertically', () => {\n\t\t\tlet cursor = pos(first);\n\t\t\tfor (const item of items) {\n\t\t\t\tconst d = cursor - pos(item.b);\n\t\t\t\tif (Math.abs(d) > 1e-9) this.doc = this.transformed(this.doc, new Set([item.id]), horizontal ? translateMatrix(d, 0) : translateMatrix(0, d));\n\t\t\t\tcursor += size(item.b) + gap;\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Structure\n\t// -------------------------------------------------------------------------\n\n\t/** Copies the selection (offset by `offset`, default 10, 10) on top of each original. */\n\tduplicate(options: { ids?: readonly string[]; offset?: Vec2 } = {}): string[] {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst offset = options.offset ?? { x: 10, y: 10 };\n\t\tconst created: string[] = [];\n\t\tif (!ids.length) return created;\n\t\tthis.change('Duplicate', () => {\n\t\t\tthis.doc = this.withDuplicates(this.doc, ids, offset, created);\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn created;\n\t}\n\n\tprivate withDuplicates(doc: VectorDocument, ids: readonly string[], offset: Vec2, created: string[]): VectorDocument {\n\t\tconst set = new Set(ids);\n\t\tconst m = translateMatrix(offset.x, offset.y);\n\t\tconst insert = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\tconst out: VectorNode[] = [];\n\t\t\tfor (const node of list) {\n\t\t\t\tconst n = node.type === 'group' ? { ...node, children: insert(node.children) } : node;\n\t\t\t\tout.push(n);\n\t\t\t\tif (set.has(node.id)) {\n\t\t\t\t\tconst copy = transformVectorNode(this.freshIds(node), m);\n\t\t\t\t\tcreated.push(copy.id);\n\t\t\t\t\tout.push(copy);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out;\n\t\t};\n\t\treturn { ...doc, nodes: insert(doc.nodes) };\n\t}\n\n\t/** Groups the selected nodes (they must share a parent). Returns the group id. */\n\tgroup(options: { ids?: readonly string[]; name?: string } = {}): string | null {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return null;\n\t\tconst locs = ids.map((id) => locateVectorNode(this.doc.nodes, id));\n\t\tif (locs.some((l) => !l)) return null;\n\t\tconst parent = locs[0]!.parent?.id ?? null;\n\t\tif (locs.some((l) => (l!.parent?.id ?? null) !== parent)) return null;\n\t\tconst id = this.newId();\n\t\tthis.change('Group', () => {\n\t\t\tconst set = new Set(ids);\n\t\t\tconst regroup = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst members = list.filter((n) => set.has(n.id));\n\t\t\t\tconst top = Math.max(...members.map((m) => list.indexOf(m)));\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlist.forEach((n, i) => {\n\t\t\t\t\tif (i === top) out.push({ id, type: 'group', name: options.name ?? 'Group', children: members });\n\t\t\t\t\tif (!set.has(n.id)) out.push(n);\n\t\t\t\t});\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tif (parent === null) this.setDoc(regroup(this.doc.nodes));\n\t\t\telse this.setDoc(mapTree(this.doc.nodes, (n) => (n.id === parent && n.type === 'group' ? { ...n, children: regroup(n.children) } : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Replaces selected groups with their children. */\n\tungroup(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst groups = (options.ids ?? this.selection).map((id) => this.getNode(id)).filter((n): n is VectorGroupNode => n?.type === 'group');\n\t\tif (!groups.length) return { ok: false, message: 'Select a group to ungroup.' };\n\t\tconst set = new Set(groups.map((g) => g.id));\n\t\tthis.change('Ungroup', () => {\n\t\t\tconst flatten = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlet changed = false;\n\t\t\t\tfor (const n of list) {\n\t\t\t\t\tif (set.has(n.id) && n.type === 'group') {\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\tconst opacity = n.opacity;\n\t\t\t\t\t\tconst m = nodeMatrix(n);\n\t\t\t\t\t\tout.push(\n\t\t\t\t\t\t\t...n.children\n\t\t\t\t\t\t\t\t.map((c) => (c.blendStep ? (({ blendStep: _s, locked: _l, ...rest }) => rest as VectorNode)(c) : c))\n\t\t\t\t\t\t\t\t.map((c) => (c.booleanOperation ? (({ booleanOperation: _b, ...rest }) => rest as VectorNode)(c) : c))\n\t\t\t\t\t\t\t\t.map((c) => (n.transform ? transformVectorNode(c, m) : c))\n\t\t\t\t\t\t\t\t.map((c) => (opacity !== undefined && opacity < 1 ? { ...c, opacity: (c.opacity ?? 1) * opacity } : c))\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (n.type === 'group') {\n\t\t\t\t\t\tconst children = flatten(n.children);\n\t\t\t\t\t\tif (children !== n.children) changed = true;\n\t\t\t\t\t\tout.push(children !== n.children ? { ...n, children } : n);\n\t\t\t\t\t} else out.push(n);\n\t\t\t\t}\n\t\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t\t};\n\t\t\tthis.setDoc(flatten(this.doc.nodes));\n\t\t\tthis.selection = groups.flatMap((g) => g.children.map((c) => c.id));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Changes stacking order within each node's parent. */\n\tarrange(op: VectorArrange, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst set = new Set(options.ids ?? this.selectedRoots());\n\t\tif (!set.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst reorder = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\tconst out = list.map((n) => (n.type === 'group' ? { ...n, children: reorder(n.children) } : n));\n\t\t\tif (op === 'front') return [...out.filter((n) => !set.has(n.id)), ...out.filter((n) => set.has(n.id))];\n\t\t\tif (op === 'back') return [...out.filter((n) => set.has(n.id)), ...out.filter((n) => !set.has(n.id))];\n\t\t\tif (op === 'forward') {\n\t\t\t\tfor (let i = out.length - 2; i >= 0; i--) if (set.has(out[i].id) && !set.has(out[i + 1].id)) [out[i], out[i + 1]] = [out[i + 1], out[i]];\n\t\t\t} else {\n\t\t\t\tfor (let i = 1; i < out.length; i++) if (set.has(out[i].id) && !set.has(out[i - 1].id)) [out[i], out[i - 1]] = [out[i - 1], out[i]];\n\t\t\t}\n\t\t\treturn out;\n\t\t};\n\t\tconst labels = { front: 'Bring to Front', forward: 'Bring Forward', backward: 'Send Backward', back: 'Send to Back' };\n\t\tthis.change(labels[op], () => this.setDoc(reorder(this.doc.nodes)));\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Combines the selected paths (two or more) into one with a boolean operation. `subtract`\n\t * removes the upper shapes from the lowest one. The result takes the lowest shape's style\n\t * and place. Shapes take part as drawn (path effects and live booleans applied).\n\t *\n\t * With `live`, the operands stay editable instead: a lone live boolean group gets the\n\t * operation (its operands follow it again), operands of live boolean groups get it as their\n\t * own, and anything else (two or more nodes with one parent) is wrapped in a new live boolean\n\t * group. Returns the result's (or the live group's) id, or null.\n\t */\n\tbooleanOp(op: VectorBooleanOperation, options: { ids?: readonly string[]; live?: boolean } = {}): string | null {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tif (options.live) return this.liveBooleanOp(op, roots);\n\t\tconst entries = vectorPathEntries(this.doc, roots, { locked: true });\n\t\tif (entries.length < 2) return null;\n\t\tconst result = pathBoolean(\n\t\t\tBOOLEAN_OPS[op],\n\t\t\tentries.map((e) => ({\n\t\t\t\tpath: vectorPathWorldBezier({ ...e.node, subpaths: e.node.subpaths.filter((s) => s.anchors.length > 1).map((s) => ({ ...s, closed: true })) }, e.parent),\n\t\t\t\tfillRule: e.node.fillRule ?? 'nonzero'\n\t\t\t}))\n\t\t);\n\t\tconst base = entries[0].node;\n\t\tconst anchorRoot = roots.find((r) => this.holds(r, base.id)) ?? base.id;\n\t\tconst subpaths = bezierToSubpaths(this.intoParentSpace(anchorRoot, result.path));\n\t\tif (result.error || !subpaths.length) return null;\n\t\tconst id = this.newId();\n\t\tconst { transform: _t, effects: _e, booleanOperation: _b, ...baseRest } = cloneVectorNode(base);\n\t\tconst node: VectorPathNode = { ...baseRest, id, name: BOOLEAN_LABELS[op], subpaths };\n\t\tconst drop = new Set([...entries.map((e) => e.node.id), ...roots]);\n\t\tthis.change(BOOLEAN_LABELS[op], () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === anchorRoot ? node : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Whether stored node `rootId` holds `id` as drawn (`id` may be an expanded path inside it). */\n\tprivate holds(rootId: string, id: string): boolean {\n\t\tconst n = this.getNode(rootId);\n\t\treturn !!n && (!!findVectorNode([n], id) || !!findVectorNode([expandVectorAppearance(n)], id));\n\t}\n\n\tprivate liveBooleanOp(op: VectorBooleanOperation, roots: readonly string[]): string | null {\n\t\tconst nodes = roots.map((id) => this.getNode(id));\n\t\tif (!nodes.length || nodes.some((n) => !n)) return null;\n\t\tconst label = `Live ${BOOLEAN_LABELS[op]}`;\n\t\tconst lone = nodes.length === 1 ? nodes[0] : null;\n\t\tif (isVectorLiveBoolean(lone)) {\n\t\t\tconst children = lone.children.map((c) => (c.booleanOperation ? (({ booleanOperation: _b, ...rest }) => rest as VectorNode)(c) : c));\n\t\t\tthis.change(label, () => this.replaceNode(lone.id, { ...lone, liveBoolean: op, children }));\n\t\t\treturn lone.id;\n\t\t}\n\t\tconst parents = roots.map((id) => locateVectorNode(this.doc.nodes, id)?.parent ?? null);\n\t\tif (parents.every((g) => isVectorLiveBoolean(g))) {\n\t\t\tconst set = new Set(roots);\n\t\t\tthis.change(label, () =>\n\t\t\t\tthis.setDoc(\n\t\t\t\t\tmapTree(this.doc.nodes, (n) => {\n\t\t\t\t\t\tif (n.type !== 'group' || !n.liveBoolean || !n.children.some((c) => set.has(c.id))) return n;\n\t\t\t\t\t\tconst group = n;\n\t\t\t\t\t\tconst children = group.children.map((c) => {\n\t\t\t\t\t\t\tif (!set.has(c.id)) return c;\n\t\t\t\t\t\t\tconst { booleanOperation: _b, ...rest } = c;\n\t\t\t\t\t\t\treturn (op === group.liveBoolean ? rest : { ...rest, booleanOperation: op }) as VectorNode;\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn { ...group, children };\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t);\n\t\t\treturn parents[0]!.id;\n\t\t}\n\t\tif (nodes.length < 2) return null;\n\t\tconst parent = parents[0]?.id ?? null;\n\t\tif (parents.some((g) => (g?.id ?? null) !== parent)) return null;\n\t\tconst id = this.newId();\n\t\tthis.change(label, () => {\n\t\t\tconst set = new Set(roots);\n\t\t\tconst wrap = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst members = list.filter((n) => set.has(n.id)).map((c) => (c.booleanOperation ? (({ booleanOperation: _b, ...rest }) => rest as VectorNode)(c) : c));\n\t\t\t\tconst top = Math.max(...list.map((n, i) => (set.has(n.id) ? i : -1)));\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlist.forEach((n, i) => {\n\t\t\t\t\tif (i === top) out.push({ id, type: 'group', name: BOOLEAN_LABELS[op], liveBoolean: op, children: members });\n\t\t\t\t\tif (!set.has(n.id)) out.push(n);\n\t\t\t\t});\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tif (parent === null) this.setDoc(wrap(this.doc.nodes));\n\t\t\telse this.setDoc(mapTree(this.doc.nodes, (n) => (n.id === parent && n.type === 'group' ? { ...n, children: wrap(n.children) } : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Joins the selected paths into one compound path (subpaths kept, lowest style). */\n\tcombine(options: { ids?: readonly string[] } = {}): string | null {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst entries = vectorPathEntries(this.doc, roots, { locked: true });\n\t\tif (entries.length < 2) return null;\n\t\tconst paths = entries.map((e) => e.node);\n\t\tconst id = this.newId();\n\t\tconst first = roots.find((r) => this.holds(r, paths[0].id)) ?? paths[0].id;\n\t\tconst subpaths = entries.flatMap((e) => bezierToSubpaths(this.intoParentSpace(first, vectorPathWorldBezier(e.node, e.parent))));\n\t\tconst { transform: _t, effects: _e, booleanOperation: _b, ...baseRest } = cloneVectorNode(paths[0]);\n\t\tconst node: VectorPathNode = { ...baseRest, id, name: 'Compound Path', subpaths };\n\t\tconst drop = new Set([...paths.map((p) => p.id), ...roots]);\n\t\tthis.change('Combine', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === first ? node : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** A document-space path mapped into the parent space of node `id`. */\n\tprivate intoParentSpace(id: string, path: BezierPath): BezierPath {\n\t\tconst parent = vectorParentMatrix(this.doc.nodes, id) ?? IDENTITY_MATRIX;\n\t\treturn isRoot(parent) ? path : transformBezierPath(path, invertMatrix(parent));\n\t}\n\n\t/** Splits selected compound paths into one path per subpath. */\n\tbreakApart(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst paths = (options.ids ?? this.selection).map((id) => this.getNode(id)).filter((n): n is VectorPathNode => n?.type === 'path' && n.subpaths.length > 1);\n\t\tif (!paths.length) return { ok: false, message: 'Select a compound path to break apart.' };\n\t\tconst created: string[] = [];\n\t\tconst set = new Set(paths.map((p) => p.id));\n\t\tthis.change('Break Apart', () => {\n\t\t\tconst split = (list: readonly VectorNode[]): VectorNode[] =>\n\t\t\t\tlist.flatMap((n): VectorNode[] => {\n\t\t\t\t\tif (n.type === 'group') return [{ ...n, children: split(n.children) }];\n\t\t\t\t\tif (!set.has(n.id)) return [n];\n\t\t\t\t\treturn n.subpaths.map((sp, i) => {\n\t\t\t\t\t\tconst id = i === 0 ? n.id : this.newId();\n\t\t\t\t\t\tcreated.push(id);\n\t\t\t\t\t\treturn { ...n, id, subpaths: [sp] };\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\tthis.setDoc(split(this.doc.nodes));\n\t\t\tthis.selection = created;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Pathfinder, Shape Builder and paint bucket\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Pathfinder: Divide, Trim, Merge, Crop, Outline or Minus Back over the selected (or given)\n\t * paths, in document space (rotated nodes and groups included, live corners cut). Unfilled\n\t * stroked paths take part as the area their stroke paints (Divide: open ones cut instead).\n\t * The results replace the operands at the place of the top-most one, grouped when there are\n\t * several; each keeps the style of the operand whose area it is. Returns the new path ids,\n\t * or an empty list when nothing came out.\n\t */\n\tpathfinder(op: VectorPathfinderOperation, options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst entries = vectorPathEntries(this.doc, roots);\n\t\tif (entries.length < (op === 'divide' || op === 'outline' ? 1 : 2)) return [];\n\t\tconst shapes = entries.map((e) => vectorPathfinderShape(e, op));\n\t\tconst result = runPathfinder(op, shapes);\n\t\tif (result.error || !result.pieces.length) return [];\n\t\tconst last = entries[entries.length - 1].node.id;\n\t\tconst topRoot = [...roots].reverse().find((r) => this.holds(r, last)) ?? last;\n\t\tconst nodes: VectorPathNode[] = [];\n\t\tfor (const piece of result.pieces) {\n\t\t\tconst subpaths = bezierToSubpaths(this.intoParentSpace(topRoot, piece.path)).map((sp) => (piece.open ? { ...sp, closed: false } : sp));\n\t\t\tif (!subpaths.length) continue;\n\t\t\tconst source = entries[piece.source].node;\n\t\t\tconst style = vectorResultStyle(source, shapes[piece.source].paint, op === 'outline');\n\t\t\tnodes.push({ ...style, type: 'path', id: this.newId(), name: source.name ?? 'Path', subpaths });\n\t\t}\n\t\tif (!nodes.length) return [];\n\t\tconst label = VECTOR_PATHFINDER_LABELS[op];\n\t\tconst container: VectorNode = nodes.length > 1 ? { id: this.newId(), type: 'group', name: label, children: nodes } : nodes[0];\n\t\tconst drop = new Set([...entries.map((e) => e.node.id), ...roots]);\n\t\tthis.change(label, () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === topRoot ? container : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [container.id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn nodes.map((n) => n.id);\n\t}\n\n\t/** The Shape Builder map of the selected (or given) paths, cached per document and selection. */\n\t// -------------------------------------------------------------------------\n\t// Blends\n\t// -------------------------------------------------------------------------\n\n\t/** Selected (or given) blend groups; a selected key or step counts as its blend. */\n\tprivate blendTargets(ids?: readonly string[]): (VectorGroupNode & { blend: VectorBlend })[] {\n\t\tconst out = new Map<string, VectorGroupNode & { blend: VectorBlend }>();\n\t\tfor (const id of ids ?? this.selection) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tconst group = isVectorBlendGroup(node) ? node : locateVectorNode(this.doc.nodes, id)?.parent;\n\t\t\tif (isVectorBlendGroup(group)) out.set(group.id, group);\n\t\t}\n\t\treturn [...out.values()];\n\t}\n\n\t/**\n\t * Blends two or more selected (or given) paths or groups: they become the keys of a live\n\t * blend group (bottom to top, or in the order given with `keepOrder`) whose in-betweens are\n\t * regenerated whenever a key or the options change. The keys must share a parent. Returns\n\t * the blend group's id, or null.\n\t */\n\tblend(input: VectorBlendInput = {}): string | null {\n\t\tconst ids = [...new Set(input.ids ?? this.selectedRoots())].filter((id) => {\n\t\t\tconst n = this.getNode(id);\n\t\t\treturn !!n && !n.blendStep && !n.locked;\n\t\t});\n\t\tif (ids.length < 2) return null;\n\t\tconst locs = ids.map((id) => locateVectorNode(this.doc.nodes, id)!);\n\t\tconst parent = locs[0].parent?.id ?? null;\n\t\tif (locs.some((l) => (l.parent?.id ?? null) !== parent)) return null;\n\t\tconst order = input.keepOrder ? ids : ids.slice().sort((a, b) => locs[ids.indexOf(a)].index - locs[ids.indexOf(b)].index);\n\t\tconst blend: VectorBlend = blendOptionsOf({ ...this.blendDefaults, ...input });\n\t\tif (input.starts) {\n\t\t\tconst starts = Object.fromEntries(Object.entries(input.starts).filter(([k, v]) => order.includes(k) && Number.isInteger(v) && v >= 0));\n\t\t\tif (Object.keys(starts).length) blend.starts = starts;\n\t\t}\n\t\tconst id = this.newId();\n\t\tthis.change('Blend', () => {\n\t\t\tconst set = new Set(order);\n\t\t\tconst regroup = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst members = order.map((m) => list.find((n) => n.id === m)!);\n\t\t\t\tconst top = Math.max(...members.map((m) => list.indexOf(m)));\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlist.forEach((n, i) => {\n\t\t\t\t\tif (i === top) out.push({ id, type: 'group', name: input.name ?? 'Blend', blend, children: members });\n\t\t\t\t\tif (!set.has(n.id)) out.push(n);\n\t\t\t\t});\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tif (parent === null) this.setDoc(regroup(this.doc.nodes));\n\t\t\telse this.setDoc(mapTree(this.doc.nodes, (n) => (n.id === parent && n.type === 'group' ? { ...n, children: regroup(n.children) } : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Sets the options new blends get (spacing, steps, distance, orientation, morph). */\n\tsetBlendDefaults(patch: Partial<VectorBlendOptions>): void {\n\t\tthis.blendDefaults = { ...this.blendDefaults, ...blendOptionsOf(patch) };\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Adds a node as the last key of a blend (it must share the blend's parent); `start` is the\n\t * anchor of its first subpath the blend starts from. One undo step.\n\t */\n\taddBlendKey(blendId: string, nodeId: string, options: { start?: number | null } = {}): VectorActionResult {\n\t\tconst group = this.getNode(blendId);\n\t\tconst node = this.getNode(nodeId);\n\t\tif (!isVectorBlendGroup(group)) return { ok: false, message: `\"${blendId}\" is not a blend.` };\n\t\tif (!node || node.blendStep || node.locked || node.id === blendId) return { ok: false, message: `\"${nodeId}\" cannot be a key.` };\n\t\tconst parentOf = (id: string) => locateVectorNode(this.doc.nodes, id)?.parent?.id ?? null;\n\t\tif (parentOf(blendId) !== parentOf(nodeId)) return { ok: false, message: 'The new key must sit beside the blend (same parent).' };\n\t\tconst start = options.start;\n\t\tthis.change('Blend', () => {\n\t\t\tconst blend = start !== null && start !== undefined ? { ...group.blend, starts: { ...group.blend.starts, [nodeId]: start } } : group.blend;\n\t\t\t// The key leaves its place and joins the blend.\n\t\t\tconst m = invertMatrix(nodeMatrix(group));\n\t\t\tconst key = group.transform ? transformVectorNode(node, m) : node;\n\t\t\t// Two passes: the key must not be removed again from inside the blend.\n\t\t\tconst without = mapTree(this.doc.nodes, (n) => (n.id === nodeId ? null : n));\n\t\t\tthis.setDoc(spliceTree(without, blendId, [{ ...group, blend, children: [...group.children, key] }]));\n\t\t\tthis.selection = [blendId];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Changes the spacing, steps, distance, orientation or morph of the selected (or given) blends. */\n\tsetBlendOptions(patch: Partial<VectorBlendOptions>, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst groups = this.blendTargets(options.ids);\n\t\tif (!groups.length) return { ok: false, message: 'Select a blend.' };\n\t\tconst clean = blendOptionsOf(patch);\n\t\tif (!Object.keys(clean).length) return { ok: false, message: 'No valid blend options were given.' };\n\t\tconst set = new Set(groups.map((g) => g.id));\n\t\tthis.change('Blend Options', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (set.has(n.id) && n.type === 'group' && n.blend ? { ...n, blend: { ...n.blend, ...clean } } : n)));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Expand: turns the selected (or given) blends into plain groups of their keys and steps. Returns their ids. */\n\texpandBlend(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst groups = this.blendTargets(options.ids);\n\t\tif (!groups.length) return [];\n\t\tconst set = new Set(groups.map((g) => g.id));\n\t\tconst used = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n) => used.add(n.id));\n\t\tconst fresh = () => {\n\t\t\tlet id = this.createId();\n\t\t\twhile (used.has(id)) id = this.createId();\n\t\t\tused.add(id);\n\t\t\treturn id;\n\t\t};\n\t\tthis.change('Expand Blend', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (set.has(n.id) && n.type === 'group' ? expandVectorBlend(n, fresh) : n)));\n\t\t\tthis.selection = [...set];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn [...set];\n\t}\n\n\t/** Release: replaces the selected (or given) blends with their keys (and a replaced spine as a path). */\n\treleaseBlend(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst groups = this.blendTargets(options.ids);\n\t\tif (!groups.length) return [];\n\t\tconst released: string[] = [];\n\t\tthis.change('Release Blend', () => {\n\t\t\tfor (const g of groups) {\n\t\t\t\tconst nodes = releaseVectorBlend(g, () => this.newId());\n\t\t\t\treleased.push(...nodes.map((n) => n.id));\n\t\t\t\tthis.setDoc(spliceTree(this.doc.nodes, g.id, nodes));\n\t\t\t}\n\t\t\tthis.selection = released;\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn released;\n\t}\n\n\t/**\n\t * Replace Spine: the selected blend's steps follow the selected path instead of the straight\n\t * lines between its keys. The path's first subpath becomes the spine (the path is removed)\n\t * and the keys move onto it, spread evenly by arc length.\n\t */\n\treplaceBlendSpine(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst groups = this.blendTargets(roots);\n\t\tconst paths = roots.map((id) => this.getNode(id)).filter((n): n is VectorPathNode => n?.type === 'path' && !n.blendStep && !isVectorBlendGroup(locateVectorNode(this.doc.nodes, n.id)?.parent));\n\t\tif (groups.length !== 1 || paths.length !== 1) return { ok: false, message: 'Select one blend and one path to be its spine.' };\n\t\tconst group = groups[0];\n\t\tconst path = paths[0];\n\t\tconst first = path.subpaths.find((sp) => sp.anchors.length >= 2);\n\t\tif (!first) return { ok: false, message: 'The spine needs a path with at least two points.' };\n\t\t// The path's first subpath in the blend group's own space.\n\t\tconst m = multiplyMatrices(this.worldOf(path.id), invertMatrix(this.worldOf(group.id)));\n\t\tconst spine = transformVectorNode<VectorPathNode>({ id: '', type: 'path', subpaths: [first] }, m).subpaths[0];\n\t\tthis.change('Replace Spine', () => {\n\t\t\tconst withSpine: VectorGroupNode = { ...group, blend: { ...group.blend, spine } };\n\t\t\tconst targets = vectorBlendKeyTargets(withSpine);\n\t\t\tlet k = 0;\n\t\t\tconst children = withSpine.children.map((c) => {\n\t\t\t\tif (c.blendStep) return c;\n\t\t\t\tconst target = targets[k++];\n\t\t\t\tconst b = vectorNodeBounds(c);\n\t\t\t\tif (!target || !b) return c;\n\t\t\t\tconst dx = target[0] - (b.x + b.width / 2);\n\t\t\t\tconst dy = target[1] - (b.y + b.height / 2);\n\t\t\t\treturn Math.hypot(dx, dy) > 1e-9 ? transformVectorNode(c, translateMatrix(dx, dy)) : c;\n\t\t\t});\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === path.id ? null : n.id === group.id ? { ...withSpine, children } : n)));\n\t\t\tthis.selection = [group.id];\n\t\t\tthis.anchors = [];\n\t\t\tif (this.editingId === path.id) this.editingId = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\tprivate shapeBuilderMap(ids?: readonly string[]): VectorShapeBuilderMap | null {\n\t\tconst roots = ids ?? this.selectedRoots();\n\t\tconst key = roots.join('\\u0000');\n\t\tif (this.builderCache?.doc === this.doc && this.builderCache.key === key) return this.builderCache.map;\n\t\t// The Shape Builder edits the shapes it takes area from: their stored geometry.\n\t\tconst entries = roots.length ? vectorPathEntries(this.doc, roots, { expand: false }) : [];\n\t\tconst map = entries.length ? vectorShapeBuilderMap(entries) : null;\n\t\tthis.builderCache = { doc: this.doc, key, map };\n\t\treturn map;\n\t}\n\n\t/** The faces the Shape Builder offers for the selected (or given) paths (document units). */\n\tgetShapeBuilderFaces(options: { ids?: readonly string[] } = {}): VectorShapeBuilderFace[] {\n\t\tconst m = this.shapeBuilderMap(options.ids);\n\t\tif (!m) return [];\n\t\treturn m.map.faces.map((f, index) => {\n\t\t\tconst p = m.map.faceInterior(index);\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\td: bezierPathToSvg(f.path, { precision: 3 }),\n\t\t\t\tarea: f.area,\n\t\t\t\tsources: m.map.faceSources(index).map((i) => m.entries[i].node.id),\n\t\t\t\tpoint: p ? { x: p[0], y: p[1] } : null\n\t\t\t};\n\t\t});\n\t}\n\n\t/** Pick distance of the Shape Builder's erase for line pieces (document units). */\n\tprivate builderLineTolerance(): number {\n\t\treturn Math.max(this.hitRadius, 4) / this.viewport.zoom;\n\t}\n\n\t/**\n\t * Shape Builder gesture along `points` (document units; one point is a click) over the faces\n\t * the selected (or given) paths make. Merges the faces touched into one shape styled like the\n\t * top-most shape over the first face (the current fill for a face only outlines enclose);\n\t * with `erase` deletes them, the pieces of unfilled open paths and the edges of other outlines\n\t * (cut where paths meet) within `tolerance`: a deleted edge opens a closed subpath there,\n\t * splits an open one or takes a subpath it runs all the way round, and edges bounding a face\n\t * deleted in the same gesture go with the face. Every shape covering a touched face loses\n\t * that area; paths keep their own transforms. One undo step.\n\t */\n\tshapeBuilder(points: readonly Vec2[], options: { ids?: readonly string[]; erase?: boolean; tolerance?: number } = {}): VectorShapeBuilderResult {\n\t\tconst none = (message: string): VectorShapeBuilderResult => ({ ok: false, message, merged: null, faces: 0, lines: 0, edges: 0 });\n\t\tif (!points.length || !points.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y))) return none('Give the points of the gesture.');\n\t\tconst m = this.shapeBuilderMap(options.ids);\n\t\tif (!m) return none('Select paths that make faces.');\n\t\tconst erase = !!options.erase;\n\t\tconst tol = erase ? (options.tolerance ?? this.builderLineTolerance()) : null;\n\t\tconst touched: VectorBuilderTouched = { faces: [], lines: [], edges: [] };\n\t\tconst size = m.map.faces.reduce((s, f) => Math.max(s, f.bounds.maxX - f.bounds.minX, f.bounds.maxY - f.bounds.minY), 1);\n\t\tfor (const p of samplePolyline(points, Math.max(size / 2000, 0.25 / this.viewport.zoom))) addBuilderHit(touched, vectorShapeBuilderHit(m, p, tol));\n\t\tif (!touched.faces.length && !touched.lines.length && !touched.edges.length) return none('There is no face under the pointer.');\n\t\treturn this.applyShapeBuilder(m, touched, erase);\n\t}\n\n\tprivate applyShapeBuilder(m: VectorShapeBuilderMap, touched: VectorBuilderTouched, erase: boolean): VectorShapeBuilderResult {\n\t\tconst plan = planShapeBuilder(m, touched, erase);\n\t\tlet mergedId: string | null = null;\n\t\tconst created = new Map<string, string[]>();\n\t\tthis.change(erase ? 'Shape Builder Delete' : 'Shape Builder', () => {\n\t\t\tlet nodes = this.doc.nodes;\n\t\t\tm.entries.forEach((entry, i) => {\n\t\t\t\tconst node = entry.node;\n\t\t\t\tconst toLocal = (path: BezierPath) => transformBezierPath(path, invertMatrix(multiplyMatrices(nodeMatrix(node), entry.parent)));\n\t\t\t\tconst list: VectorNode[] = [];\n\t\t\t\tconst r = plan.replace.get(i);\n\t\t\t\tif (r === undefined) list.push(node);\n\t\t\t\telse if (r?.kind === 'fill') list.push({ ...node, fillRule: 'nonzero', subpaths: bezierToSubpaths(toLocal(r.path)) });\n\t\t\t\telse if (r?.kind === 'outline') list.push({ ...node, subpaths: bezierToSubpaths(toLocal(r.path)) });\n\t\t\t\telse if (r?.kind === 'pieces') {\n\t\t\t\t\tr.paths.forEach((path, k) =>\n\t\t\t\t\t\tlist.push({ ...node, id: k === 0 ? node.id : this.newId(), subpaths: bezierToSubpaths(toLocal(path)).map((sp) => ({ ...sp, closed: false })) })\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (plan.merged && plan.merged.style === i) {\n\t\t\t\t\tmergedId = this.newId();\n\t\t\t\t\tconst merged: VectorPathNode = {\n\t\t\t\t\t\t...vectorResultStyle(node, 'fill'),\n\t\t\t\t\t\ttype: 'path',\n\t\t\t\t\t\tid: mergedId,\n\t\t\t\t\t\tname: 'Shape',\n\t\t\t\t\t\t...(node.transform ? { transform: node.transform } : {}),\n\t\t\t\t\t\tsubpaths: bezierToSubpaths(toLocal(plan.merged.path))\n\t\t\t\t\t};\n\t\t\t\t\tif (plan.merged.currentFill || !hasPaint(merged.fill)) merged.fill = hasPaint(this.defaults.fill) ? this.defaults.fill! : '#808080';\n\t\t\t\t\tlist.push(merged);\n\t\t\t\t}\n\t\t\t\tif (r === undefined && list.length === 1) return;\n\t\t\t\tcreated.set(node.id, list.map((n) => n.id));\n\t\t\t\tnodes = spliceTree(nodes, node.id, list);\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t\t// The shapes stay selected so the next gesture works on them too.\n\t\t\tconst selection = this.selection.flatMap((id) => created.get(id) ?? [id]);\n\t\t\tif (mergedId && !selection.includes(mergedId)) selection.push(mergedId);\n\t\t\tthis.selection = selection.filter((id, k) => !!this.getNode(id) && selection.indexOf(id) === k);\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\tthis.builderCache = null;\n\t\treturn { ok: true, merged: mergedId, faces: touched.faces.length, lines: touched.lines.length, edges: erase ? vectorBuilderErasedEdges(m, touched).length : 0 };\n\t}\n\n\t/** The paint bucket's map of the visible outlines, cached per document and gap. */\n\tprivate fillMap(gap: number): PlanarMap | null {\n\t\tif (this.fillCache?.doc === this.doc && this.fillCache.gap === gap) return this.fillCache.map;\n\t\tconst map = vectorFillMap(this.doc, gap);\n\t\tthis.fillCache = { doc: this.doc, gap, map };\n\t\treturn map;\n\t}\n\n\t/**\n\t * Paint bucket: the region the visible outlines enclose around `point` (document units),\n\t * crossings split and islands left as holes, becomes a new path filled with the current fill\n\t * default, placed just below the selection (or on top when nothing is selected). `gap`\n\t * (default `editing.fillGap`) closes gaps up to that size between loose ends. Returns the new\n\t * path's id, or null when nothing encloses the point.\n\t */\n\tfillRegion(point: Vec2, options: { gap?: number } = {}): string | null {\n\t\tif (!Number.isFinite(point.x) || !Number.isFinite(point.y)) return null;\n\t\tconst region = this.fillMap(options.gap ?? this.editing.fillGap)?.regionAt([point.x, point.y]);\n\t\tif (!region?.length) return null;\n\t\t// Below the lowest selected node, in its parent.\n\t\tlet below: string | null = null;\n\t\tconst roots = new Set(this.selectedRoots());\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (!below && roots.has(n.id)) below = n.id;\n\t\t});\n\t\tconst subpaths = bezierToSubpaths(below ? this.intoParentSpace(below, region) : region);\n\t\tif (!subpaths.length) return null;\n\t\tconst id = this.newId();\n\t\tconst node: VectorPathNode = { id, type: 'path', name: 'Fill', ...this.styleFor(false), stroke: null, fillRule: 'nonzero', subpaths };\n\t\tif (!hasPaint(node.fill)) node.fill = '#808080';\n\t\tconst target = below as string | null;\n\t\tthis.change('Fill Region', () => {\n\t\t\tif (target) {\n\t\t\t\tconst current = this.getNode(target)!;\n\t\t\t\tthis.setDoc(spliceTree(this.doc.nodes, target, [node, current]));\n\t\t\t} else this.setDoc([...this.doc.nodes, node]);\n\t\t\tif (!target) this.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Updates the Shape Builder / paint bucket highlight for the pointer at `p`; true when it changed. */\n\tprivate hoverBuilder(p: Vec2, alt: boolean): boolean {\n\t\tif (this.tool === 'paintBucket') {\n\t\t\tconst region = this.fillMap(this.editing.fillGap)?.regionAt([p.x, p.y]) ?? null;\n\t\t\tconst key = region ? bezierPathToSvg(region, { precision: 2 }) : null;\n\t\t\tif (key === this.builderHoverKey) return false;\n\t\t\tthis.builderHoverKey = key;\n\t\t\tthis.builderPreview = region ? { mode: 'fill', faces: [region], lines: [], trail: null } : null;\n\t\t\treturn true;\n\t\t}\n\t\tconst m = this.selectedRoots().length ? this.shapeBuilderMap() : null;\n\t\tconst hit = m ? vectorShapeBuilderHit(m, p, alt ? this.builderLineTolerance() : null) : null;\n\t\tconst key = hit ? `${alt ? 'erase' : 'merge'}:${JSON.stringify(hit)}` : null;\n\t\tif (key === this.builderHoverKey) return false;\n\t\tthis.builderHoverKey = key;\n\t\tconst touched: VectorBuilderTouched = { faces: [], lines: [], edges: [] };\n\t\taddBuilderHit(touched, hit);\n\t\tthis.builderPreview = hit && m ? this.builderPreviewOf(m, touched, alt, null) : null;\n\t\treturn true;\n\t}\n\n\tprivate builderPreviewOf(m: VectorShapeBuilderMap, touched: VectorBuilderTouched, erase: boolean, trail: Vec2[] | null): VectorBuilderPreview {\n\t\tconst faces = m.map.faces;\n\t\treturn {\n\t\t\tmode: erase ? 'erase' : 'merge',\n\t\t\tfaces: touched.faces.map((f) => faces[f].path),\n\t\t\t// Edges bounding a face touched too go with the face, so they are not shown apart.\n\t\t\tlines: [...touched.lines.map((k) => m.pieces[k].path), ...(erase ? vectorBuilderErasedEdges(m, touched).map((k) => m.edges[k].path) : [])],\n\t\t\ttrail\n\t\t};\n\t}\n\n\tprivate downBuilder(p: Vec2, input: VectorPointerInput) {\n\t\tthis.builderHoverKey = null;\n\t\tif (this.tool === 'paintBucket') {\n\t\t\tthis.fillRegion(p);\n\t\t\tthis.builderPreview = null;\n\t\t\tthis.hoverBuilder(p, false);\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst m = this.selectedRoots().length ? this.shapeBuilderMap() : null;\n\t\tif (!m) return;\n\t\tconst erase = !!input.alt;\n\t\tconst touched: VectorBuilderTouched = { faces: [], lines: [], edges: [] };\n\t\taddBuilderHit(touched, vectorShapeBuilderHit(m, p, erase ? this.builderLineTolerance() : null));\n\t\tthis.drag = { kind: 'builder', erase, points: [p], touched, map: m };\n\t\tthis.interaction = { type: 'builder', mode: erase ? 'erase' : 'merge', points: [p] };\n\t\tthis.builderPreview = this.builderPreviewOf(m, touched, erase, [p]);\n\t\tthis.notify();\n\t}\n\n\tprivate moveBuilder(drag: Extract<Drag, { kind: 'builder' }>, p: Vec2) {\n\t\tconst last = drag.points[drag.points.length - 1];\n\t\tif (Math.hypot(p.x - last.x, p.y - last.y) * this.viewport.zoom < 1) return;\n\t\tconst tol = drag.erase ? this.builderLineTolerance() : null;\n\t\tfor (const q of samplePolyline([last, p], 2 / this.viewport.zoom)) addBuilderHit(drag.touched, vectorShapeBuilderHit(drag.map, q, tol));\n\t\tdrag.points.push(p);\n\t\tthis.interaction = { type: 'builder', mode: drag.erase ? 'erase' : 'merge', points: drag.points.slice() };\n\t\tthis.builderPreview = this.builderPreviewOf(drag.map, drag.touched, drag.erase, drag.points.slice());\n\t\tthis.notify();\n\t}\n\n\tprivate upBuilder(drag: Extract<Drag, { kind: 'builder' }>) {\n\t\tthis.builderPreview = null;\n\t\tthis.builderHoverKey = null;\n\t\tif (!drag.touched.faces.length && !drag.touched.lines.length && !drag.touched.edges.length) {\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.applyShapeBuilder(drag.map, drag.touched, drag.erase);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Anchor editing\n\t// -------------------------------------------------------------------------\n\n\tprivate updateAnchors(doc: VectorDocument, refs: readonly VectorAnchorRef[], fn: (a: VectorAnchor, ref: VectorAnchorRef) => VectorAnchor): VectorDocument {\n\t\tconst byNode = new Map<string, VectorAnchorRef[]>();\n\t\tfor (const r of refs) byNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r]);\n\t\tconst nodes = mapTree(doc.nodes, (n) => {\n\t\t\tconst list = byNode.get(n.id);\n\t\t\tif (!list || n.type !== 'path' || n.locked) return n;\n\t\t\tconst subpaths = n.subpaths.map((sp, s) => {\n\t\t\t\tconst hits = list.filter((r) => r.subpath === s);\n\t\t\t\tif (!hits.length) return sp;\n\t\t\t\treturn { closed: sp.closed, anchors: sp.anchors.map((a, i) => (hits.some((r) => r.index === i) ? fn(a, { nodeId: n.id, subpath: s, index: i }) : a)) };\n\t\t\t});\n\t\t\treturn { ...n, subpaths };\n\t\t});\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\t/** Moves anchors by a document-space offset (converted into each node's own space). */\n\tprivate movedAnchors(doc: VectorDocument, refs: readonly VectorAnchorRef[], dx: number, dy: number): VectorDocument {\n\t\tconst local = new Map<string, Vec2>();\n\t\tfor (const r of refs) if (!local.has(r.nodeId)) local.set(r.nodeId, applyMatrixLinear(invertMatrix(this.worldOf(r.nodeId, doc)), { x: dx, y: dy }));\n\t\treturn this.updateAnchors(doc, refs, (a, ref) => {\n\t\t\tconst d = local.get(ref.nodeId)!;\n\t\t\treturn translateAnchor(a, d.x, d.y);\n\t\t});\n\t}\n\n\t/**\n\t * Moves one anchor to a document position. Its handles follow; with `curvature` (default:\n\t * the `curvatureMoves` setting) its two segments bend instead, as the Curvature tool does.\n\t */\n\tmoveAnchor(ref: VectorAnchorRef, to: Vec2, options: { curvature?: boolean } = {}): VectorActionResult {\n\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\tif (!a) return { ok: false, message: 'There is no such anchor.' };\n\t\tconst curvature = options.curvature ?? this.editing.curvatureMoves;\n\t\tthis.change('Move Point', () => {\n\t\t\tthis.doc = curvature ? this.curvatureMoved(this.doc, ref, to) : this.movedAnchors(this.doc, [ref], to.x - a.x, to.y - a.y);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** `doc` with anchor `ref` moved to document point `to` by a Curvature-tool move. */\n\tprivate curvatureMoved(doc: VectorDocument, ref: VectorAnchorRef, to: Vec2): VectorDocument {\n\t\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\t\tif (node?.type !== 'path' || node.locked || !node.subpaths[ref.subpath]) return doc;\n\t\tconst q = this.toLocal(ref.nodeId, to, doc);\n\t\tconst subpaths = node.subpaths.map((sp, i) => (i === ref.subpath ? curvatureMoveAnchor(sp, ref.index, q) : sp));\n\t\tconst nodes = mapTree(doc.nodes, (n) => (n.id === ref.nodeId ? { ...node, subpaths } : n));\n\t\treturn { ...doc, nodes };\n\t}\n\n\t/** `doc` with segment `ref` bent through document point `p` at parameter `t`. */\n\tprivate bent(doc: VectorDocument, ref: VectorSegmentRef, t: number, p: Vec2): VectorDocument {\n\t\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\t\tif (node?.type !== 'path' || node.locked || !node.subpaths[ref.subpath]) return doc;\n\t\tconst q = this.toLocal(ref.nodeId, p, doc);\n\t\tconst subpaths = node.subpaths.map((sp, i) => (i === ref.subpath ? bendSubpathSegment(sp, ref.segment, t, q) : sp));\n\t\treturn { ...doc, nodes: mapTree(doc.nodes, (n) => (n.id === ref.nodeId ? { ...node, subpaths } : n)) };\n\t}\n\n\t/**\n\t * Bends a segment so the curve passes through document point `to` at parameter `t`\n\t * (default 0.5, clamped to 0.05–0.95); see `bendSegment` in `pathEdit`.\n\t */\n\tbendSegment(ref: VectorSegmentRef, to: Vec2, t = 0.5): VectorActionResult {\n\t\tconst node = this.getNode(ref.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[ref.subpath] : undefined;\n\t\tif (!sp || ref.segment < 0 || ref.segment >= (sp.closed ? sp.anchors.length : sp.anchors.length - 1) || sp.anchors.length < 2) return { ok: false, message: 'There is no such segment.' };\n\t\tif (node!.locked) return { ok: false, message: 'The path is locked.' };\n\t\tthis.change('Bend Segment', () => {\n\t\t\tthis.doc = this.bent(this.doc, ref, t, to);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Moves one handle to a document position (see `moveAnchorHandle` for how the opposite handle follows). */\n\tmoveHandle(ref: VectorHandleRef, to: Vec2, options: { breakHandles?: boolean } = {}): VectorActionResult {\n\t\tif (!getAnchor(this.doc, ref)) return { ok: false, message: 'There is no such anchor.' };\n\t\tconst local = this.toLocal(ref.nodeId, to);\n\t\tthis.change('Move Handle', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, [ref], (a) => moveAnchorHandle(a, ref.handle, local, options.breakHandles));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Converts the selected (or given) anchors between corner, smooth and symmetric. */\n\tconvertAnchors(type: VectorAnchorType, refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tif (!refs.length) return { ok: false, message: 'Select points to convert.' };\n\t\tthis.change(type === 'corner' ? 'Make Corner' : 'Make Smooth', () => {\n\t\t\tconst nodes = mapTree(this.doc.nodes, (n) => {\n\t\t\t\tif (n.type !== 'path') return n;\n\t\t\t\tconst mine = refs.filter((r) => r.nodeId === n.id);\n\t\t\t\tif (!mine.length) return n;\n\t\t\t\tconst subpaths = n.subpaths.map((sp, s) => mine.filter((r) => r.subpath === s).reduce((acc, r) => convertAnchor(acc, r.index, type), sp));\n\t\t\t\treturn { ...n, subpaths };\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Adds an anchor on the nearest segment of `nodeId` to document point `point` (shape unchanged). */\n\tinsertAnchorAt(nodeId: string, point: Vec2): VectorAnchorRef | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path') return null;\n\t\tconst hit = nearestSegment(node, this.toLocal(nodeId, point));\n\t\tif (!hit) return null;\n\t\tconst { subpath, index } = insertAnchor(node.subpaths[hit.subpath], hit.segment, hit.t);\n\t\tconst ref = { nodeId, subpath: hit.subpath, index };\n\t\tthis.change('Add Point', () => {\n\t\t\tthis.replaceNode(nodeId, { ...node, subpaths: node.subpaths.map((sp, i) => (i === hit.subpath ? subpath : sp)) });\n\t\t\tthis.editingId = nodeId;\n\t\t\tthis.anchors = [ref];\n\t\t});\n\t\treturn ref;\n\t}\n\n\t/**\n\t * Deletes the selected (or given) anchors; subpaths left with one anchor and empty paths go\n\t * too. With `keepShape` (default: the `keepShapeOnDelete` setting, on) the neighbours'\n\t * handles are refitted so the path keeps its shape; off, the neighbours are joined as they are.\n\t */\n\tdeleteAnchors(refs: readonly VectorAnchorRef[] = this.anchors, options: { keepShape?: boolean } = {}): VectorActionResult {\n\t\tif (!refs.length) return { ok: false, message: 'Select points to delete.' };\n\t\tconst keepShape = options.keepShape ?? this.editing.keepShapeOnDelete;\n\t\tthis.change('Delete Points', () => {\n\t\t\tconst nodes = mapTree(this.doc.nodes, (n) => {\n\t\t\t\tif (n.type !== 'path' || n.locked) return n;\n\t\t\t\tconst mine = refs.filter((r) => r.nodeId === n.id);\n\t\t\t\tif (!mine.length) return n;\n\t\t\t\tconst subpaths = n.subpaths\n\t\t\t\t\t.map((sp, s) => {\n\t\t\t\t\t\tconst indices = mine.filter((r) => r.subpath === s).map((r) => r.index);\n\t\t\t\t\t\tif (!indices.length) return sp;\n\t\t\t\t\t\treturn keepShape ? removeAnchorsKeepingShape(sp, indices) : removeAnchors(sp, indices);\n\t\t\t\t\t})\n\t\t\t\t\t.filter((sp) => sp.anchors.length > 1);\n\t\t\t\treturn subpaths.length ? { ...n, subpaths } : null;\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.anchors = [];\n\t\t\tthis.selection = this.selection.filter((id) => this.getNode(id));\n\t\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Opens or closes the subpaths that contain selected anchors (or all subpaths of `nodeId`). */\n\tsetClosed(closed: boolean, nodeId?: string): VectorActionResult {\n\t\tconst targets = nodeId\n\t\t\t? (() => {\n\t\t\t\t\tconst n = this.getNode(nodeId);\n\t\t\t\t\treturn n?.type === 'path' ? n.subpaths.map((_, s) => ({ nodeId, subpath: s })) : [];\n\t\t\t\t})()\n\t\t\t: this.anchors.map((r) => ({ nodeId: r.nodeId, subpath: r.subpath }));\n\t\tif (!targets.length) return { ok: false, message: 'Select a path or points.' };\n\t\tthis.change(closed ? 'Close Path' : 'Open Path', () => {\n\t\t\tthis.setDoc(\n\t\t\t\tmapTree(this.doc.nodes, (n) =>\n\t\t\t\t\tn.type === 'path' && targets.some((t) => t.nodeId === n.id)\n\t\t\t\t\t\t? { ...n, subpaths: n.subpaths.map((sp, s) => (targets.some((t) => t.nodeId === n.id && t.subpath === s) ? { ...sp, closed } : sp)) }\n\t\t\t\t\t\t: n\n\t\t\t\t)\n\t\t\t);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Reverses the direction of every subpath of the selected paths. */\n\treversePaths(ids: readonly string[] = this.selection): VectorActionResult {\n\t\tconst set = new Set(ids.flatMap((id) => (this.getNode(id) ? collectPathNodes(this.getNode(id)!) : [])).map((p) => p.id));\n\t\tif (!set.size) return { ok: false, message: 'Select a path.' };\n\t\tthis.change('Reverse Path', () => {\n\t\t\tthis.setDoc(\n\t\t\t\tmapTree(this.doc.nodes, (n) =>\n\t\t\t\t\tn.type === 'path' && set.has(n.id)\n\t\t\t\t\t\t? { ...n, subpaths: n.subpaths.map(reverseSubpath), ...(n.strokeWidthProfile?.length ? { strokeWidthProfile: reverseWidthProfile(n.strokeWidthProfile) } : {}) }\n\t\t\t\t\t\t: n\n\t\t\t\t)\n\t\t\t);\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Path clean-up, Scissors, Knife and Eraser\n\t// -------------------------------------------------------------------------\n\n\t/** Unlocked path nodes in the given roots (default: the paths being edited, else the selection). */\n\tprivate pathTargets(ids?: readonly string[]): VectorPathNode[] {\n\t\tconst roots = ids ?? (this.tool === 'direct' && this.anchors.length ? [...new Set(this.anchors.map((r) => r.nodeId))] : this.selection);\n\t\tconst out = new Map<string, VectorPathNode>();\n\t\tfor (const id of roots) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) out.set(p.id, p);\n\t\t}\n\t\t// Document order, bottom to top.\n\t\tconst order: string[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (out.has(n.id)) order.push(n.id);\n\t\t});\n\t\treturn order.map((id) => out.get(id)!);\n\t}\n\n\t/** Subpaths of node `from` mapped into node `to`'s own space. */\n\tprivate subpathsIn(from: VectorPathNode, to: string): VectorSubpath[] {\n\t\tconst m = multiplyMatrices(this.worldOf(from.id), invertMatrix(this.worldOf(to)));\n\t\tif (isRoot(m)) return from.subpaths;\n\t\tconst map = (p: Vec2) => applyMatrix(m, p);\n\t\treturn from.subpaths.map((sp) => ({\n\t\t\tclosed: sp.closed,\n\t\t\tanchors: sp.anchors.map((a) => ({ ...map(a), ...(a.in ? { in: map(a.in) } : {}), ...(a.out ? { out: map(a.out) } : {}), ...(a.type ? { type: a.type } : {}), ...(a.corner ? { corner: { ...a.corner } } : {}) }))\n\t\t}));\n\t}\n\n\t/**\n\t * Replaces a path with pieces: each entry becomes one path (the first keeps the node's id and\n\t * place, the others go just above it with the same style). No pieces removes the path.\n\t * Returns the ids of the paths now standing in for it.\n\t */\n\tprivate replaceWithPieces(node: VectorPathNode, pieces: readonly VectorSubpath[][]): string[] {\n\t\tconst nodes = pieces.filter((p) => p.length).map((subpaths, i) => ({ ...node, id: i === 0 ? node.id : this.newId(), subpaths }) as VectorPathNode);\n\t\tthis.setDoc(spliceTree(this.doc.nodes, node.id, nodes));\n\t\treturn nodes.map((n) => n.id);\n\t}\n\n\t/** Clears anchor selections, editing and pen state that no longer point at anything. */\n\tprivate dropStaleRefs() {\n\t\tthis.selection = this.selection.filter((id) => this.getNode(id));\n\t\tthis.anchors = this.anchors.filter((r) => getAnchor(this.doc, r));\n\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t}\n\n\t/**\n\t * Join: the open subpaths of the selected (or given) paths become one open path, joined\n\t * nearest endpoints first (ends within `tolerance` document units merge into one anchor,\n\t * others get a straight segment); a single open subpath is closed. The result replaces the\n\t * lowest path, in its space and style. Default tolerance: the pick distance.\n\t */\n\tjoinPaths(options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst paths = this.pathTargets(options.ids);\n\t\tif (!paths.length) return { ok: false, message: 'Select paths to join.' };\n\t\tconst base = paths[0];\n\t\tconst all = paths.flatMap((p) => this.subpathsIn(p, base.id));\n\t\tif (!all.some((sp) => !sp.closed && sp.anchors.length > 1)) return { ok: false, message: 'There are no open paths to join.' };\n\t\tconst subpaths = joinSubpaths(all, options.tolerance ?? this.tolerance());\n\t\tconst drop = new Set(paths.slice(1).map((p) => p.id));\n\t\tthis.change('Join', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === base.id ? { ...base, subpaths } : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [base.id];\n\t\t\tthis.anchors = [];\n\t\t\tif (this.editingId && drop.has(this.editingId)) this.editingId = base.id;\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Average: moves the selected (or given) anchors onto their average position along `axis`, in document space. */\n\taverageAnchors(axis: VectorAverageAxis = 'both', refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tconst points = refs.map((r) => ({ ref: r, at: getAnchorWorld(this.doc, r) })).filter((p): p is { ref: VectorAnchorRef; at: NonNullable<ReturnType<typeof getAnchorWorld>> } => !!p.at);\n\t\tif (points.length < 2) return { ok: false, message: 'Select at least two points to average.' };\n\t\tconst cx = points.reduce((s, p) => s + p.at.x, 0) / points.length;\n\t\tconst cy = points.reduce((s, p) => s + p.at.y, 0) / points.length;\n\t\tthis.change('Average', () => {\n\t\t\tfor (const { ref, at } of points) {\n\t\t\t\tconst dx = axis === 'horizontal' ? 0 : cx - at.x;\n\t\t\t\tconst dy = axis === 'vertical' ? 0 : cy - at.y;\n\t\t\t\tif (dx || dy) this.doc = this.movedAnchors(this.doc, [ref], dx, dy);\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies `fn` to every subpath of the target paths as one undo step. */\n\tprivate editSubpaths(label: string, ids: readonly string[] | undefined, fn: (sp: VectorSubpath, node: VectorPathNode, index: number) => VectorSubpath): VectorActionResult {\n\t\tconst paths = this.pathTargets(ids);\n\t\tif (!paths.length) return { ok: false, message: 'Select a path.' };\n\t\tconst set = new Set(paths.map((p) => p.id));\n\t\tthis.change(label, () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.type === 'path' && set.has(n.id) ? { ...n, subpaths: n.subpaths.map((sp, i) => fn(sp, n, i)) } : n)));\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Remove Redundant Points: drops anchors of the selected (or given) paths that can go\n\t * without moving the outline more than `tolerance` document units (default 0.5).\n\t */\n\tremoveRedundantPoints(options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst tolerance = options.tolerance ?? 0.5;\n\t\treturn this.editSubpaths('Remove Redundant Points', options.ids, (sp) => removeRedundantSubpathPoints(sp, tolerance));\n\t}\n\n\t/**\n\t * Smooth: pulls handles towards smooth tangents by `amount` (0–1, default 1). With the direct\n\t * tool and points selected, only those points change.\n\t */\n\tsmoothPaths(options: { ids?: readonly string[]; amount?: number; refs?: readonly VectorAnchorRef[] } = {}): VectorActionResult {\n\t\tconst refs = options.refs ?? (!options.ids && this.tool === 'direct' && this.anchors.length ? this.anchors : null);\n\t\tconst ids = options.ids ?? (refs ? [...new Set(refs.map((r) => r.nodeId))] : undefined);\n\t\treturn this.editSubpaths('Smooth', ids, (sp, node, i) => {\n\t\t\tconst only = refs ? new Set(refs.filter((r) => r.nodeId === node.id && r.subpath === i).map((r) => r.index)) : undefined;\n\t\t\treturn only && !only.size ? sp : smoothSubpath(sp, options.amount ?? 1, only);\n\t\t});\n\t}\n\n\t/** Splits a cut subpath into pieces: separate paths for a one-subpath node, subpaths in place for a compound one. */\n\tprivate applyCuts(node: VectorPathNode, cut: (sp: VectorSubpath, index: number) => VectorSubpath[] | null): string[] | null {\n\t\tconst results = node.subpaths.map((sp, i) => cut(sp, i));\n\t\tif (results.every((r) => !r)) return null;\n\t\tconst subpaths = node.subpaths.flatMap((sp, i) => results[i] ?? [sp]);\n\t\tif (node.subpaths.length === 1) return this.replaceWithPieces(node, subpaths.map((sp) => [sp]));\n\t\tthis.replaceNode(node.id, { ...node, subpaths });\n\t\treturn [node.id];\n\t}\n\n\t/**\n\t * Scissors: cuts path `nodeId` at the outline point nearest document point `point` (at an\n\t * anchor when within the pick distance of one). A closed subpath opens there; an open one\n\t * splits in two (a one-subpath path becomes two paths). Returns the ids of the paths.\n\t */\n\tcutPathAt(nodeId: string, point: Vec2): string[] | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path' || node.locked) return null;\n\t\tconst local = this.toLocal(nodeId, point);\n\t\tconst hit = nearestSegment(node, local);\n\t\tif (!hit) return null;\n\t\tconst sp = node.subpaths[hit.subpath];\n\t\tconst n = sp.anchors.length;\n\t\tconst near = [hit.segment, (hit.segment + 1) % n].find((i) => Math.hypot(sp.anchors[i].x - hit.point.x, sp.anchors[i].y - hit.point.y) <= this.tolerance());\n\t\tif (!sp.closed && n > 1 && (near === 0 || near === n - 1) && !(hit.t > 1e-6 && hit.t < 1 - 1e-6)) return null;\n\t\tlet ids: string[] | null = null;\n\t\tthis.change('Cut Path', () => {\n\t\t\tids = this.applyCuts(node, (s, i) => (i !== hit.subpath ? null : near !== undefined ? cutSubpathAt(s, [near]) : splitSubpathAt(s, hit.segment, hit.t)));\n\t\t\tif (ids) {\n\t\t\t\tthis.selection = ids;\n\t\t\t\tthis.anchors = [];\n\t\t\t\tif (this.editingId === nodeId) this.editingId = null;\n\t\t\t}\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn ids;\n\t}\n\n\t/** Scissors on the selected (or given) anchors: each cuts its subpath there (see `cutPathAt`). */\n\tcutAtAnchors(refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tconst byNode = new Map<string, VectorAnchorRef[]>();\n\t\tfor (const r of refs) if (getAnchor(this.doc, r)) byNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r]);\n\t\tif (!byNode.size) return { ok: false, message: 'Select points to cut at.' };\n\t\tconst created: string[] = [];\n\t\tthis.change('Cut Path', () => {\n\t\t\tfor (const [id, list] of byNode) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\tif (node.locked) continue;\n\t\t\t\tconst ids = this.applyCuts(node, (sp, i) => {\n\t\t\t\t\tconst at = list.filter((r) => r.subpath === i).map((r) => r.index);\n\t\t\t\t\tconst pieces = at.length ? cutSubpathAt(sp, at) : null;\n\t\t\t\t\treturn pieces && !(pieces.length === 1 && pieces[0].closed === sp.closed) ? pieces : null;\n\t\t\t\t});\n\t\t\t\tif (ids) created.push(...ids);\n\t\t\t}\n\t\t\tif (created.length) this.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn created.length ? { ok: true } : { ok: false, message: 'Points at the ends of open paths do not cut.' };\n\t}\n\n\t/** Visible, unlocked paths a stroke over `points` can reach: in `ids`, the selection, or (with neither) any whose bounds it crosses. */\n\tprivate strokeTargets(points: readonly Vec2[], ids: readonly string[] | undefined, pad: number): VectorPathNode[] {\n\t\tconst blocked = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n, parent) => {\n\t\t\tif (n.visible === false || n.locked || (parent && blocked.has(parent.id))) blocked.add(n.id);\n\t\t});\n\t\tconst visible = (p: VectorPathNode) => !blocked.has(p.id);\n\t\tif (ids?.length || this.selection.length) return this.pathTargets(ids ?? this.selection).filter(visible);\n\t\tconst box = polylineBounds(points.map(toPoint), pad);\n\t\tif (!box) return [];\n\t\tconst out: VectorPathNode[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || !visible(n)) return;\n\t\t\tconst b = vectorNodeBounds(n, vectorParentMatrix(this.doc.nodes, n.id) ?? IDENTITY_MATRIX);\n\t\t\tif (b && boundsIntersect(b, box)) out.push(n);\n\t\t});\n\t\treturn out;\n\t}\n\n\t/** A stroke's points in node `id`'s own space. */\n\tprivate localPoints(id: string, points: readonly Vec2[]): Point[] {\n\t\tconst inv = invertMatrix(this.worldOf(id));\n\t\treturn points.map((p) => toPoint(applyMatrix(inv, p)));\n\t}\n\n\t/**\n\t * Knife: cuts closed paths along the polyline `points` (document space) wherever it crosses\n\t * them from edge to edge, with no gap between the pieces. It cuts the given paths, the\n\t * selection, or (with neither) every path it crosses. Returns the ids of the pieces (empty\n\t * when nothing was cut).\n\t */\n\tknife(points: readonly Vec2[], options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst pts = simplifyPolyline(points.map(toPoint), 0.25 / this.viewport.zoom).map(([x, y]) => ({ x, y }));\n\t\tif (pts.length < 2) return [];\n\t\tconst plan: { node: VectorPathNode; pieces: VectorSubpath[][] }[] = [];\n\t\tfor (const node of this.strokeTargets(pts, options.ids, 0)) {\n\t\t\tconst closed = node.subpaths.filter((sp) => sp.anchors.length > 1);\n\t\t\tif (!closed.length || closed.some((sp) => !sp.closed)) continue;\n\t\t\tconst result = knifePath(subpathsToBezier(closed), node.fillRule ?? 'nonzero', this.localPoints(node.id, pts));\n\t\t\tif (result) plan.push({ node, pieces: result.map((path) => bezierToSubpaths(path)) });\n\t\t}\n\t\tif (!plan.length) return [];\n\t\tconst created: string[] = [];\n\t\tthis.change('Knife', () => {\n\t\t\tfor (const { node, pieces } of plan) created.push(...this.replaceWithPieces(node, pieces));\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn created;\n\t}\n\n\t/**\n\t * Eraser: rubs out a round stroke of diameter `size` (default: the `eraserSize` setting)\n\t * along `points` (document space). Filled closed paths lose that area (pieces that come\n\t * apart become separate paths); outlines are cut where they pass under it. It erases from\n\t * the given paths, the selection, or (with neither) every path it reaches. Returns the ids\n\t * of the paths it changed or created.\n\t */\n\terase(points: readonly Vec2[], options: { ids?: readonly string[]; size?: number } = {}): string[] {\n\t\tconst width = options.size ?? this.editing.eraserSize;\n\t\tif (!(width > 0) || !points.length) return [];\n\t\tconst pts = simplifyPolyline(points.map(toPoint), Math.min(width * 0.05, 0.25 / this.viewport.zoom));\n\t\tconst region = eraserRegion(pts, width);\n\t\tif (!region.length) return [];\n\t\tconst plan: { node: VectorPathNode; pieces: VectorSubpath[][] }[] = [];\n\t\tconst rb = bezierPathBounds(region);\n\t\tconst reach = rb ? [{ x: rb.minX, y: rb.minY }, { x: rb.maxX, y: rb.maxY }] : points;\n\t\tfor (const node of this.strokeTargets(reach, options.ids, 0)) {\n\t\t\tconst local = transformBezierPath(region, invertMatrix(this.worldOf(node.id)));\n\t\t\tconst live = node.subpaths.filter((sp) => sp.anchors.length > 1);\n\t\t\tif (!live.length) continue;\n\t\t\tif (hasPaint(node.fill) && live.every((sp) => sp.closed)) {\n\t\t\t\tconst faces = eraseFromFill(subpathsToBezier(live), node.fillRule ?? 'nonzero', local);\n\t\t\t\tif (faces) plan.push({ node, pieces: faces.map((f) => bezierToSubpaths(f)) });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst results = live.map((sp) => eraseFromOutline(sp, local));\n\t\t\tif (results.every((r) => !r)) continue;\n\t\t\tconst subpaths = live.flatMap((sp, i) => results[i] ?? [sp]);\n\t\t\tplan.push({ node, pieces: live.length === 1 ? subpaths.map((sp) => [sp]) : [subpaths] });\n\t\t}\n\t\tif (!plan.length) return [];\n\t\tconst changed: string[] = [];\n\t\tthis.change('Erase', () => {\n\t\t\tfor (const { node, pieces } of plan) changed.push(...this.replaceWithPieces(node, pieces));\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t\tif (this.selection.length || options.ids) this.selection = [...new Set([...this.selection, ...changed.filter((id) => this.getNode(id))])];\n\t\t});\n\t\treturn changed;\n\t}\n\n\t/** Ends the pen path being drawn (a lone anchor is removed). */\n\tfinishPath(): void {\n\t\tif (!this.pen) return;\n\t\tconst node = this.getNode(this.pen.nodeId) as VectorPathNode | undefined;\n\t\tconst sp = node?.subpaths[this.pen.subpath];\n\t\tconst pen = this.pen;\n\t\tthis.pen = null;\n\t\tthis.pointer = null;\n\t\tif (node && sp && sp.anchors.length < 2) {\n\t\t\tconst subpaths = node.subpaths.filter((_, i) => i !== pen.subpath);\n\t\t\tthis.change('Delete Path', () => {\n\t\t\t\tthis.replaceNode(node.id, subpaths.length ? { ...node, subpaths } : null);\n\t\t\t\tif (!subpaths.length) {\n\t\t\t\t\tthis.selection = this.selection.filter((id) => id !== node.id);\n\t\t\t\t\tif (this.editingId === node.id) this.editingId = null;\n\t\t\t\t}\n\t\t\t\tthis.anchors = [];\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis.notify();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Clipboard\n\t// -------------------------------------------------------------------------\n\n\t/** Copies the selection. Returns JSON text for the system clipboard (or null). */\n\tcopy(): string | null {\n\t\tconst nodes = this.selectedRoots()\n\t\t\t.map((id) => this.getNode(id))\n\t\t\t.filter((n): n is VectorNode => !!n)\n\t\t\t.map((n) => cloneVectorNode(n));\n\t\tif (!nodes.length) return null;\n\t\tthis.clipboard = nodes;\n\t\treturn JSON.stringify({ type: VECTOR_CLIPBOARD_TYPE, nodes });\n\t}\n\n\tcut(): string | null {\n\t\tconst text = this.copy();\n\t\tif (text) this.removeNodes(this.selectedRoots(), { label: 'Cut' });\n\t\treturn text;\n\t}\n\n\t/**\n\t * Pastes `text` (from `copy()`, or SVG markup) or the internal clipboard, offset by 10, 10.\n\t * Returns the new ids.\n\t */\n\tpaste(text?: string, options: { offset?: Vec2 } = {}): string[] {\n\t\tlet nodes: VectorNode[] | null = null;\n\t\tif (text) {\n\t\t\tconst trimmed = text.trim();\n\t\t\tif (trimmed.startsWith('{')) {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(trimmed);\n\t\t\t\t\tif (data?.type === VECTOR_CLIPBOARD_TYPE && Array.isArray(data.nodes)) nodes = data.nodes;\n\t\t\t\t} catch {\n\t\t\t\t\tnodes = null;\n\t\t\t\t}\n\t\t\t} else if (/<svg[\\s>]/i.test(trimmed)) {\n\t\t\t\ttry {\n\t\t\t\t\tnodes = parseVectorSvg(trimmed).nodes;\n\t\t\t\t} catch {\n\t\t\t\t\tnodes = null;\n\t\t\t\t}\n\t\t\t}\n\t\t} else nodes = this.clipboard;\n\t\tif (!nodes?.length) return [];\n\t\tconst offset = options.offset ?? (text && !text.trim().startsWith('{') ? { x: 0, y: 0 } : { x: 10, y: 10 });\n\t\tconst copies = nodes.map((n) => transformVectorNode(this.freshIds(n), translateMatrix(offset.x, offset.y)));\n\t\tthis.change('Paste', () => {\n\t\t\tthis.setDoc([...this.doc.nodes, ...copies]);\n\t\t\tthis.selection = copies.map((n) => n.id);\n\t\t\tthis.anchors = [];\n\t\t});\n\t\tif (!text) this.clipboard = copies.map((n) => cloneVectorNode(n));\n\t\treturn copies.map((n) => n.id);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Undo\n\t// -------------------------------------------------------------------------\n\n\tundo(): boolean {\n\t\tthis.cancelDrag();\n\t\tthis.pen = null;\n\t\treturn this.history.undo();\n\t}\n\n\tredo(): boolean {\n\t\tthis.cancelDrag();\n\t\treturn this.history.redo();\n\t}\n\n\t/** Deletes selected anchors (direct tool) or nodes. */\n\tdeleteSelection(): VectorActionResult {\n\t\tif (this.tool === 'direct' && this.anchors.length) return this.deleteAnchors();\n\t\treturn this.removeNodes(this.selectedRoots());\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Pointer input\n\t// -------------------------------------------------------------------------\n\n\t/** The fields the anchor / handle helpers read, without building a full state. */\n\tprivate view() {\n\t\treturn { document: this.doc, selection: this.selection, editingId: this.editingId, tool: this.tool, pen: this.pen, selectedAnchors: this.anchors };\n\t}\n\n\tprivate tolerance() {\n\t\treturn this.hitRadius / this.viewport.zoom;\n\t}\n\n\tprivate hitTransformHandle(screen: Vec2): VectorTransformHandle | null {\n\t\tif (this.tool !== 'select' || !this.selection.length) return null;\n\t\tconst frame = this.frameOf(this.selectedRoots());\n\t\tif (!frame) return null;\n\t\tconst { box, handles } = getVectorSelectionBoxGeometry(frame, this.viewport);\n\t\tconst r = this.hitRadius + 2;\n\t\t// Tiny boxes: only corners and rotation, so the box can still be grabbed.\n\t\tconst usable = box.width < 2 * r || box.height < 2 * r ? handles.filter((h) => h.handle.length === 2 || h.handle === 'rotate') : handles;\n\t\tfor (const h of usable) if (Math.hypot(h.screen.x - screen.x, h.screen.y - screen.y) <= r * Math.SQRT2) return h.handle;\n\t\treturn null;\n\t}\n\n\tprivate hitHandle(screen: Vec2): VectorHandleRef | null {\n\t\tfor (const ref of getVisibleHandles(this.view()).reverse()) {\n\t\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\t\tconst h = a?.[ref.handle];\n\t\t\tif (!h) continue;\n\t\t\tconst s = this.documentToScreen(h);\n\t\t\tif (Math.hypot(s.x - screen.x, s.y - screen.y) <= this.hitRadius) return ref;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate cornerView() {\n\t\treturn { ...this.view(), viewport: this.viewport };\n\t}\n\n\tprivate hitCornerWidget(screen: Vec2): VectorCornerWidget | null {\n\t\tlet best: VectorCornerWidget | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const w of getVectorCornerWidgets(this.cornerView())) {\n\t\t\tconst s = this.documentToScreen(w);\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\tif (d <= this.hitRadius && d < bestD) {\n\t\t\t\tbest = w;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\tprivate hitAnchor(screen: Vec2, refs: readonly VectorAnchorRef[]): VectorAnchorRef | null {\n\t\tlet best: VectorAnchorRef | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const ref of refs) {\n\t\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\t\tif (!a) continue;\n\t\t\tconst s = this.documentToScreen(a);\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\tif (d <= this.hitRadius && d < bestD) {\n\t\t\t\tbest = ref;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** Deepest unlocked visible path under `p`. */\n\t/** Live groups being edited (selected, or holding the selection or the edited path): their children are hit as stored. */\n\tprivate enteredGroups(): Set<string> {\n\t\treturn vectorEnteredGroups(this.doc.nodes, this.editingId ? [...this.selection, this.editingId] : this.selection);\n\t}\n\n\tprivate hitPath(p: Vec2): VectorPathNode | null {\n\t\tconst tol = this.tolerance();\n\t\tconst entered = this.enteredGroups();\n\t\tconst search = (list: readonly VectorNode[], parent: AffineMatrix): VectorPathNode | null => {\n\t\t\tfor (let i = list.length - 1; i >= 0; i--) {\n\t\t\t\tconst n = list[i];\n\t\t\t\tif (n.visible === false || n.locked) continue;\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\t// A live group not being edited is hit where it draws (a click in a subtracted\n\t\t\t\t\t// hole goes through), then picks the child under the pointer.\n\t\t\t\t\tif (hasOwnVectorAppearance(n) && !entered.has(n.id) && !hitTestVectorNode(n, p, tol, parent, { entered })) continue;\n\t\t\t\t\tconst found = search(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (found) return found;\n\t\t\t\t} else if (hitTestVectorNode(n, p, tol, parent, { entered })) return n;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\t\treturn search(this.doc.nodes, IDENTITY_MATRIX);\n\t}\n\n\t/** Endpoints of open subpaths of unlocked visible paths (pen tool resumes from them). */\n\tprivate openEndpoints(): VectorAnchorRef[] {\n\t\tconst out: VectorAnchorRef[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || n.locked || n.visible === false) return;\n\t\t\tn.subpaths.forEach((sp, s) => {\n\t\t\t\tif (sp.closed || sp.anchors.length < 1) return;\n\t\t\t\tout.push({ nodeId: n.id, subpath: s, index: 0 });\n\t\t\t\tif (sp.anchors.length > 1) out.push({ nodeId: n.id, subpath: s, index: sp.anchors.length - 1 });\n\t\t\t});\n\t\t});\n\t\treturn out;\n\t}\n\n\tprivate computeHover(screen: Vec2): VectorHover | null {\n\t\tconst p = this.screenToDocument(screen);\n\t\tswitch (this.tool) {\n\t\t\tcase 'select': {\n\t\t\t\tconst handle = this.hitTransformHandle(screen);\n\t\t\t\tif (handle) return { nodeId: null, transformHandle: handle };\n\t\t\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance(), { entered: this.enteredGroups() });\n\t\t\t\treturn node ? { nodeId: node.id } : null;\n\t\t\t}\n\t\t\tcase 'direct': {\n\t\t\t\tconst handle = this.hitHandle(screen);\n\t\t\t\tif (handle) return { nodeId: handle.nodeId, handle };\n\t\t\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\t\t\tif (anchor) return { nodeId: anchor.nodeId, anchor };\n\t\t\t\tconst widget = this.hitCornerWidget(screen);\n\t\t\t\tif (widget) return { nodeId: widget.ref.nodeId, corner: widget.ref };\n\t\t\t\tfor (const id of getEditablePathIds(this.view())) {\n\t\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\t\tconst seg = nearestSegment(node, this.toLocal(id, p));\n\t\t\t\t\tif (seg && seg.distance <= this.tolerance()) {\n\t\t\t\t\t\tconst point = applyMatrix(this.worldOf(id), seg.point);\n\t\t\t\t\t\treturn { nodeId: id, segment: { nodeId: id, subpath: seg.subpath, segment: seg.segment, t: seg.t, point } };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst path = this.hitPath(p);\n\t\t\t\treturn path ? { nodeId: path.id } : null;\n\t\t\t}\n\t\t\tcase 'pen': {\n\t\t\t\tconst refs = this.pen ? [{ nodeId: this.pen.nodeId, subpath: this.pen.subpath, index: 0 }] : this.openEndpoints();\n\t\t\t\tconst anchor = this.hitAnchor(screen, refs);\n\t\t\t\treturn anchor ? { nodeId: anchor.nodeId, anchor } : null;\n\t\t\t}\n\t\t\tcase 'scissors': {\n\t\t\t\tconst seg = this.nearestOutline(p);\n\t\t\t\treturn seg ? { nodeId: seg.nodeId, segment: seg } : null;\n\t\t\t}\n\t\t\tcase 'blend': {\n\t\t\t\tconst hit = this.blendHit(screen, p);\n\t\t\t\tif (!hit) return null;\n\t\t\t\treturn hit.anchor === null ? { nodeId: hit.nodeId } : { nodeId: hit.nodeId, anchor: { nodeId: hit.nodeId, subpath: 0, index: hit.anchor } };\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tconst hit = this.hitWidthHandle(screen);\n\t\t\t\tif (hit) return { nodeId: hit.ref.nodeId, widthPoint: hit.ref };\n\t\t\t\tconst spot = this.strokeSpotAt(p);\n\t\t\t\treturn spot ? { nodeId: spot.nodeId, strokeSpot: spot } : null;\n\t\t\t}\n\t\t\tcase 'gradient': {\n\t\t\t\tconst a = this.getGradientAnnotator();\n\t\t\t\tconst part = a ? hitVectorGradientAnnotator(a, screen) : null;\n\t\t\t\tif (a && part) return { nodeId: a.nodeId, gradient: part };\n\t\t\t\tconst path = this.hitPath(p);\n\t\t\t\treturn path ? { nodeId: path.id } : null;\n\t\t\t}\n\t\t\tcase 'envelope': {\n\t\t\t\tconst hit = this.hitEnvelope(screen, p);\n\t\t\t\tif (hit) return { nodeId: hit.target.node.id, envelope: { nodeId: hit.target.node.id, index: hit.index } };\n\t\t\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance(), { entered: this.enteredGroups() });\n\t\t\t\treturn node ? { nodeId: node.id } : null;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate widthView(): Pick<VectorEditorState, 'document' | 'selection' | 'tool' | 'hover' | 'interaction' | 'selectedWidthPoints'> {\n\t\treturn { document: this.doc, selection: this.selection, tool: this.tool, hover: this.hover, interaction: this.interaction, selectedWidthPoints: this.widthPoints };\n\t}\n\n\t/** The width point centre or side end under `screen` (width tool). */\n\tprivate hitWidthHandle(screen: Vec2): { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null {\n\t\tconst shown = this.hitWidthHandleIn(screen, this.widthView());\n\t\tif (shown) return shown;\n\t\t// The points of the stroke under the pointer, when no hover has shown them yet.\n\t\tconst spot = this.strokeSpotAt(this.screenToDocument(screen));\n\t\treturn spot && spot.nodeId !== this.hover?.nodeId ? this.hitWidthHandleIn(screen, { ...this.widthView(), hover: { nodeId: spot.nodeId } }) : null;\n\t}\n\n\tprivate hitWidthHandleIn(screen: Vec2, view: Pick<VectorEditorState, 'document' | 'selection' | 'tool' | 'hover' | 'interaction' | 'selectedWidthPoints'>): { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null {\n\t\tlet best: { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const h of getVectorWidthHandles(view)) {\n\t\t\tfor (const [part, q] of [['center', h], ['left', h.left], ['right', h.right]] as const) {\n\t\t\t\tconst s = this.documentToScreen(q);\n\t\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\t\t// Ties go to the centre (listed first), so a zero-width point can still be moved.\n\t\t\t\tif (d <= this.hitRadius && d < bestD - 1e-9) {\n\t\t\t\t\tbest = { ref: { ...h.ref, part } };\n\t\t\t\t\tbestD = d;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** The nearest stroked, unlocked visible path whose stroke is under document point `p` (width tool). */\n\tprivate strokeSpotAt(p: Vec2): VectorStrokeSpot | null {\n\t\tlet best: (VectorStrokeSpot & { distance: number }) | null = null;\n\t\tconst tol = this.tolerance();\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || n.visible === false || n.locked) return;\n\t\t\tif (hiddenOrLocked(this.doc.nodes, n.id)) return;\n\t\t\tconst g = vectorStrokeWidthGeometry(n);\n\t\t\tif (!g) return;\n\t\t\tconst m = this.worldOf(n.id);\n\t\t\tconst local = applyMatrix(invertMatrix(m), p);\n\t\t\tconst near = nearestStrokePosition(g.line, [local.x, local.y]);\n\t\t\tif (!near) return;\n\t\t\tconst profile = strokeWidthProfileOf(n);\n\t\t\tconst w = widthProfileAt(profile, near.t);\n\t\t\tconst reach = Math.max(near.side === 'left' ? w.left : w.right, 0) * g.unit + tol;\n\t\t\tif (near.distance > reach || near.distance > widthProfileMaxScale(profile) * g.unit + tol) return;\n\t\t\tif (best && near.distance >= best.distance) return;\n\t\t\tconst nx = near.tangent[1];\n\t\t\tconst ny = -near.tangent[0];\n\t\t\tconst [cx, cy] = near.point;\n\t\t\tbest = {\n\t\t\t\tnodeId: n.id,\n\t\t\t\tsubpath: near.contour,\n\t\t\t\tt: near.t,\n\t\t\t\tpoint: applyMatrix(m, { x: cx, y: cy }),\n\t\t\t\tleft: applyMatrix(m, { x: cx + nx * w.left * g.unit, y: cy + ny * w.left * g.unit }),\n\t\t\t\tright: applyMatrix(m, { x: cx - nx * w.right * g.unit, y: cy - ny * w.right * g.unit }),\n\t\t\t\tdistance: near.distance\n\t\t\t};\n\t\t});\n\t\tif (!best) return null;\n\t\tconst { distance: _d, ...spot } = best as VectorStrokeSpot & { distance: number };\n\t\treturn spot;\n\t}\n\n\tprivate downWidth(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst hit = this.hitWidthHandle(screen);\n\t\tconst spot = hit ? null : this.strokeSpotAt(p);\n\t\tconst nodeId = hit?.ref.nodeId ?? spot?.nodeId;\n\t\tconst node = nodeId ? this.getNode(nodeId) : undefined;\n\t\tconst g = node?.type === 'path' ? vectorStrokeWidthGeometry(node) : null;\n\t\tif (this.widthEdit) this.widthEdit = null;\n\t\tif (!node || node.type !== 'path' || !g) {\n\t\t\t// A click away from strokes deselects (Shift keeps the selection).\n\t\t\tif (!input.shift) this.widthPoints = [];\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst before = this.snapshot();\n\t\tconst local = this.toLocal(node.id, p);\n\t\tlet profile: VectorWidthPoint[];\n\t\tlet ref: VectorWidthPointRef;\n\t\tlet mode: 'width' | 'move' | 'copy' = 'width';\n\t\tlet side: 'both' | 'left' | 'right' = 'both';\n\t\tlet group: number[] = [];\n\t\tlet shift = false;\n\t\tlet t: number;\n\t\tlet subpath: number;\n\t\tif (hit) {\n\t\t\tprofile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\t\tref = { nodeId: node.id, index: hit.ref.index, subpath: hit.ref.subpath };\n\t\t\tt = profile[ref.index]?.t ?? 0;\n\t\t\tsubpath = hit.ref.subpath;\n\t\t\tif (hit.ref.part === 'center') mode = input.alt && profile.length < VECTOR_WIDTH_PROFILE_MAX_POINTS ? 'copy' : 'move';\n\t\t\telse if (input.alt) side = hit.ref.part;\n\t\t\tconst same = this.widthPoints.length > 0 && this.widthPoints[0].nodeId === node.id;\n\t\t\tconst selected = same && this.widthPoints.some((r) => r.index === ref.index);\n\t\t\tif (input.shift && mode !== 'copy') {\n\t\t\t\t// Shift-click adds the point to the selection, or takes it out (and drags nothing).\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.widthPoints = this.widthPoints.filter((r) => r.index !== ref.index);\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.widthPoints = same ? [...this.widthPoints, ref] : [ref];\n\t\t\t\tshift = true;\n\t\t\t} else if (mode === 'copy' || !selected) this.widthPoints = [ref];\n\t\t\tif (mode !== 'copy') group = this.widthPoints.filter((r) => r.index !== ref.index).map((r) => r.index);\n\t\t} else {\n\t\t\tconst near = nearestStrokePosition(g.line, [local.x, local.y])!;\n\t\t\tconst inserted = insertWidthPoint(strokeWidthProfileOf(node), near.t);\n\t\t\tprofile = inserted.points;\n\t\t\tsubpath = near.contour;\n\t\t\tt = near.t;\n\t\t\tref = { nodeId: node.id, index: inserted.index, subpath };\n\t\t\tif (input.alt) side = near.side;\n\t\t\tthis.widthPoints = [ref];\n\t\t}\n\t\tconst at = strokePositionPoint(g.line, subpath, t);\n\t\tif (!at) return;\n\t\tconst base = { ...this.doc, nodes: mapTree(this.doc.nodes, (n) => (n.id === node.id ? { ...(n as VectorPathNode), strokeWidthProfile: profile } : n)) };\n\t\tthis.doc = base;\n\t\tthis.drag = {\n\t\t\tkind: 'width',\n\t\t\tref,\n\t\t\tmode,\n\t\t\tside,\n\t\t\tsource: ref.index,\n\t\t\tgroup,\n\t\t\tshift,\n\t\t\trenumber: null,\n\t\t\torigin: { x: at.point[0], y: at.point[1] },\n\t\t\tnormal: { x: at.tangent[1], y: -at.tangent[0] },\n\t\t\tunit: g.unit,\n\t\t\tprofile,\n\t\t\tbefore,\n\t\t\tbase,\n\t\t\tstart: p,\n\t\t\tmoved: false,\n\t\t\tcreated: !hit\n\t\t};\n\t\tconst w = profile[ref.index];\n\t\tthis.interaction = { type: 'width', ref, mode, width: (w.left + w.right) * g.unit };\n\t\tthis.notify(!hit);\n\t}\n\n\t/**\n\t * A width-tool slide to `t` on the dragged point's subpath lands exactly on another width\n\t * point (not `skip`) within the pick distance on screen: dropping a point onto another makes\n\t * a discontinuous point (two points at one `t`, the width steps there).\n\t */\n\tprivate snapWidthT(drag: Extract<Drag, { kind: 'width' }>, node: VectorPathNode, line: BezierPath, t: number, skip: number): number {\n\t\tconst m = this.worldOf(node.id, drag.base);\n\t\tconst at = strokePositionPoint(line, drag.ref.subpath, t);\n\t\tif (!at) return t;\n\t\tconst here = this.documentToScreen(applyMatrix(m, { x: at.point[0], y: at.point[1] }));\n\t\tlet best = t;\n\t\tlet bestD = this.hitRadius;\n\t\tdrag.profile.forEach((w, i) => {\n\t\t\tif (i === skip || drag.group.includes(i)) return;\n\t\t\tconst q = strokePositionPoint(line, drag.ref.subpath, w.t);\n\t\t\tif (!q) return;\n\t\t\tconst s = this.documentToScreen(applyMatrix(m, { x: q.point[0], y: q.point[1] }));\n\t\t\tconst d = Math.hypot(s.x - here.x, s.y - here.y);\n\t\t\tif (d <= bestD) {\n\t\t\t\tbest = w.t;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t});\n\t\treturn best;\n\t}\n\n\t/** The nearest outline point of any visible, unlocked path within the pick distance of document point `p`. */\n\tprivate nearestOutline(p: Vec2): NonNullable<VectorHover['segment']> | null {\n\t\tlet best: (NonNullable<VectorHover['segment']> & { distance: number }) | null = null;\n\t\tconst tol = this.tolerance();\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (let i = list.length - 1; i >= 0; i--) {\n\t\t\t\tconst n = list[i];\n\t\t\t\tif (n.visible === false || n.locked) continue;\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tvisit(n.children, m);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst hit = nearestSegment(n, applyMatrix(invertMatrix(m), p));\n\t\t\t\t// Node matrices are rigid, so local distances are document distances.\n\t\t\t\tif (hit && hit.distance <= tol && (!best || hit.distance < best.distance - 1e-9)) {\n\t\t\t\t\tbest = { nodeId: n.id, subpath: hit.subpath, segment: hit.segment, t: hit.t, point: applyMatrix(m, hit.point), distance: hit.distance };\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvisit(this.doc.nodes, IDENTITY_MATRIX);\n\t\tif (!best) return null;\n\t\tconst { distance: _d, ...seg } = best as NonNullable<VectorHover['segment']> & { distance: number };\n\t\treturn seg;\n\t}\n\n\tprivate sameHover(a: VectorHover | null, b: VectorHover | null): boolean {\n\t\treturn JSON.stringify(a) === JSON.stringify(b);\n\t}\n\n\t/** Primary button down on the canvas at `screen` (pixels relative to the canvas). */\n\tpointerDown(screen: Vec2, input: VectorPointerInput = {}): void {\n\t\tthis.cancelDrag();\n\t\tif (input.button === 1 || this.spaceHeld) {\n\t\t\tthis.drag = { kind: 'pan', start: screen, viewport: this.viewport };\n\t\t\tthis.interaction = { type: 'pan' };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (input.button !== undefined && input.button !== 0) return;\n\t\tconst p = this.screenToDocument(screen);\n\t\tthis.pointer = p;\n\t\tswitch (this.tool) {\n\t\t\tcase 'select':\n\t\t\t\treturn this.downSelect(screen, p, input);\n\t\t\tcase 'direct':\n\t\t\t\treturn this.downDirect(screen, p, input);\n\t\t\tcase 'pen':\n\t\t\t\treturn this.downPen(screen, p, input);\n\t\t\tcase 'pencil':\n\t\t\t\treturn this.downPencil(p, input);\n\t\t\tcase 'width':\n\t\t\t\treturn this.downWidth(screen, p, input);\n\t\t\tcase 'shapeBuilder':\n\t\t\tcase 'paintBucket':\n\t\t\t\treturn this.downBuilder(p, input);\n\t\t\tcase 'blend':\n\t\t\t\treturn this.downBlend(screen, p);\n\t\t\tcase 'gradient':\n\t\t\t\treturn this.downGradient(screen, p, input);\n\t\t\tcase 'envelope':\n\t\t\t\treturn this.downEnvelope(screen, p, input);\n\t\t\tcase 'scissors': {\n\t\t\t\tconst seg = this.nearestOutline(p);\n\t\t\t\tif (seg) this.cutPathAt(seg.nodeId, seg.point);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'knife':\n\t\t\tcase 'eraser':\n\t\t\t\tthis.drag = { kind: 'stroke', tool: this.tool, points: [p], before: this.snapshot() };\n\t\t\t\tthis.interaction = { type: 'stroke', tool: this.tool, points: [p], width: this.tool === 'eraser' ? this.editing.eraserSize : 0 };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\treturn this.downShape(p, input);\n\t\t}\n\t}\n\n\t/** The shape under the pointer for the Blend tool, and the anchor of its first subpath under it. */\n\tprivate blendHit(screen: Vec2, p: Vec2): VectorBlendStart | null {\n\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance());\n\t\tif (!node) return null;\n\t\tlet anchor: number | null = null;\n\t\tif (node.type === 'path' && node.subpaths[0]) {\n\t\t\tconst refs = node.subpaths[0].anchors.map((_, index) => ({ nodeId: node.id, subpath: 0, index }));\n\t\t\tanchor = this.hitAnchor(screen, refs)?.index ?? null;\n\t\t}\n\t\treturn { nodeId: node.id, anchor };\n\t}\n\n\t/** Blend tool: the first click picks the shape to blend from, the next one blends it into the shape clicked. */\n\tprivate downBlend(screen: Vec2, p: Vec2) {\n\t\tconst hit = this.blendHit(screen, p);\n\t\tconst start = this.blendStart;\n\t\tif (!hit) {\n\t\t\tif (start) {\n\t\t\t\tthis.blendStart = null;\n\t\t\t\tthis.notify();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!start || start.nodeId === hit.nodeId) {\n\t\t\tthis.blendStart = hit;\n\t\t\tthis.selection = [hit.nodeId];\n\t\t\tthis.anchors = [];\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.blendStart = null;\n\t\tconst first = this.getNode(start.nodeId);\n\t\tif (isVectorBlendGroup(first)) {\n\t\t\t// Clicking on from a blend adds the shape as its next key.\n\t\t\tif (!this.addBlendKey(first.id, hit.nodeId, { start: hit.anchor }).ok) this.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst starts: Record<string, number> = {};\n\t\tif (start.anchor !== null) starts[start.nodeId] = start.anchor;\n\t\tif (hit.anchor !== null) starts[hit.nodeId] = hit.anchor;\n\t\tif (!this.blend({ ids: [start.nodeId, hit.nodeId], keepOrder: true, starts })) this.notify();\n\t}\n\n\tprivate downSelect(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst handle = this.hitTransformHandle(screen);\n\t\tif (handle) {\n\t\t\tconst frame = this.frameOf(this.selectedRoots())!;\n\t\t\tconst before = this.snapshot();\n\t\t\tconst center = applyMatrix(rotateMatrix(frame.angle), { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 });\n\t\t\tthis.drag =\n\t\t\t\thandle === 'rotate'\n\t\t\t\t\t? { kind: 'rotate', start: p, center, before, base: this.doc }\n\t\t\t\t\t: { kind: 'scale', handle, start: p, frame, before, base: this.doc };\n\t\t\tthis.interaction = handle === 'rotate' ? { type: 'rotate', angle: 0 } : { type: 'scale', handle, sx: 1, sy: 1 };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance(), { entered: this.enteredGroups() });\n\t\tif (node) {\n\t\t\tconst selected = this.selection.includes(node.id);\n\t\t\tif (input.shift) {\n\t\t\t\tthis.selection = selected ? this.selection.filter((id) => id !== node.id) : [...this.selection, node.id];\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!selected) this.selection = [node.id];\n\t\t\tthis.anchors = [];\n\t\t\tconst before = this.snapshot();\n\t\t\tthis.drag = {\n\t\t\t\tkind: 'move',\n\t\t\t\tstart: p,\n\t\t\t\torigin: this.boundsOf(this.selectedRoots()),\n\t\t\t\tbefore,\n\t\t\t\tbase: this.doc,\n\t\t\t\tmoved: false,\n\t\t\t\tduplicated: false,\n\t\t\t\tclickId: selected && !input.shift ? node.id : null\n\t\t\t};\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!input.shift) this.selection = [];\n\t\tthis.drag = { kind: 'marquee', start: p, base: this.selection, baseAnchors: [], anchorsMode: false };\n\t\tthis.interaction = { type: 'marquee', bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify();\n\t}\n\n\tprivate downDirect(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst handle = this.hitHandle(screen);\n\t\tif (handle) {\n\t\t\tthis.drag = { kind: 'handle', ref: handle, before: this.snapshot(), base: this.doc };\n\t\t\tthis.interaction = { type: 'handle', ref: handle };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\tif (anchor) {\n\t\t\tconst selected = this.anchors.some((a) => sameRef(a, anchor));\n\t\t\tthis.editingId = anchor.nodeId;\n\t\t\tif (input.alt) {\n\t\t\t\t// Alt-drag an anchor pulls out fresh symmetric handles.\n\t\t\t\tthis.anchors = [anchor];\n\t\t\t\tthis.drag = { kind: 'pull', ref: anchor, before: this.snapshot(), base: this.doc, label: 'Make Smooth', outOnly: false, closing: false, altBreaks: false };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (input.shift) {\n\t\t\t\tthis.anchors = selected ? this.anchors.filter((a) => !sameRef(a, anchor)) : [...this.anchors, anchor];\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!selected) this.anchors = [anchor];\n\t\t\tthis.drag = { kind: 'anchors', start: p, before: this.snapshot(), base: this.doc, moved: false, clickRef: selected && !input.shift ? anchor : null, lead: anchor };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst widget = this.hitCornerWidget(screen);\n\t\tif (widget) {\n\t\t\tconst refs = getVectorCornerWidgets(this.cornerView()).map((w) => w.ref);\n\t\t\tthis.drag = { kind: 'corner', widget, refs, start: p, before: this.snapshot(), base: this.doc, moved: false, alt: !!input.alt, shift: !!input.shift };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tfor (const id of getEditablePathIds(this.view())) {\n\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\tconst seg = nearestSegment(node, this.toLocal(id, p));\n\t\t\tif (!seg || seg.distance > this.tolerance()) continue;\n\t\t\tconst sp = node.subpaths[seg.subpath];\n\t\t\tif (input.alt) {\n\t\t\t\tconst before = this.snapshot();\n\t\t\t\tconst { subpath, index } = insertAnchor(sp, seg.segment, seg.t);\n\t\t\t\tthis.replaceNode(id, { ...node, subpaths: node.subpaths.map((s, i) => (i === seg.subpath ? subpath : s)) });\n\t\t\t\tconst ref = { nodeId: id, subpath: seg.subpath, index };\n\t\t\t\tthis.anchors = [ref];\n\t\t\t\tthis.editingId = id;\n\t\t\t\tthis.drag = { kind: 'anchors', start: p, before, base: this.doc, moved: true, clickRef: null, lead: ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A click selects the segment's anchors; a drag bends it through the pointer.\n\t\t\tconst a = { nodeId: id, subpath: seg.subpath, index: seg.segment };\n\t\t\tconst b = { nodeId: id, subpath: seg.subpath, index: (seg.segment + 1) % sp.anchors.length };\n\t\t\tthis.anchors = input.shift ? [...this.anchors.filter((r) => !sameRef(r, a) && !sameRef(r, b)), a, b] : [a, b];\n\t\t\tthis.editingId = id;\n\t\t\tthis.drag = { kind: 'bend', ref: { nodeId: id, subpath: seg.subpath, segment: seg.segment }, t: seg.t, start: p, before: this.snapshot(), base: this.doc, moved: false };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst path = this.hitPath(p);\n\t\tif (path) {\n\t\t\tthis.editingId = path.id;\n\t\t\tif (!input.shift) this.selection = [path.id];\n\t\t\telse if (!this.selection.includes(path.id)) this.selection = [...this.selection, path.id];\n\t\t\tthis.anchors = path.subpaths.flatMap((sp, s) => sp.anchors.map((_, i) => ({ nodeId: path.id, subpath: s, index: i })));\n\t\t\tthis.drag = { kind: 'anchors', start: p, before: this.snapshot(), base: this.doc, moved: false, clickRef: null, lead: null };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!input.shift) {\n\t\t\tthis.anchors = [];\n\t\t}\n\t\tthis.drag = { kind: 'marquee', start: p, base: this.selection, baseAnchors: this.anchors, anchorsMode: getEditablePathIds(this.view()).length > 0 };\n\t\tthis.interaction = { type: 'marquee', bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify();\n\t}\n\n\tprivate downPen(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\tconst sp = this.pen ? (this.getNode(this.pen.nodeId) as VectorPathNode | undefined)?.subpaths[this.pen.subpath] : undefined;\n\t\tif (this.pen && sp) {\n\t\t\tconst pen = this.pen;\n\t\t\tconst first = { nodeId: pen.nodeId, subpath: pen.subpath, index: 0 };\n\t\t\tif (sp.anchors.length >= 2 && this.hitAnchor(screen, [first])) {\n\t\t\t\tconst node = this.getNode(pen.nodeId) as VectorPathNode;\n\t\t\t\tthis.replaceNode(pen.nodeId, { ...node, subpaths: node.subpaths.map((s, i) => (i === pen.subpath ? { ...s, closed: true } : s)) });\n\t\t\t\tthis.drag = { kind: 'pull', ref: first, before, base: this.doc, label: 'Close Path', outOnly: false, closing: true, altBreaks: true };\n\t\t\t\tthis.interaction = { type: 'pen', nodeId: pen.nodeId };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst last = getAnchorWorld(this.doc, { nodeId: pen.nodeId, subpath: pen.subpath, index: sp.anchors.length - 1 })!;\n\t\t\tconst leave = { at: { x: last.x, y: last.y }, constrain: input.shift ? ('angle' as const) : null };\n\t\t\tlet pt = this.snapDrawn(p, leave, input, () => this.drawingTargets(pen.nodeId));\n\t\t\tpt = this.toLocal(pen.nodeId, pt);\n\t\t\tconst node = this.getNode(pen.nodeId) as VectorPathNode;\n\t\t\tconst anchors = [...sp.anchors, { x: pt.x, y: pt.y }];\n\t\t\tthis.replaceNode(pen.nodeId, { ...node, subpaths: node.subpaths.map((s, i) => (i === pen.subpath ? { ...s, anchors } : s)) });\n\t\t\tconst ref = { nodeId: pen.nodeId, subpath: pen.subpath, index: anchors.length - 1 };\n\t\t\tthis.anchors = [ref];\n\t\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Add Point', outOnly: false, closing: false, altBreaks: true };\n\t\t\tthis.interaction = { type: 'pen', nodeId: pen.nodeId };\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tconst endpoint = this.hitAnchor(screen, this.openEndpoints());\n\t\tif (endpoint) {\n\t\t\tlet node = this.getNode(endpoint.nodeId) as VectorPathNode;\n\t\t\tlet index = endpoint.index;\n\t\t\tif (index === 0 && node.subpaths[endpoint.subpath].anchors.length > 1) {\n\t\t\t\tnode = { ...node, subpaths: node.subpaths.map((s, i) => (i === endpoint.subpath ? reverseSubpath(s) : s)) };\n\t\t\t\tthis.replaceNode(node.id, node);\n\t\t\t\tindex = node.subpaths[endpoint.subpath].anchors.length - 1;\n\t\t\t}\n\t\t\tthis.pen = { nodeId: node.id, subpath: endpoint.subpath };\n\t\t\tthis.selection = [node.id];\n\t\t\tthis.editingId = node.id;\n\t\t\tconst ref = { nodeId: node.id, subpath: endpoint.subpath, index };\n\t\t\tthis.anchors = [ref];\n\t\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Continue Path', outOnly: true, closing: false, altBreaks: true };\n\t\t\tthis.interaction = { type: 'pen', nodeId: node.id };\n\t\t\tthis.notify(this.doc !== before.doc);\n\t\t\treturn;\n\t\t}\n\t\tconst pt = this.snapDrawn(p, null, input, () => this.drawingTargets(null));\n\t\tconst node: VectorPathNode = { id: this.newId(), type: 'path', name: 'Path', ...this.styleFor(true), subpaths: [{ anchors: [{ x: pt.x, y: pt.y }], closed: false }] };\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tthis.pen = { nodeId: node.id, subpath: 0 };\n\t\tthis.selection = [node.id];\n\t\tthis.editingId = node.id;\n\t\tconst ref = { nodeId: node.id, subpath: 0, index: 0 };\n\t\tthis.anchors = [ref];\n\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Start Path', outOnly: false, closing: false, altBreaks: true };\n\t\tthis.interaction = { type: 'pen', nodeId: node.id };\n\t\tthis.notify(true);\n\t}\n\n\tprivate downPencil(p: Vec2, input: VectorPointerInput = {}) {\n\t\tconst before = this.snapshot();\n\t\tconst node: VectorPathNode = {\n\t\t\tid: this.newId(),\n\t\t\ttype: 'path',\n\t\t\tname: 'Pencil',\n\t\t\t...this.styleFor(true),\n\t\t\tstrokeLinecap: this.defaults.strokeLinecap ?? 'round',\n\t\t\tstrokeLinejoin: this.defaults.strokeLinejoin ?? 'round',\n\t\t\tsubpaths: [{ anchors: [{ x: p.x, y: p.y }], closed: false }]\n\t\t};\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tconst lazy = new LazyMouse((this.editing.pencilSmoothing * VECTOR_PENCIL_STRING_PX) / this.viewport.zoom);\n\t\tlazy.push([p.x, p.y]);\n\t\tconst mode = this.editing.pencilPressure;\n\t\tconst hasPressure = typeof input.pressure === 'number' && Number.isFinite(input.pressure);\n\t\tconst record = hasPressure && (mode === 'all' || (mode === 'pen' && input.pointerType === 'pen'));\n\t\tconst pressure = hasPressure ? input.pressure! : 0.5;\n\t\tthis.drag = { kind: 'pencil', nodeId: node.id, points: [[p.x, p.y]], before, lazy, pressures: record ? [pressure] : null, pressure };\n\t\tthis.interaction = { type: 'draw', tool: 'pencil', nodeId: node.id, bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify(true);\n\t}\n\n\tprivate downShape(p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\t// The targets are gathered before the new shape joins the document, and kept for the drag.\n\t\tconst targets = this.drawingTargets(null);\n\t\tconst start = this.snapDrawn(p, null, input, () => targets);\n\t\tconst kind = this.tool as VectorShapeInput['kind'];\n\t\tconst node = this.createShapeNode({ kind, x: start.x, y: start.y, width: 0, height: 0 });\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tthis.drag = { kind: 'shape', tool: this.tool, start, nodeId: node.id, before, targets };\n\t\tthis.interaction = { type: 'draw', tool: this.tool, nodeId: node.id, bounds: { x: start.x, y: start.y, width: 0, height: 0 } };\n\t\tthis.notify(true);\n\t}\n\n\t/** Pointer moved over the canvas (with or without a button down). */\n\tpointerMove(screen: Vec2, input: VectorPointerInput = {}): void {\n\t\tconst p = this.screenToDocument(screen);\n\t\tconst drag = this.drag;\n\t\tif (!drag && (this.tool === 'shapeBuilder' || this.tool === 'paintBucket')) {\n\t\t\tthis.pointer = p;\n\t\t\tif (this.hoverBuilder(p, !!input.alt)) this.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!drag) {\n\t\t\tconst hover = this.computeHover(screen);\n\t\t\tconst pointerMatters = this.tool === 'pen' && !!this.pen;\n\t\t\tconst guides = this.guides;\n\t\t\tthis.hover = hover;\n\t\t\tconst pointer = this.hoverSnap(p, input);\n\t\t\tif (this.sameHover(hover, this.state.hover) && !pointerMatters && JSON.stringify(guides) === JSON.stringify(this.guides)) return;\n\t\t\tthis.pointer = pointer;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.pointer = p;\n\t\tswitch (drag.kind) {\n\t\t\tcase 'pan':\n\t\t\t\tthis.viewport = { ...drag.viewport, x: drag.viewport.x + screen.x - drag.start.x, y: drag.viewport.y + screen.y - drag.start.y };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tcase 'gradient':\n\t\t\t\treturn this.moveGradient(drag, screen, p, input);\n\t\t\tcase 'envelope':\n\t\t\t\treturn this.moveEnvelope(drag, p);\n\t\t\tcase 'move': {\n\t\t\t\tlet dx = p.x - drag.start.x;\n\t\t\t\tlet dy = p.y - drag.start.y;\n\t\t\t\tif (!drag.moved && Math.hypot(dx, dy) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tif (input.shift) Math.abs(dx) > Math.abs(dy) ? (dy = 0) : (dx = 0);\n\t\t\t\tif (input.alt && !drag.duplicated) {\n\t\t\t\t\tdrag.duplicated = true;\n\t\t\t\t\tconst created: string[] = [];\n\t\t\t\t\tdrag.base = this.withDuplicates(drag.base, this.selectedRoots(), { x: 0, y: 0 }, created);\n\t\t\t\t\tthis.selection = created;\n\t\t\t\t\t// The originals stay behind as targets.\n\t\t\t\t\tdrag.targets = undefined;\n\t\t\t\t}\n\t\t\t\t({ dx, dy } = this.snapMove(drag, dx, dy, input));\n\t\t\t\tthis.doc = this.transformed(drag.base, new Set(this.selectedRoots()), translateMatrix(dx, dy));\n\t\t\t\tthis.interaction = { type: 'move', dx, dy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'scale': {\n\t\t\t\tif (this.freeDistort && drag.handle !== 'rotate') return this.moveDistort(drag, p, input);\n\t\t\t\t// Scale in the box's own (possibly rotated) frame.\n\t\t\t\tconst angle = drag.frame.angle;\n\t\t\t\tconst q = angle ? applyMatrix(rotateMatrix(-angle), p) : p;\n\t\t\t\tlet { sx, sy, origin } = scaleFor(drag.handle, drag.frame, q, input);\n\t\t\t\tif (this.snap.objects && !input.mod && drag.handle !== 'rotate') {\n\t\t\t\t\tdrag.targets ??= VectorSnapTargets.forResize(drag.base, this.selectedRoots());\n\t\t\t\t\tconst res = drag.targets.snapScale(drag.frame, drag.handle, sx, sy, input, this.snapTolerance());\n\t\t\t\t\t({ sx, sy } = res);\n\t\t\t\t\tthis.setGuides(res);\n\t\t\t\t} else this.setGuides(null);\n\t\t\t\tconst ids = new Set(this.selectedRoots());\n\t\t\t\tthis.doc = this.transformed(drag.base, ids, this.inFrame(angle, scaleMatrix(sx, sy, origin)));\n\t\t\t\tthis.interaction = { type: 'scale', handle: drag.handle, sx, sy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'rotate': {\n\t\t\t\tconst a0 = Math.atan2(drag.start.y - drag.center.y, drag.start.x - drag.center.x);\n\t\t\t\tconst a1 = Math.atan2(p.y - drag.center.y, p.x - drag.center.x);\n\t\t\t\tlet angle = ((a1 - a0) * 180) / Math.PI;\n\t\t\t\tif (input.shift) angle = Math.round(angle / 15) * 15;\n\t\t\t\tthis.doc = this.transformed(drag.base, new Set(this.selectedRoots()), rotateMatrix(angle, drag.center));\n\t\t\t\tthis.interaction = { type: 'rotate', angle };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'marquee': {\n\t\t\t\tconst bounds = boundsFromPoints(drag.start, p);\n\t\t\t\tthis.interaction = { type: 'marquee', bounds };\n\t\t\t\tif (drag.anchorsMode) {\n\t\t\t\t\tconst inside = getVisibleAnchors(this.view()).filter((r) => {\n\t\t\t\t\t\tconst a = getAnchorWorld(this.doc, r)!;\n\t\t\t\t\t\treturn a.x >= bounds.x && a.x <= bounds.x + bounds.width && a.y >= bounds.y && a.y <= bounds.y + bounds.height;\n\t\t\t\t\t});\n\t\t\t\t\tthis.anchors = [...drag.baseAnchors, ...inside.filter((r) => !drag.baseAnchors.some((b) => sameRef(b, r)))];\n\t\t\t\t} else {\n\t\t\t\t\tconst hits = this.doc.nodes\n\t\t\t\t\t\t.filter((n) => !n.locked && n.visible !== false)\n\t\t\t\t\t\t.filter((n) => {\n\t\t\t\t\t\t\tconst b = vectorNodeBounds(n);\n\t\t\t\t\t\t\treturn b && boundsIntersect(b, bounds);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.map((n) => n.id);\n\t\t\t\t\tthis.selection = [...new Set([...drag.base, ...hits])];\n\t\t\t\t}\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'anchors': {\n\t\t\t\tlet dx = p.x - drag.start.x;\n\t\t\t\tlet dy = p.y - drag.start.y;\n\t\t\t\tif (!drag.moved && Math.hypot(dx, dy) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst lead = this.leadAnchor(drag);\n\t\t\t\tif (lead) {\n\t\t\t\t\t// The grabbed (or nearest) anchor snaps; the others move with it.\n\t\t\t\t\tconst leave = input.shift ? { at: lead, constrain: 'axis' as const, curves: false } : null;\n\t\t\t\t\tconst q = this.snapDrawn({ x: lead.x + dx, y: lead.y + dy }, leave, input, () => (drag.targets ??= VectorSnapTargets.forAnchorDrag(drag.base, this.anchors)));\n\t\t\t\t\tdx = q.x - lead.x;\n\t\t\t\t\tdy = q.y - lead.y;\n\t\t\t\t} else if (input.shift) Math.abs(dx) > Math.abs(dy) ? (dy = 0) : (dx = 0);\n\t\t\t\tconst single = this.anchors.length === 1 ? this.anchors[0] : null;\n\t\t\t\tconst from = single ? getAnchorWorld(drag.base, single) : undefined;\n\t\t\t\t// A lone point bends its segments with the Curvature setting (Alt held flips it).\n\t\t\t\tif (single && from && this.editing.curvatureMoves !== !!input.alt) this.doc = this.curvatureMoved(drag.base, single, { x: from.x + dx, y: from.y + dy });\n\t\t\t\telse this.doc = this.movedAnchors(drag.base, this.anchors, dx, dy);\n\t\t\t\tthis.interaction = { type: 'anchors', dx, dy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'handle': {\n\t\t\t\tconst anchor = getAnchorWorld(drag.base, drag.ref);\n\t\t\t\tconst leave = anchor ? { at: { x: anchor.x, y: anchor.y }, constrain: input.shift ? ('angle' as const) : null } : null;\n\t\t\t\tconst pt = this.snapDrawn(p, leave, input, () => (drag.targets ??= VectorSnapTargets.forHandle(drag.base, drag.ref.nodeId)));\n\t\t\t\tconst local = this.toLocal(drag.ref.nodeId, pt, drag.base);\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, [drag.ref], (a) => moveAnchorHandle(a, drag.ref.handle, local, input.alt));\n\t\t\t\tthis.interaction = { type: 'handle', ref: drag.ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'corner': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 3) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst c = drag.widget.corner;\n\t\t\t\tconst inv = invertMatrix(this.worldOf(drag.widget.ref.nodeId, drag.base));\n\t\t\t\tconst d = applyMatrixLinear(inv, { x: p.x - drag.start.x, y: p.y - drag.start.y });\n\t\t\t\tconst radius = Math.max(0, Math.min(c.maxRadius, drag.widget.drawnRadius + cornerRadiusChange(c, d)));\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, drag.refs, (a) => setAnchorCorner(a, radius));\n\t\t\t\tthis.interaction = { type: 'corner', ref: drag.widget.ref, radius };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'bend': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tthis.doc = this.bent(drag.base, drag.ref, drag.t, p);\n\t\t\t\tthis.interaction = { type: 'bend', ref: drag.ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'builder':\n\t\t\t\treturn this.moveBuilder(drag, p);\n\t\t\tcase 'stroke': {\n\t\t\t\tconst last = drag.points[drag.points.length - 1];\n\t\t\t\tif (Math.hypot(p.x - last.x, p.y - last.y) * this.viewport.zoom < 1.5) return;\n\t\t\t\tdrag.points.push(p);\n\t\t\t\tthis.interaction = { type: 'stroke', tool: drag.tool, points: drag.points.slice(), width: drag.tool === 'eraser' ? this.editing.eraserSize : 0 };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pull': {\n\t\t\t\tconst anchor = getAnchorWorld(drag.base, drag.ref);\n\t\t\t\tif (!anchor) return;\n\t\t\t\tif (Math.hypot(p.x - anchor.x, p.y - anchor.y) * this.viewport.zoom < 2) {\n\t\t\t\t\tthis.doc = drag.base;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.guides = null;\n\t\t\t\tlet pt = p;\n\t\t\t\tif (input.shift) pt = constrain45(anchor, pt);\n\t\t\t\tconst side = drag.closing ? 'in' : 'out';\n\t\t\t\t// Dragging out of the closing anchor pulls its incoming handle toward the pointer's mirror.\n\t\t\t\tconst pos = this.toLocal(drag.ref.nodeId, drag.closing ? { x: 2 * anchor.x - pt.x, y: 2 * anchor.y - pt.y } : pt, drag.base);\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, [drag.ref], (a) => {\n\t\t\t\t\tif (drag.outOnly || (drag.altBreaks && input.alt)) return moveAnchorHandle(a, side, pos, true);\n\t\t\t\t\treturn moveAnchorHandle({ ...a, type: 'symmetric' }, side, pos);\n\t\t\t\t});\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'shape': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path') return;\n\t\t\t\tconst leave = { at: drag.start, constrain: input.shift ? (drag.tool === 'line' ? ('angle' as const) : ('square' as const)) : null, curves: false };\n\t\t\t\tlet end = this.snapDrawn(p, leave, input, () => (drag.targets ??= this.drawingTargets(null)));\n\t\t\t\tif (!this.snappedToObject && drag.tool !== 'line' && !input.shift && !input.mod && this.snap.objects && drag.targets) end = this.matchShapeSize(drag.targets, drag.start, end, input.alt);\n\t\t\t\tlet start = drag.start;\n\t\t\t\tlet bounds: VectorBounds;\n\t\t\t\tif (drag.tool === 'line') {\n\t\t\t\t\tif (input.shift) end = constrain45(start, end);\n\t\t\t\t\tif (input.alt) start = { x: 2 * start.x - end.x, y: 2 * start.y - end.y };\n\t\t\t\t\tbounds = { x: start.x, y: start.y, width: end.x - start.x, height: end.y - start.y };\n\t\t\t\t} else {\n\t\t\t\t\tlet w = end.x - start.x;\n\t\t\t\t\tlet h = end.y - start.y;\n\t\t\t\t\tif (input.shift) {\n\t\t\t\t\t\tconst s = Math.max(Math.abs(w), Math.abs(h));\n\t\t\t\t\t\tw = Math.sign(w || 1) * s;\n\t\t\t\t\t\th = Math.sign(h || 1) * s;\n\t\t\t\t\t}\n\t\t\t\t\tif (input.alt) start = { x: start.x - w, y: start.y - h };\n\t\t\t\t\tconst x2 = drag.start.x + w;\n\t\t\t\t\tconst y2 = drag.start.y + h;\n\t\t\t\t\tbounds = boundsFromPoints(start, { x: x2, y: y2 });\n\t\t\t\t}\n\t\t\t\tconst shaped = this.createShapeNode({ kind: drag.tool as VectorShapeInput['kind'], ...bounds });\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths: shaped.subpaths });\n\t\t\t\tthis.interaction = { type: 'draw', tool: drag.tool, nodeId: drag.nodeId, bounds };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst node = findVectorNode(drag.base.nodes, drag.ref.nodeId) as VectorPathNode;\n\t\t\t\tconst local = this.toLocal(node.id, p, drag.base);\n\t\t\t\tconst src = drag.profile[drag.source];\n\t\t\t\tlet profile: VectorWidthPoint[];\n\t\t\t\tlet index = drag.source;\n\t\t\t\tif (drag.mode !== 'width') {\n\t\t\t\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\t\t\t\tconst near = g ? nearestStrokePosition(g.line, [local.x, local.y], drag.ref.subpath) : null;\n\t\t\t\t\tif (!g || !near) return;\n\t\t\t\t\tconst t = drag.group.length ? near.t : this.snapWidthT(drag, node, g.line, near.t, drag.source);\n\t\t\t\t\tif (drag.mode === 'copy') {\n\t\t\t\t\t\t// The source stays; a copy of it slides (and may pass other points).\n\t\t\t\t\t\t({ points: profile, index } = insertWidthPoint(drag.profile, t, { left: src.left, right: src.right }, { step: true }));\n\t\t\t\t\t} else if (drag.group.length) {\n\t\t\t\t\t\tconst shifted = shiftWidthPoints(drag.profile, [drag.source, ...drag.group], t - src.t);\n\t\t\t\t\t\tprofile = shifted.points;\n\t\t\t\t\t\tdrag.renumber = shifted.renumber;\n\t\t\t\t\t\tindex = shifted.renumber.get(drag.source) ?? drag.source;\n\t\t\t\t\t} else profile = setWidthPoint(drag.profile, drag.source, { t });\n\t\t\t\t} else {\n\t\t\t\t\tconst off = ((local.x - drag.origin.x) * drag.normal.x + (local.y - drag.origin.y) * drag.normal.y) / drag.unit;\n\t\t\t\t\tconst patch =\n\t\t\t\t\t\tdrag.side === 'both' ? { left: Math.abs(off), right: Math.abs(off) } : drag.side === 'left' ? { left: Math.max(0, off) } : { right: Math.max(0, -off) };\n\t\t\t\t\tprofile = setWidthPoint(drag.profile, drag.source, patch);\n\t\t\t\t\tif (drag.group.length) {\n\t\t\t\t\t\t// Every selected point widens by as much as the dragged one.\n\t\t\t\t\t\tconst dl = profile[drag.source].left - src.left;\n\t\t\t\t\t\tconst dr = profile[drag.source].right - src.right;\n\t\t\t\t\t\tfor (const i of drag.group) profile = setWidthPoint(profile, i, { left: Math.max(0, drag.profile[i].left + dl), right: Math.max(0, drag.profile[i].right + dr) });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.doc = { ...drag.base, nodes: mapTree(drag.base.nodes, (n) => (n.id === node.id ? { ...(n as VectorPathNode), strokeWidthProfile: profile } : n)) };\n\t\t\t\tdrag.ref = { ...drag.ref, index };\n\t\t\t\tconst w = profile[index];\n\t\t\t\tthis.interaction = { type: 'width', ref: drag.ref, mode: drag.mode, width: (w.left + w.right) * drag.unit };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pencil': {\n\t\t\t\tconst last = drag.points[drag.points.length - 1];\n\t\t\t\tlet moved = false;\n\t\t\t\tif (typeof input.pressure === 'number' && Number.isFinite(input.pressure)) drag.pressure = input.pressure;\n\t\t\t\tfor (const q of drag.lazy.push([p.x, p.y])) {\n\t\t\t\t\tif (Math.hypot(q[0] - last[0], q[1] - last[1]) * this.viewport.zoom < 1.5) continue;\n\t\t\t\t\tdrag.points.push(q);\n\t\t\t\t\tdrag.pressures?.push(drag.pressure);\n\t\t\t\t\tmoved = true;\n\t\t\t\t}\n\t\t\t\tconst string = drag.lazy.string();\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path') return;\n\t\t\t\tif (!moved) {\n\t\t\t\t\tif (string && this.interaction?.type === 'draw') {\n\t\t\t\t\t\tthis.interaction = { ...this.interaction, string: [{ x: string[0][0], y: string[0][1] }, { x: string[1][0], y: string[1][1] }] };\n\t\t\t\t\t\tthis.notify();\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths: [{ anchors: drag.points.map(([x, y]) => ({ x, y })), closed: false }] });\n\t\t\t\tconst xs = drag.points.map((q) => q[0]);\n\t\t\t\tconst ys = drag.points.map((q) => q[1]);\n\t\t\t\tthis.interaction = {\n\t\t\t\t\ttype: 'draw',\n\t\t\t\t\ttool: 'pencil',\n\t\t\t\t\tnodeId: drag.nodeId,\n\t\t\t\t\tbounds: { x: Math.min(...xs), y: Math.min(...ys), width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys) },\n\t\t\t\t\t...(string ? { string: [{ x: string[0][0], y: string[0][1] }, { x: string[1][0], y: string[1][1] }] as [Vec2, Vec2] } : {})\n\t\t\t\t};\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Snaps a move of the selection by (dx, dy): its bounds line up with targets or space evenly, else go to the grid. */\n\tprivate snapMove(drag: Extract<Drag, { kind: 'move' }>, dx: number, dy: number, input: VectorModifiers): { dx: number; dy: number } {\n\t\tconst origin = drag.origin;\n\t\tif (input.mod || !origin) {\n\t\t\tthis.setGuides(null);\n\t\t\treturn { dx, dy };\n\t\t}\n\t\t// A Shift-locked axis stays put.\n\t\tconst axes = { x: !input.shift || dx !== 0, y: !input.shift || dy !== 0 };\n\t\tlet res = null;\n\t\tif (this.snap.objects) {\n\t\t\tdrag.targets ??= VectorSnapTargets.forMove(drag.base, this.selectedRoots());\n\t\t\tres = drag.targets.snapRect({ ...origin, x: origin.x + dx, y: origin.y + dy }, this.snapTolerance(), { spacing: true, axes });\n\t\t}\n\t\tthis.setGuides(res);\n\t\treturn {\n\t\t\tdx: res?.x ? dx + res.dx : axes.x ? this.gridValue(origin.x + dx) - origin.x : dx,\n\t\t\tdy: res?.y ? dy + res.dy : axes.y ? this.gridValue(origin.y + dy) - origin.y : dy\n\t\t};\n\t}\n\n\t/** The anchor a point drag snaps by, where it started: the grabbed one, else the moving one nearest the press. */\n\tprivate leadAnchor(drag: Extract<Drag, { kind: 'anchors' }>): Vec2 | null {\n\t\tconst ref = drag.lead && this.anchors.some((a) => sameRef(a, drag.lead!)) ? drag.lead : null;\n\t\tif (ref) {\n\t\t\tconst a = getAnchorWorld(drag.base, ref);\n\t\t\treturn a ? { x: a.x, y: a.y } : null;\n\t\t}\n\t\tlet best: Vec2 | null = null;\n\t\tfor (const r of this.anchors) {\n\t\t\tconst a = getAnchorWorld(drag.base, r);\n\t\t\tif (a && (!best || Math.hypot(a.x - drag.start.x, a.y - drag.start.y) < Math.hypot(best.x - drag.start.x, best.y - drag.start.y))) best = { x: a.x, y: a.y };\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** A shape's dragged corner moved so its width or height matches another object's, when one is within reach. */\n\tprivate matchShapeSize(targets: VectorSnapTargets, start: Vec2, end: Vec2, fromCentre = false): Vec2 {\n\t\t// Dragged from the centre, the shape is twice as large as the drag.\n\t\tconst k = fromCentre ? 2 : 1;\n\t\tconst tol = this.snapTolerance() * k;\n\t\tconst out = { ...end };\n\t\tconst guides: VectorSnapGuides = { lines: [], labels: [] };\n\t\tfor (const axis of ['x', 'y'] as const) {\n\t\t\tconst d = end[axis] - start[axis];\n\t\t\tconst len = Math.abs(d) > 1e-9 ? targets.matchSize(Math.abs(d) * k, tol) : null;\n\t\t\tif (len === null || len <= 0) continue;\n\t\t\tout[axis] = start[axis] + (Math.sign(d) * len) / k;\n\t\t\tconst from = { ...out, [axis]: fromCentre ? 2 * start[axis] - out[axis] : start[axis] };\n\t\t\tguides.lines.push({ kind: 'size', x1: from.x, y1: from.y, x2: out.x, y2: out.y });\n\t\t\tguides.labels.push({ kind: 'size', x: (from.x + out.x) / 2, y: (from.y + out.y) / 2, text: `${axis === 'x' ? 'W' : 'H'} ${Math.round(len * 100) / 100}` });\n\t\t}\n\t\tthis.setGuides(guides);\n\t\treturn out;\n\t}\n\n\t/** Primary button released. */\n\tpointerUp(screen?: Vec2, input: VectorPointerInput = {}): void {\n\t\t// A pen reports no pressure as it lifts: keep the last pressure for the final move.\n\t\tif (screen && this.drag && this.drag.kind !== 'pan') this.pointerMove(screen, { ...input, pressure: undefined });\n\t\tconst drag = this.drag;\n\t\tthis.drag = null;\n\t\tthis.interaction = null;\n\t\tthis.guides = null;\n\t\tif (!drag) return;\n\t\tswitch (drag.kind) {\n\t\t\tcase 'pan':\n\t\t\tcase 'marquee':\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tcase 'move':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tif (drag.clickId) this.selection = [drag.clickId];\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit(drag.duplicated ? 'Duplicate' : 'Move', drag.before);\n\t\t\tcase 'scale':\n\t\t\t\treturn this.commit(drag.op ?? 'Scale', drag.before);\n\t\t\tcase 'envelope':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit('Edit Envelope', drag.before);\n\t\t\tcase 'rotate':\n\t\t\t\treturn this.commit('Rotate', drag.before);\n\t\t\tcase 'anchors':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tif (drag.clickRef) this.anchors = [drag.clickRef];\n\t\t\t\t\tif (drag.before.doc !== this.doc) return this.commit('Add Point', drag.before);\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit(drag.before.doc !== drag.base ? 'Add Point' : 'Move Points', drag.before);\n\t\t\tcase 'handle':\n\t\t\t\treturn this.commit('Move Handle', drag.before);\n\t\t\tcase 'bend':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit('Bend Segment', drag.before);\n\t\t\tcase 'corner': {\n\t\t\t\tif (drag.moved) return this.commit('Corner Radius', drag.before);\n\t\t\t\tif (drag.alt) {\n\t\t\t\t\tconst kind = nextVectorCornerKind(drag.widget.kind);\n\t\t\t\t\tthis.doc = this.updateAnchors(drag.base, drag.refs, (a) => setAnchorCorner(a, a.corner?.radius ?? 0, kind));\n\t\t\t\t\treturn this.commit('Corner Kind', drag.before);\n\t\t\t\t}\n\t\t\t\t// A click selects the widget's corner, so the next drag rounds that corner alone.\n\t\t\t\tconst ref = drag.widget.ref;\n\t\t\t\tconst has = this.anchors.some((a) => sameRef(a, ref));\n\t\t\t\tthis.editingId = ref.nodeId;\n\t\t\t\tthis.anchors = drag.shift ? (has ? this.anchors.filter((a) => !sameRef(a, ref)) : [...this.anchors, ref]) : [ref];\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tif (drag.moved) {\n\t\t\t\t\tconst several = drag.group.length > 0;\n\t\t\t\t\tif (drag.mode === 'copy') this.widthPoints = [drag.ref];\n\t\t\t\t\telse if (drag.mode === 'move' && several) {\n\t\t\t\t\t\t// Points moved together stay selected (re-sorting may renumber them).\n\t\t\t\t\t\tthis.widthPoints = [drag.source, ...drag.group].map((i) => ({ ...drag.ref, index: drag.renumber?.get(i) ?? i }));\n\t\t\t\t\t} else if (!several) this.widthPoints = [drag.ref];\n\t\t\t\t\tconst label = drag.mode === 'copy' ? 'Copy Width Point' : drag.mode === 'move' ? (several ? 'Move Width Points' : 'Move Width Point') : several ? 'Width Points' : 'Width Point';\n\t\t\t\t\treturn this.commit(label, drag.before);\n\t\t\t\t}\n\t\t\t\t// A click adds nothing; on a width point it selects it (just it, among several selected).\n\t\t\t\tif (drag.created) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.widthPoints = [];\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t} else {\n\t\t\t\t\tif (!drag.shift && drag.group.length) this.widthPoints = [drag.ref];\n\t\t\t\t\tthis.notify();\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'builder':\n\t\t\t\treturn this.upBuilder(drag);\n\t\t\tcase 'gradient':\n\t\t\t\treturn this.upGradient(drag);\n\t\t\tcase 'stroke': {\n\t\t\t\tthis.notify();\n\t\t\t\tif (drag.tool === 'knife') this.knife(drag.points);\n\t\t\t\telse this.erase(drag.points);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pull':\n\t\t\t\tif (drag.closing) this.pen = null;\n\t\t\t\treturn this.commit(drag.label, drag.before);\n\t\t\tcase 'shape': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tconst b = node ? vectorNodeBounds(node) : null;\n\t\t\t\tconst min = 2 / this.viewport.zoom;\n\t\t\t\tif (!b || (b.width < min && b.height < min)) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\tthis.anchors = [];\n\t\t\t\tthis.tool = 'select';\n\t\t\t\treturn this.commit(`Draw ${TOOL_LABELS[drag.tool]}`, drag.before);\n\t\t\t}\n\t\t\tcase 'pencil': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path' || drag.points.length < 2) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor (const q of drag.lazy.finish()) {\n\t\t\t\t\tdrag.points.push(q);\n\t\t\t\t\tdrag.pressures?.push(drag.pressure);\n\t\t\t\t}\n\t\t\t\tconst shape = this.editing.recognizeShapes ? recognizeInkShape(drag.points, { minSize: 6 / this.viewport.zoom }) : null;\n\t\t\t\tif (shape) {\n\t\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, name: inkShapeLabel(shape), subpaths: [inkShapeSubpath(shape)] });\n\t\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\t\treturn this.commit(`Draw ${inkShapeLabel(shape)}`, drag.before);\n\t\t\t\t}\n\t\t\t\tconst fitted = fitCubics(drag.points, 1.5 / this.viewport.zoom, { cornerAngleDeg: 60 });\n\t\t\t\tconst anchors: VectorAnchor[] = [];\n\t\t\t\tfor (const c of fitted) {\n\t\t\t\t\tif (!anchors.length) anchors.push({ x: c.p0[0], y: c.p0[1] });\n\t\t\t\t\tanchors[anchors.length - 1].out = { x: c.p1[0], y: c.p1[1] };\n\t\t\t\t\tanchors.push({ x: c.p3[0], y: c.p3[1], in: { x: c.p2[0], y: c.p2[1] } });\n\t\t\t\t}\n\t\t\t\tconst subpaths = anchors.length > 1 ? bezierToSubpaths(subpathsToBezier([{ anchors, closed: false }])) : node.subpaths;\n\t\t\t\tconst profile = drag.pressures ? pencilPressureProfile(drag.points, drag.pressures) : [];\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths, ...(profile.length ? { strokeWidthProfile: profile } : {}) });\n\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\treturn this.commit('Draw', drag.before);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The pointer left the canvas. */\n\tpointerLeave(): void {\n\t\tif (this.drag) return;\n\t\tif (!this.hover && !this.pointer && !this.guides) return;\n\t\tthis.hover = null;\n\t\tthis.pointer = null;\n\t\tthis.guides = null;\n\t\tthis.notify();\n\t}\n\n\t/** Abandons the drag in progress (Escape, lost capture). */\n\tcancelDrag(): void {\n\t\tconst drag = this.drag;\n\t\tif (!drag) return;\n\t\tthis.drag = null;\n\t\tthis.interaction = null;\n\t\tthis.guides = null;\n\t\tif (drag.kind === 'pan' || drag.kind === 'builder') {\n\t\t\tif (drag.kind === 'builder') this.builderPreview = null;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (drag.kind === 'marquee') {\n\t\t\tthis.selection = drag.base;\n\t\t\tthis.anchors = drag.baseAnchors;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.restore(drag.before);\n\t}\n\n\t/**\n\t * Double click: select tool enters path editing, direct tool toggles an anchor or adds one,\n\t * width tool opens the width-point editor (`widthPointEdit`).\n\t */\n\tdoubleClick(screen: Vec2): void {\n\t\tconst p = this.screenToDocument(screen);\n\t\tif (this.tool === 'select') {\n\t\t\tconst path = this.hitPath(p);\n\t\t\tif (!path) return;\n\t\t\tthis.tool = 'direct';\n\t\t\tthis.selection = [path.id];\n\t\t\tthis.editingId = path.id;\n\t\t\tthis.anchors = [];\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'direct') {\n\t\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\t\tif (anchor) {\n\t\t\t\tconst a = getAnchor(this.doc, anchor)!;\n\t\t\t\tthis.convertAnchors(a.in || a.out ? 'corner' : 'smooth', [anchor]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.hover?.segment?.nodeId ?? this.editingId;\n\t\t\tif (id) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode | undefined;\n\t\t\t\tconst seg = node ? nearestSegment(node, this.toLocal(id, p)) : null;\n\t\t\t\tif (seg && seg.distance <= this.tolerance()) this.insertAnchorAt(id, p);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'width') {\n\t\t\t// Width Point Edit: on a width point, or on a stroke (applying it adds a point there).\n\t\t\tconst hit = this.hitWidthHandle(screen);\n\t\t\tif (hit) {\n\t\t\t\tthis.openWidthPointEdit(hit.ref);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst spot = this.strokeSpotAt(p);\n\t\t\tif (spot) this.openWidthPointEdit({ nodeId: spot.nodeId, subpath: spot.subpath, t: spot.t });\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'pen') this.finishPath();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Keyboard input\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Handles editor shortcuts. Returns true when the key was used (call `preventDefault`).\n\t * Do not forward keys typed into text inputs.\n\t */\n\tkeyDown(input: VectorKeyInput): boolean {\n\t\tconst key = input.key;\n\t\tconst lower = key.length === 1 ? key.toLowerCase() : key;\n\t\tif (key === ' ') {\n\t\t\tif (!this.spaceHeld) {\n\t\t\t\tthis.spaceHeld = true;\n\t\t\t\tthis.notify();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (input.mod) {\n\t\t\tswitch (lower) {\n\t\t\t\tcase 'z':\n\t\t\t\t\tinput.shift ? this.redo() : this.undo();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'y':\n\t\t\t\t\tthis.redo();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'a':\n\t\t\t\t\tthis.selectAll();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'd':\n\t\t\t\t\tthis.duplicate();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'g':\n\t\t\t\t\tinput.shift ? this.ungroup() : this.group();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'j':\n\t\t\t\t\treturn input.alt ? this.averageAnchors('both').ok : this.joinPaths().ok;\n\t\t\t\tcase ']':\n\t\t\t\t\tthis.arrange(input.alt ? 'front' : 'forward');\n\t\t\t\t\treturn true;\n\t\t\t\tcase '[':\n\t\t\t\t\tthis.arrange(input.alt ? 'back' : 'backward');\n\t\t\t\t\treturn true;\n\t\t\t\tcase '=':\n\t\t\t\tcase '+':\n\t\t\t\t\tthis.setViewport({ zoom: this.viewport.zoom * 1.25 });\n\t\t\t\t\treturn true;\n\t\t\t\tcase '-':\n\t\t\t\t\tthis.setViewport({ zoom: this.viewport.zoom / 1.25 });\n\t\t\t\t\treturn true;\n\t\t\t\tcase '0':\n\t\t\t\t\tthis.setViewport({ zoom: 1 });\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tswitch (key) {\n\t\t\tcase 'Escape':\n\t\t\t\tif (this.drag) this.cancelDrag();\n\t\t\t\telse if (this.widthEdit) this.closeWidthPointEdit();\n\t\t\t\telse if (this.tool === 'width' && this.widthPoints.length) {\n\t\t\t\t\tthis.widthPoints = [];\n\t\t\t\t\tthis.notify();\n\t\t\t\t}\n\t\t\t\telse if (this.pen) this.finishPath();\n\t\t\t\telse if (this.blendStart) {\n\t\t\t\t\tthis.blendStart = null;\n\t\t\t\t\tthis.notify();\n\t\t\t\t} else if (this.tool === 'direct' && this.anchors.length) {\n\t\t\t\t\tthis.anchors = [];\n\t\t\t\t\tthis.notify();\n\t\t\t\t} else if (this.tool !== 'select') this.setTool('select');\n\t\t\t\telse this.clearSelection();\n\t\t\t\treturn true;\n\t\t\tcase 'Enter':\n\t\t\t\tif (this.pen) {\n\t\t\t\t\tthis.finishPath();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (this.tool === 'select' && this.selection.length === 1 && this.getNode(this.selection[0])?.type === 'path') {\n\t\t\t\t\tthis.tool = 'direct';\n\t\t\t\t\tthis.editingId = this.selection[0];\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\tcase 'Delete':\n\t\t\tcase 'Backspace':\n\t\t\t\tif (this.tool === 'width' && this.widthPoints.length) return this.removeWidthPoints().ok;\n\t\t\t\tif (this.tool === 'gradient' && this.gradientEdit.stop !== null) return this.removeGradientStop(this.gradientEdit.stop).ok;\n\t\t\t\tif (this.pen) {\n\t\t\t\t\tconst node = this.getNode(this.pen.nodeId) as VectorPathNode;\n\t\t\t\t\tconst sp = node.subpaths[this.pen.subpath];\n\t\t\t\t\tif (sp.anchors.length > 2) this.deleteAnchors([{ nodeId: node.id, subpath: this.pen.subpath, index: sp.anchors.length - 1 }]);\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.removeNodes([node.id], { label: 'Delete Path' });\n\t\t\t\t\t\tthis.pen = null;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn this.deleteSelection().ok;\n\t\t\tcase 'ArrowLeft':\n\t\t\tcase 'ArrowRight':\n\t\t\tcase 'ArrowUp':\n\t\t\tcase 'ArrowDown': {\n\t\t\t\tconst step = input.shift ? 10 : 1;\n\t\t\t\tconst dx = key === 'ArrowLeft' ? -step : key === 'ArrowRight' ? step : 0;\n\t\t\t\tconst dy = key === 'ArrowUp' ? -step : key === 'ArrowDown' ? step : 0;\n\t\t\t\treturn this.translate(dx, dy).ok;\n\t\t\t}\n\t\t}\n\t\tif (key.length === 1 && !input.alt) {\n\t\t\tconst tool = TOOL_KEYS[lower];\n\t\t\tif (tool) {\n\t\t\t\tthis.setTool(tool);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tkeyUp(input: VectorKeyInput): void {\n\t\tif (input.key === ' ' && this.spaceHeld) {\n\t\t\tthis.spaceHeld = false;\n\t\t\tthis.notify();\n\t\t}\n\t}\n}\n\n/** \"Rectangle\", \"Square\", \"Ellipse\", \"Circle\", \"Line\", \"Triangle\" or \"Polygon\". */\nfunction inkShapeLabel(shape: VectorInkShape): string {\n\tconst name = vectorInkShapeName(shape);\n\treturn name[0].toUpperCase() + name.slice(1);\n}\n\n/** The subpath of a recognised pencil shape. */\nfunction inkShapeSubpath(shape: VectorInkShape): VectorSubpath {\n\tswitch (shape.kind) {\n\t\tcase 'line':\n\t\t\treturn lineSubpath({ x: shape.a[0], y: shape.a[1] }, { x: shape.b[0], y: shape.b[1] });\n\t\tcase 'rect':\n\t\t\treturn rectSubpath(shape);\n\t\tcase 'ellipse':\n\t\t\treturn ellipseSubpath(shape);\n\t\tcase 'polygon':\n\t\t\treturn { anchors: shape.points.map(([x, y]) => ({ x, y })), closed: true };\n\t}\n}\n\n/** Snaps `p` to the nearest 45° direction from `origin`, keeping its distance. */\nfunction constrain45(origin: Vec2, p: Vec2): Vec2 {\n\tconst dx = p.x - origin.x;\n\tconst dy = p.y - origin.y;\n\tconst len = Math.hypot(dx, dy);\n\tconst a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);\n\treturn { x: origin.x + Math.cos(a) * len, y: origin.y + Math.sin(a) * len };\n}\n\n/** Scale factors and origin for dragging a selection-box handle to `p`. */\nexport function scaleFor(handle: VectorTransformHandle, b: VectorBounds, p: Vec2, mods: VectorModifiers = {}): { sx: number; sy: number; origin: Vec2 } {\n\tconst west = handle.includes('w');\n\tconst east = handle.includes('e');\n\tconst north = handle.startsWith('n');\n\tconst south = handle.startsWith('s');\n\tconst center = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\tconst origin = mods.alt ? center : { x: west ? b.x + b.width : east ? b.x : center.x, y: north ? b.y + b.height : south ? b.y : center.y };\n\tconst reachX = mods.alt ? b.width / 2 : b.width;\n\tconst reachY = mods.alt ? b.height / 2 : b.height;\n\tlet sx = west || east ? (reachX > 1e-9 ? ((p.x - origin.x) * (west ? -1 : 1)) / reachX : 1) : 1;\n\tlet sy = north || south ? (reachY > 1e-9 ? ((p.y - origin.y) * (north ? -1 : 1)) / reachY : 1) : 1;\n\tif (mods.shift) {\n\t\tif ((west || east) && (north || south)) {\n\t\t\tconst s = Math.max(Math.abs(sx), Math.abs(sy));\n\t\t\tsx = Math.sign(sx || 1) * s;\n\t\t\tsy = Math.sign(sy || 1) * s;\n\t\t} else if (west || east) sy = Math.abs(sx);\n\t\telse sx = Math.abs(sy);\n\t}\n\treturn { sx, sy, origin };\n}\n\n/** A style applied to a path; a `null` (or empty) width profile removes it. */\nfunction withStyle(node: VectorPathNode, style: VectorStyle & { opacity?: number }): VectorNode {\n\tconst next = { ...node, ...style } as VectorPathNode;\n\tif ('strokeWidthProfile' in style) {\n\t\tconst p = style.strokeWidthProfile ? sanitizeWidthProfile(style.strokeWidthProfile) : [];\n\t\tif (p.length) next.strokeWidthProfile = p;\n\t\telse delete next.strokeWidthProfile;\n\t}\n\treturn next;\n}\n\n/** True when node `id` or one of its ancestors is locked or hidden. */\nfunction hiddenOrLocked(nodes: readonly VectorNode[], id: string): boolean {\n\tconst loc = locateVectorNode(nodes as VectorNode[], id);\n\tif (!loc) return false;\n\tconst n = loc.list[loc.index];\n\tif (n.locked || n.visible === false) return true;\n\treturn loc.parent ? hiddenOrLocked(nodes, loc.parent.id) : false;\n}\n\n/** The width profile of pencil samples and their pressures (positions by length along the samples). */\nfunction pencilPressureProfile(points: readonly Point[], pressures: readonly number[]): VectorWidthPoint[] {\n\tconst n = Math.min(points.length, pressures.length);\n\tif (n < 2) return [];\n\tconst s = [0];\n\tfor (let i = 1; i < n; i++) s.push(s[i - 1] + Math.hypot(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]));\n\tconst total = s[n - 1];\n\tif (!(total > 0)) return [];\n\treturn pressureWidthProfile(s.map((d, i) => ({ t: d / total, pressure: pressures[i] })));\n}\n","/**\n * Framework-neutral render data for a vector editor: the scene (document-space SVG paths and\n * gradient defs) and the overlay (screen-space selection box, anchors, handles, marquee and\n * pen preview). React, Svelte or plain DOM code turns these into `<svg>` elements.\n */\nimport { bezierPathToSvg, transformBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { hatchPath } from '../canvas/pathops/hatch.js';\nimport type { SvgGradientDef } from '../canvas/gradient.js';\nimport { expandVectorGradientStops, isCentredVectorGradient, isVectorGradient, parseVectorColor, sortedVectorGradientStops, type VectorGradientHandle, type VectorPaintDef } from './gradient.js';\nimport { getVectorGradientAnnotator, VECTOR_GRADIENT_STOP_GAP } from './gradientTool.js';\n\nexport type { SvgGradientDef };\nimport {\n\tgetAnchorWorld,\n\tgetVectorCornerWidgets,\n\tgetVectorEnvelopeTarget,\n\tgetVectorSelectionBoxGeometry,\n\tgetVectorWidthHandles,\n\tgetVisibleAnchors,\n\tgetVisibleHandles,\n\ttype VectorEditorController,\n\ttype VectorEditorState,\n\ttype VectorSelectionBoxGeometry,\n\ttype VectorWidthPointRef\n} from './controller.js';\nimport { sanitizeWidthProfile, widthProfilePresetId, type VectorWidthPreset } from './width.js';\nimport {\n\tfindVectorNode,\n\twalkVectorNodes,\n\tlocateVectorNode,\n\tsubpathsToBezier,\n\tvectorWorldMatrix,\n\tIDENTITY_MATRIX,\n\tinferAnchorType,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\tvectorNodeBounds,\n\tvectorParentMatrix,\n\tvectorPathData,\n\tvectorPathWorldBezier,\n\ttype AffineMatrix\n} from './geometry.js';\nimport { vectorPaintToSvg, vectorStrokeSvgParts, type VectorRenderStrokeParts } from './svg.js';\nimport { vectorCorners } from './corners.js';\nimport {\n\texpandVectorAppearance,\n\thasOwnVectorAppearance,\n\thasVectorAppearance,\n\tvectorAppearanceOutline,\n\tvectorEnteredGroups,\n\tVECTOR_EFFECT_LABELS,\n\tVECTOR_EFFECT_PARAM_SPECS,\n\ttype VectorEffectParamSpec,\n\ttype VectorEnvelopeParams\n} from './appearance.js';\nimport { vectorMeshEditPoints, vectorMeshGridCurves, VECTOR_WARP_STYLES, VECTOR_WARP_STYLE_LABELS } from './warp.js';\nimport { VECTOR_EFFECT_TYPES, type VectorEffectType } from './types.js';\nimport { isVectorBlendGroup, resolveVectorBlendOptions, vectorBlendRailAt, vectorBlendSpine } from './blendGroup.js';\nimport type { VectorGuideKind, VectorSnapKind } from './snap.js';\nimport type {\n\tVectorAnchorRef,\n\tVectorAnchorType,\n\tVectorArrowAlign,\n\tVectorArrowhead,\n\tVectorBlendOptions,\n\tVectorBlendSpacing,\n\tVectorBounds,\n\tVectorCornerKind,\n\tVectorGradient,\n\tVectorGradientInterpolation,\n\tVectorGradientSpread,\n\tVectorGradientStop,\n\tVectorGradientType,\n\tVectorStrokeGradientMode,\n\tVectorGroupNode,\n\tVectorHandleRef,\n\tVectorNode,\n\tVectorPaint,\n\tVectorPathfinderOperation,\n\tVectorPathNode,\n\tVectorStrokeAlign,\n\tVectorTransformHandle,\n\tVectorWidthPoint,\n\tVec2\n} from './types.js';\n\nexport interface VectorRenderPath {\n\tkind: 'path';\n\tid: string;\n\t/** SVG `transform` (`matrix(…)`) for a rotated node. */\n\ttransform?: string;\n\td: string;\n\t/** `none`, a colour, or `url(#id)` of a gradient in `defs`. */\n\tfill: string;\n\tstroke: string;\n\tstrokeWidth: number;\n\tstrokeLinecap?: string;\n\tstrokeLinejoin?: string;\n\tstrokeDasharray?: string;\n\tfillRule: 'nonzero' | 'evenodd';\n\topacity: number;\n\t/**\n\t * Set when the stroke takes more than one element: an inside / outside alignment or\n\t * arrowheads. Draw `d` with the fill only, then `stroke.d` with the stroke (at\n\t * `stroke.width`, clipped or masked as `stroke.clip` says), then each head filled with\n\t * `stroke`; group them under `id`, `transform` and `opacity`.\n\t */\n\tstrokeParts?: VectorRenderStrokeParts;\n}\n\nexport interface VectorRenderGroup {\n\tkind: 'group';\n\tid: string;\n\t/** SVG `transform` (`matrix(…)`) for a rotated group. */\n\ttransform?: string;\n\topacity: number;\n\tchildren: VectorRenderNode[];\n}\n\nexport type VectorRenderNode = VectorRenderPath | VectorRenderGroup;\n\nexport interface VectorSceneRenderData {\n\t/** SVG `transform` for the document layer: `translate(x y) scale(zoom)`. */\n\ttransform: string;\n\twidth: number;\n\theight: number;\n\tbackground?: string;\n\t/**\n\t * Paint servers referenced by `fill` / `stroke` values: `<linearGradient>` /\n\t * `<radialGradient>` descriptors and `pattern`s (conic, diamond and stroke-mode gradients:\n\t * draw each of `gradients`, then each tile filled, inside a `<pattern>`).\n\t */\n\tdefs: VectorPaintDef[];\n\t/** Visible nodes, bottom to top. */\n\tnodes: VectorRenderNode[];\n}\n\nexport interface VectorRenderAnchor {\n\tref: VectorAnchorRef;\n\t/** Screen position. */\n\tx: number;\n\ty: number;\n\ttype: VectorAnchorType;\n\tselected: boolean;\n\thovered: boolean;\n\t/** The pen tool closes the path when this anchor is clicked. */\n\tcloses: boolean;\n}\n\nexport interface VectorRenderHandle {\n\tref: VectorHandleRef;\n\tx: number;\n\ty: number;\n\t/** Screen position of the handle's anchor (draw a line to it). */\n\tanchorX: number;\n\tanchorY: number;\n\thovered: boolean;\n}\n\n/** A live corner widget in screen pixels. */\nexport interface VectorRenderCornerWidget {\n\tref: VectorAnchorRef;\n\tx: number;\n\ty: number;\n\tradius: number;\n\tkind: VectorCornerKind;\n\thovered: boolean;\n\t/** Its corners are being dragged. */\n\tactive: boolean;\n}\n\n/**\n * A width point of the width tool in screen pixels: a diamond at (`x`, `y`) on the path and a\n * line across the stroke from `left` to `right`, with a handle at each end.\n */\nexport interface VectorRenderWidthPoint {\n\tref: VectorWidthPointRef;\n\tx: number;\n\ty: number;\n\tleft: Vec2;\n\tright: Vec2;\n\tselected: boolean;\n\t/** The part under the pointer, if any. */\n\thovered: 'center' | 'left' | 'right' | null;\n\t/** Being dragged. */\n\tactive: boolean;\n}\n\n/** A smart guide line in screen pixels. */\nexport interface VectorRenderGuideLine {\n\tkind: VectorGuideKind;\n\tx1: number;\n\ty1: number;\n\tx2: number;\n\ty2: number;\n}\n\n/** A smart guide label (\"anchor\", \"intersect\", \"align\", \"centre\", a gap or a size) at a screen position. */\nexport interface VectorRenderGuideLabel {\n\tkind: VectorSnapKind;\n\tx: number;\n\ty: number;\n\ttext: string;\n}\n\nexport interface VectorOverlayRenderData {\n\t/** Outlines (screen-space path data) of hovered and selected nodes. */\n\toutlines: { id: string; d: string; selected: boolean }[];\n\t/**\n\t * Selection box with resize and rotate handles (select tool). `x / y / width / height` and\n\t * each handle's `x / y` are the unrotated box in screen pixels: draw them inside\n\t * `<g transform={transform}>`. `corners` and each handle's `screen` are true positions.\n\t */\n\tselectionBox:\n\t\t| (VectorBounds & { angle: number; transform: string; corners: Vec2[]; handles: VectorSelectionBoxGeometry['handles']; freeDistort: boolean })\n\t\t| null;\n\t/**\n\t * A Free Distort drag (screen space): the quad the selection box's corners make so far (`d`,\n\t * closed path data) and its corners clockwise from the top left. The box is hidden meanwhile.\n\t */\n\tdistort: { mode: 'distort' | 'perspective' | 'skew'; d: string; corners: Vec2[] } | null;\n\t/**\n\t * The Envelope tool's mesh of the selected envelope (screen space): `grid` is the grid lines as\n\t * path data, `anchors` the points where they cross and `handles` the handles along them, each\n\t * with the anchor it belongs to (`index` is the point's index in the mesh). Draw anchors as\n\t * squares and handles as dots joined to their anchors.\n\t */\n\tenvelope: {\n\t\tnodeId: string;\n\t\tgrid: string;\n\t\tanchors: { index: number; x: number; y: number; hovered: boolean; active: boolean }[];\n\t\thandles: { index: number; x: number; y: number; anchorX: number; anchorY: number; hovered: boolean; active: boolean }[];\n\t} | null;\n\tanchors: VectorRenderAnchor[];\n\thandles: VectorRenderHandle[];\n\t/** Marquee rectangle, screen space. */\n\tmarquee: VectorBounds | null;\n\t/** Rubber-band segment from the pen path's last anchor to the pointer, screen space. */\n\tpenPreview: string | null;\n\t/** Artboard rectangle, screen space. */\n\tartboard: VectorBounds;\n\t/** Smart guides of the snap in progress, screen space (empty when nothing snapped). */\n\tguides: { lines: VectorRenderGuideLine[]; labels: VectorRenderGuideLabel[] };\n\t/**\n\t * The knife or eraser stroke being drawn, screen space: `d` is an open polyline; draw the\n\t * eraser's with a round-capped stroke `width` pixels wide (0 for the knife: a thin line).\n\t */\n\ttoolStroke: { tool: 'knife' | 'eraser'; d: string; width: number } | null;\n\t/** The pencil's lazy-mouse string from the pen to the pointer, screen space. */\n\tpencilString: { x1: number; y1: number; x2: number; y2: number } | null;\n\t/** Where the scissors would cut (screen space). */\n\tcutPoint: Vec2 | null;\n\t/**\n\t * Live corner widgets of the direct tool (screen space): drag one to round its corners,\n\t * Alt-click to cycle round / inverted / chamfer, click to pick its corner alone.\n\t */\n\tcornerWidgets: VectorRenderCornerWidget[];\n\t/** Width points of the width tool (screen space). */\n\twidthPoints: VectorRenderWidthPoint[];\n\t/**\n\t * Where a width-tool drag would add a width point (screen space): draw a dashed line from\n\t * `left` to `right` and a hollow diamond at (`x`, `y`).\n\t */\n\twidthSpot: { x: number; y: number; left: Vec2; right: Vec2 } | null;\n\t/**\n\t * Shape Builder and paint bucket highlight (screen space): `faces` are filled paths (fill\n\t * them translucent and outline them), `hatches` the 45° hatch lines over each face\n\t * (`hatchPath`, a few pixels apart; merge and erase only, empty strings for the paint\n\t * bucket: stroke them over the translucent fill), `lines` are the line pieces and outline\n\t * edges an erase deletes, `trail` is the drag's polyline. `mode` is `merge`, `erase` (Alt)\n\t * or `fill` (paint bucket).\n\t */\n\tbuilder: { mode: 'merge' | 'erase' | 'fill'; faces: string[]; hatches: string[]; lines: string[]; trail: string | null } | null;\n\t/**\n\t * Blends (screen space): the spine of each selected blend (`d`, draw it dashed; `keys` are\n\t * where its keys sit on it; `replaced` when it is a replaced spine) and, with the Blend tool,\n\t * the outline of the shape it blends from (`start`, with the clicked anchor) and the anchors\n\t * of the first subpath under the pointer (click one to start the blend there).\n\t */\n\tblend: {\n\t\tspines: { id: string; d: string; keys: Vec2[]; replaced: boolean }[];\n\t\tstart: { d: string; anchor: Vec2 | null } | null;\n\t\tanchors: { x: number; y: number; hovered: boolean }[];\n\t};\n\t/** The gradient tool's annotator over the selection's gradient (screen space), or null. */\n\tgradient: VectorRenderGradientAnnotator | null;\n\t/** A short status, e.g. \"W 120 × H 80\" or \"45°\". */\n\tstatus: string | null;\n}\n\n/**\n * The gradient annotator in screen pixels: draw the `extent` outline (dashed), the bar from\n * `start` to `end`, the handles, each stop's chip (a swatch at `x, y` with a tick to `barX, barY`;\n * `removing`: the dragged stop is off the bar and will be deleted, draw it faded) and the\n * midpoint diamonds.\n */\nexport interface VectorRenderGradientAnnotator {\n\tnodeId: string;\n\ttype: VectorGradientType;\n\tstart: { x: number; y: number; hovered: boolean };\n\t/** `radius` for radial, conic and diamond gradients. */\n\tend: { x: number; y: number; hovered: boolean; handle: 'end' | 'radius' };\n\taspect: { x: number; y: number; hovered: boolean } | null;\n\tfocal: { x: number; y: number; hovered: boolean } | null;\n\tstops: { index: number; x: number; y: number; barX: number; barY: number; color: string; opacity: number; selected: boolean; hovered: boolean }[];\n\tmidpoints: { index: number; x: number; y: number; hovered: boolean }[];\n\textent: string | null;\n\tremoving: boolean;\n}\n\nconst fmt = (n: number) => Math.round(n * 100) / 100;\nconst fmtMatrix = (m: AffineMatrix) => `matrix(${m.map((n) => Math.round(n * 1e6) / 1e6).join(' ')})`;\n/** Distance between the Shape Builder's hatch lines over a face (screen pixels). */\nexport const VECTOR_BUILDER_HATCH_GAP = 6;\n\nfunction renderNode(stored: VectorNode, defs: VectorPaintDef[], idPrefix: string): VectorRenderNode | null {\n\tif (stored.visible === false) return null;\n\t// Path effects and live booleans draw as their expanded shapes.\n\tconst node = expandVectorAppearance(stored);\n\tif (node.type === 'group') {\n\t\tconst children = node.children.map((c) => renderNode(c, defs, idPrefix)).filter((c): c is VectorRenderNode => !!c);\n\t\treturn { kind: 'group', id: node.id, ...(node.transform ? { transform: fmtMatrix(node.transform) } : {}), opacity: node.opacity ?? 1, children };\n\t}\n\tconst fill = vectorPaintToSvg(node.fill, `${idPrefix}fill-${node.id}`, { node });\n\tconst stroke = vectorPaintToSvg(node.stroke, `${idPrefix}stroke-${node.id}`, { node, role: 'stroke' });\n\tdefs.push(...fill.defs, ...stroke.defs);\n\tconst strokeParts = stroke.value !== 'none' ? vectorStrokeSvgParts(node, `${idPrefix}clip-${node.id}`) : undefined;\n\treturn {\n\t\tkind: 'path',\n\t\tid: node.id,\n\t\t...(node.transform ? { transform: fmtMatrix(node.transform) } : {}),\n\t\t...(strokeParts ? { strokeParts } : {}),\n\t\td: vectorPathData(node),\n\t\tfill: fill.value,\n\t\tstroke: stroke.value,\n\t\tstrokeWidth: node.strokeWidth ?? 1,\n\t\t...(node.strokeLinecap ? { strokeLinecap: node.strokeLinecap } : {}),\n\t\t...(node.strokeLinejoin ? { strokeLinejoin: node.strokeLinejoin } : {}),\n\t\t...(node.strokeDasharray?.length ? { strokeDasharray: node.strokeDasharray.join(' ') } : {}),\n\t\tfillRule: node.fillRule ?? 'nonzero',\n\t\topacity: node.opacity ?? 1\n\t};\n}\n\n/**\n * The document layer. Render the nodes inside `<g transform={transform}>` and `defs` in a\n * `<defs>` block. Pass a unique `idPrefix` when several editors share a page.\n */\nexport function getVectorSceneRenderData(state: Pick<VectorEditorState, 'document' | 'viewport'>, options: { idPrefix?: string } = {}): VectorSceneRenderData {\n\tconst defs: VectorPaintDef[] = [];\n\tconst prefix = options.idPrefix ?? 've-';\n\tconst nodes = state.document.nodes.map((n) => renderNode(n, defs, prefix)).filter((n): n is VectorRenderNode => !!n);\n\tconst v = state.viewport;\n\treturn {\n\t\ttransform: `translate(${fmt(v.x)} ${fmt(v.y)}) scale(${v.zoom})`,\n\t\twidth: state.document.width,\n\t\theight: state.document.height,\n\t\t...(state.document.background ? { background: state.document.background } : {}),\n\t\tdefs,\n\t\tnodes\n\t};\n}\n\nconst toScreen = (state: Pick<VectorEditorState, 'viewport'>, p: Vec2) => ({ x: p.x * state.viewport.zoom + state.viewport.x, y: p.y * state.viewport.zoom + state.viewport.y });\n\nfunction screenOutline(state: VectorEditorState, node: VectorNode, entered: ReadonlySet<string>): string {\n\tconst v = state.viewport;\n\tconst view: AffineMatrix = [v.zoom, 0, 0, v.zoom, v.x, v.y];\n\tconst parent = vectorParentMatrix(state.document.nodes, node.id) ?? IDENTITY_MATRIX;\n\treturn outlinePaths(node, parent, entered)\n\t\t.map((path) => bezierPathToSvg(transformBezierPath(path, view), { precision: 2 }))\n\t\t.join(' ');\n}\n\n/**\n * Document-space outlines of a subtree: paths as stored (their anchors are what is edited; the\n * scene shows their effects), live groups as drawn unless they are being edited (then their\n * children, as figcraft outlines a boolean group's operands).\n */\nfunction outlinePaths(node: VectorNode, parent: AffineMatrix, entered: ReadonlySet<string>): BezierPath[] {\n\tif (node.type === 'path') return [vectorPathWorldBezier(node, parent, { effects: false })];\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\tif (hasOwnVectorAppearance(node) && !entered.has(node.id)) return [transformBezierPath(vectorAppearanceOutline(node), m)];\n\treturn node.children.filter((c) => c.visible !== false).flatMap((c) => outlinePaths(c, m, entered));\n}\n\n/** Live groups being edited in `state` (see `vectorEnteredGroups`). */\nexport function getVectorEnteredGroups(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId'>): Set<string> {\n\treturn vectorEnteredGroups(state.document.nodes, state.editingId ? [...state.selection, state.editingId] : state.selection);\n}\n\nfunction collect(node: VectorNode): VectorPathNode[] {\n\tif (node.type === 'path') return [node];\n\treturn node.children.flatMap(collect);\n}\n\n/** The editing overlay in screen pixels. Render it on top of the scene, untransformed. */\nexport function getVectorOverlayRenderData(state: VectorEditorState): VectorOverlayRenderData {\n\tconst doc = state.document;\n\tconst z = state.viewport.zoom;\n\tconst outlines: VectorOverlayRenderData['outlines'] = [];\n\tconst entered = getVectorEnteredGroups(state);\n\tconst seen = new Set<string>();\n\tconst outline = (id: string, selected: boolean) => {\n\t\tif (seen.has(id)) return;\n\t\tconst node = findVectorNode(doc.nodes, id);\n\t\tif (!node || node.visible === false) return;\n\t\tseen.add(id);\n\t\toutlines.push({ id, d: screenOutline(state, node, entered), selected });\n\t};\n\tfor (const id of state.selection) outline(id, true);\n\tif (state.editingId) outline(state.editingId, true);\n\tif (state.hover?.nodeId && !state.interaction) outline(state.hover.nodeId, false);\n\n\tlet selectionBox: VectorOverlayRenderData['selectionBox'] = null;\n\tif (state.tool === 'select' && state.selectionFrame && state.interaction?.type !== 'marquee' && state.interaction?.type !== 'distort') {\n\t\tconst g = getVectorSelectionBoxGeometry(state.selectionFrame, state.viewport);\n\t\tselectionBox = { ...g.box, angle: g.angle, transform: g.transform, corners: g.corners, handles: g.handles, freeDistort: state.freeDistort };\n\t}\n\n\tconst selected = (r: VectorAnchorRef) => state.selectedAnchors.some((a) => a.nodeId === r.nodeId && a.subpath === r.subpath && a.index === r.index);\n\tconst sameAnchor = (a: VectorAnchorRef | undefined, b: VectorAnchorRef) => !!a && a.nodeId === b.nodeId && a.subpath === b.subpath && a.index === b.index;\n\tconst anchors: VectorRenderAnchor[] = getVisibleAnchors(state).map((ref) => {\n\t\tconst a = getAnchorWorld(doc, ref)!;\n\t\tconst s = toScreen(state, a);\n\t\tconst closes = !!state.pen && state.pen.nodeId === ref.nodeId && state.pen.subpath === ref.subpath && ref.index === 0;\n\t\treturn { ref, x: s.x, y: s.y, type: a.type ?? inferAnchorType(a), selected: selected(ref), hovered: sameAnchor(state.hover?.anchor, ref), closes };\n\t});\n\tif (state.tool === 'pen' && !state.pen && state.hover?.anchor) {\n\t\tconst a = getAnchorWorld(doc, state.hover.anchor);\n\t\tif (a) {\n\t\t\tconst s = toScreen(state, a);\n\t\t\tanchors.push({ ref: state.hover.anchor, x: s.x, y: s.y, type: a.type ?? 'corner', selected: false, hovered: true, closes: false });\n\t\t}\n\t}\n\n\tconst handles: VectorRenderHandle[] = getVisibleHandles(state).flatMap((ref) => {\n\t\tconst a = getAnchorWorld(doc, ref);\n\t\tconst h = a?.[ref.handle];\n\t\tif (!a || !h) return [];\n\t\tconst s = toScreen(state, h);\n\t\tconst sa = toScreen(state, a);\n\t\tconst hovered = !!state.hover?.handle && sameAnchor(state.hover.handle, ref) && state.hover.handle.handle === ref.handle;\n\t\treturn [{ ref, x: s.x, y: s.y, anchorX: sa.x, anchorY: sa.y, hovered }];\n\t});\n\n\tlet marquee: VectorBounds | null = null;\n\tif (state.interaction?.type === 'marquee') {\n\t\tconst b = state.interaction.bounds;\n\t\tconst tl = toScreen(state, b);\n\t\tmarquee = { x: tl.x, y: tl.y, width: b.width * z, height: b.height * z };\n\t}\n\n\tlet penPreview: string | null = null;\n\tif (state.tool === 'pen' && state.pen && state.pointer && !state.interaction) {\n\t\tconst node = findVectorNode(doc.nodes, state.pen.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[state.pen.subpath] : undefined;\n\t\tconst last = sp ? getAnchorWorld(doc, { nodeId: state.pen.nodeId, subpath: state.pen.subpath, index: sp.anchors.length - 1 }) : undefined;\n\t\tif (last) {\n\t\t\tconst a = toScreen(state, last);\n\t\t\tconst p = toScreen(state, state.pointer);\n\t\t\tconst c = last.out ? toScreen(state, last.out) : null;\n\t\t\tpenPreview = c ? `M${fmt(a.x)} ${fmt(a.y)}Q${fmt(c.x)} ${fmt(c.y)} ${fmt(p.x)} ${fmt(p.y)}` : `M${fmt(a.x)} ${fmt(a.y)}L${fmt(p.x)} ${fmt(p.y)}`;\n\t\t}\n\t}\n\n\tconst origin = toScreen(state, { x: 0, y: 0 });\n\tconst artboard = { x: origin.x, y: origin.y, width: doc.width * z, height: doc.height * z };\n\n\tlet status: string | null = null;\n\tconst it = state.interaction;\n\tif (it?.type === 'rotate') status = `${Math.round(it.angle)}°`;\n\telse if (it?.type === 'move' || it?.type === 'anchors') status = `Δ ${fmt(it.dx)}, ${fmt(it.dy)}`;\n\telse if (it?.type === 'scale' || it?.type === 'draw') {\n\t\tconst b = it.type === 'draw' ? (findVectorNode(doc.nodes, it.nodeId) ? vectorNodeBounds(findVectorNode(doc.nodes, it.nodeId)!) : null) : state.selectionFrame;\n\t\tif (b) status = `W ${fmt(b.width)} × H ${fmt(b.height)}`;\n\t}\n\n\tconst guides: VectorOverlayRenderData['guides'] = { lines: [], labels: [] };\n\tif (state.guides) {\n\t\tfor (const l of state.guides.lines) {\n\t\t\tconst a = toScreen(state, { x: l.x1, y: l.y1 });\n\t\t\tconst b = toScreen(state, { x: l.x2, y: l.y2 });\n\t\t\tguides.lines.push({ kind: l.kind, x1: fmt(a.x), y1: fmt(a.y), x2: fmt(b.x), y2: fmt(b.y) });\n\t\t}\n\t\tfor (const l of state.guides.labels) {\n\t\t\tconst p = toScreen(state, l);\n\t\t\tguides.labels.push({ kind: l.kind, x: fmt(p.x), y: fmt(p.y), text: l.text });\n\t\t}\n\t}\n\n\tlet toolStroke: VectorOverlayRenderData['toolStroke'] = null;\n\tif (it?.type === 'stroke') {\n\t\tconst pts = it.points.map((q) => toScreen(state, q));\n\t\tconst d = pts.map((q, i) => `${i ? 'L' : 'M'}${fmt(q.x)} ${fmt(q.y)}`).join('') + (pts.length === 1 ? `L${fmt(pts[0].x)} ${fmt(pts[0].y)}` : '');\n\t\ttoolStroke = { tool: it.tool, d, width: fmt(it.width * z) };\n\t}\n\tlet pencilString: VectorOverlayRenderData['pencilString'] = null;\n\tif (it?.type === 'draw' && it.string) {\n\t\tconst a = toScreen(state, it.string[0]);\n\t\tconst b = toScreen(state, it.string[1]);\n\t\tpencilString = { x1: fmt(a.x), y1: fmt(a.y), x2: fmt(b.x), y2: fmt(b.y) };\n\t}\n\tconst dragged = it?.type === 'corner' ? it.ref : null;\n\tconst cornerWidgets: VectorRenderCornerWidget[] = getVectorCornerWidgets(state).map((w) => {\n\t\tconst s = toScreen(state, w);\n\t\treturn { ref: w.ref, x: fmt(s.x), y: fmt(s.y), radius: w.radius, kind: w.kind, hovered: sameAnchor(state.hover?.corner, w.ref), active: !!dragged };\n\t});\n\tif (it?.type === 'corner') status = `R ${fmt(it.radius)}`;\n\tconst cutPoint = state.tool === 'scissors' && state.hover?.segment && !it ? (({ x, y }) => ({ x: fmt(x), y: fmt(y) }))(toScreen(state, state.hover.segment.point)) : null;\n\n\tconst sc = (p: Vec2) => {\n\t\tconst q = toScreen(state, p);\n\t\treturn { x: fmt(q.x), y: fmt(q.y) };\n\t};\n\tconst sameWidth = (a: VectorWidthPointRef | null | undefined, b: VectorWidthPointRef) => !!a && a.nodeId === b.nodeId && a.index === b.index;\n\tconst widthPoints: VectorRenderWidthPoint[] = getVectorWidthHandles(state).map((h) => {\n\t\tconst c = sc(h);\n\t\tconst hw = state.hover?.widthPoint;\n\t\tconst hovered = hw && sameWidth(hw, h.ref) && hw.subpath === h.ref.subpath ? hw.part : null;\n\t\treturn { ref: h.ref, x: c.x, y: c.y, left: sc(h.left), right: sc(h.right), selected: h.selected, hovered, active: it?.type === 'width' && sameWidth(it.ref, h.ref) };\n\t});\n\tconst spot = state.tool === 'width' && !it ? state.hover?.strokeSpot : null;\n\tconst widthSpot = spot ? { ...sc(spot.point), left: sc(spot.left), right: sc(spot.right) } : null;\n\tif (it?.type === 'width') status = it.mode === 'move' ? 'Move width point' : it.mode === 'copy' ? 'Copy width point' : `W ${fmt(it.width)}`;\n\n\tlet builder: VectorOverlayRenderData['builder'] = null;\n\tif (state.builder) {\n\t\tconst v = state.viewport;\n\t\tconst view: AffineMatrix = [v.zoom, 0, 0, v.zoom, v.x, v.y];\n\t\tconst svg = (path: BezierPath) => bezierPathToSvg(path, { precision: 2 });\n\t\tconst screen = state.builder.faces.map((f) => transformBezierPath(f, view));\n\t\tconst hatch = state.builder.mode !== 'fill';\n\t\tconst trail = state.builder.trail && state.builder.trail.length > 1 ? state.builder.trail.map((q, i) => `${i ? 'L' : 'M'}${sc(q).x} ${sc(q).y}`).join('') : null;\n\t\tbuilder = {\n\t\t\tmode: state.builder.mode,\n\t\t\tfaces: screen.map(svg),\n\t\t\thatches: screen.map((f) => (hatch ? svg(hatchPath(f, { gap: VECTOR_BUILDER_HATCH_GAP })) : '')),\n\t\t\tlines: state.builder.lines.map((l) => svg(transformBezierPath(l, view))),\n\t\t\ttrail\n\t\t};\n\t\tif (state.builder.mode !== 'fill' && it?.type === 'builder') {\n\t\t\tconst n = state.builder.faces.length;\n\t\t\tstatus = state.builder.mode === 'erase' ? `Delete ${n} ${n === 1 ? 'face' : 'faces'}` : `Merge ${n} ${n === 1 ? 'face' : 'faces'}`;\n\t\t}\n\t}\n\n\tconst blend = blendOverlay(state);\n\tif (state.tool === 'blend' && !it) status = state.blendStart ? 'Click another shape to blend into' : 'Click a shape to blend from';\n\n\tlet gradient: VectorRenderGradientAnnotator | null = null;\n\tif (state.tool === 'gradient') {\n\t\tgradient = gradientOverlay(state);\n\t\tif (!gradient && !it) status = 'Drag across a shape to set a gradient';\n\t\telse if (it?.type === 'gradient' && it.removing) status = 'Release to delete the stop';\n\t}\n\n\tlet distort: VectorOverlayRenderData['distort'] = null;\n\tif (it?.type === 'distort') {\n\t\tconst corners = it.corners.map(sc);\n\t\tdistort = { mode: it.mode, corners, d: corners.map((c, i) => `${i ? 'L' : 'M'}${c.x} ${c.y}`).join('') + 'Z' };\n\t\tstatus = it.mode === 'skew' ? 'Skew' : it.mode === 'perspective' ? 'Perspective' : 'Distort';\n\t}\n\n\tconst envelope = state.tool === 'envelope' ? envelopeOverlay(state) : null;\n\tif (state.tool === 'envelope' && !envelope && !it) status = 'Select an object with an envelope to edit its mesh';\n\n\treturn { outlines, selectionBox, distort, anchors, handles, marquee, penPreview, artboard, guides, status, toolStroke, pencilString, cutPoint, cornerWidgets, widthPoints, widthSpot, builder, blend, gradient, envelope };\n}\n\nfunction envelopeOverlay(state: VectorEditorState): VectorOverlayRenderData['envelope'] {\n\tconst target = getVectorEnvelopeTarget(state.document, state.selection);\n\tif (!target) return null;\n\tconst v = state.viewport;\n\tconst m = multiplyMatrices(target.world, [v.zoom, 0, 0, v.zoom, v.x, v.y]);\n\tconst sc = (p: Vec2) => ({ x: fmt(m[0] * p.x + m[2] * p.y + m[4]), y: fmt(m[1] * p.x + m[3] * p.y + m[5]) });\n\tconst { mesh } = target.frame;\n\tconst grid = vectorMeshGridCurves(mesh)\n\t\t.map((c) => {\n\t\t\tconst [a, b, cc, d] = c.map(sc);\n\t\t\treturn `M${a.x} ${a.y}C${b.x} ${b.y} ${cc.x} ${cc.y} ${d.x} ${d.y}`;\n\t\t})\n\t\t.join('');\n\tconst hover = state.hover?.envelope?.nodeId === target.node.id ? state.hover.envelope.index : undefined;\n\tconst it = state.interaction;\n\tconst active = it?.type === 'envelope' && it.nodeId === target.node.id ? it.index : undefined;\n\tconst pts = vectorMeshEditPoints(mesh);\n\treturn {\n\t\tnodeId: target.node.id,\n\t\tgrid,\n\t\tanchors: pts.anchors.map((index) => ({ index, ...sc(mesh.points[index]), hovered: !it && hover === index, active: active === index })),\n\t\thandles: pts.handles.map((h) => {\n\t\t\tconst a = sc(mesh.points[h.anchor]);\n\t\t\treturn { index: h.index, ...sc(mesh.points[h.index]), anchorX: a.x, anchorY: a.y, hovered: !it && hover === h.index, active: active === h.index };\n\t\t})\n\t};\n}\n\n/** Warp choices of an envelope: the fifteen presets, then Mesh. */\nexport const VECTOR_ENVELOPE_STYLE_OPTIONS: readonly { value: VectorEnvelopeParams['style']; label: string }[] = [\n\t...VECTOR_WARP_STYLES.map((value) => ({ value, label: VECTOR_WARP_STYLE_LABELS[value] })),\n\t{ value: 'mesh', label: 'Mesh' }\n];\n\n/** What a Distort / Envelope panel shows for the selection. */\nexport interface VectorEnvelopePanelData {\n\t/** The one selected node, or null when several are selected. */\n\tnodeId: string | null;\n\tcount: number;\n\t/** The selected node's envelope (the first one in its stack), if any. */\n\tenvelope: { effectId: string; enabled: boolean; params: VectorEnvelopeParams } | null;\n\t/** Some selected node can take an envelope (Make with Warp / Mesh). */\n\tcanMake: boolean;\n\t/** Make with Top Object: several objects selected and the topmost is a closed path. */\n\tcanMakeWithTopObject: boolean;\n\t/** Some selected node has an envelope (Release, Expand). */\n\tcanRelease: boolean;\n}\n\n/** The Distort / Envelope panel of the selection, or null when nothing is selected. */\nexport function getVectorEnvelopePanel(state: Pick<VectorEditorState, 'document' | 'selection'>): VectorEnvelopePanelData | null {\n\tconst nodes = state.selection.map((id) => findVectorNode(state.document.nodes, id)).filter((n): n is VectorNode => !!n && !n.blendStep);\n\tif (!nodes.length) return null;\n\tconst one = nodes.length === 1 ? nodes[0] : null;\n\tconst first = one?.effects?.find((e) => e.type === 'envelope');\n\tconst order = new Map<string, number>();\n\twalkVectorNodes(state.document.nodes, (n) => order.set(n.id, order.size));\n\tconst top = nodes.length > 1 ? nodes.slice().sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))[nodes.length - 1] : null;\n\treturn {\n\t\tnodeId: one?.id ?? null,\n\t\tcount: nodes.length,\n\t\tenvelope: first?.type === 'envelope' ? { effectId: first.id, enabled: first.enabled !== false, params: first.params } : null,\n\t\tcanMake: nodes.some((n) => !n.locked),\n\t\tcanMakeWithTopObject: top?.type === 'path' && top.subpaths.some((sp) => sp.closed && sp.anchors.length > 1),\n\t\tcanRelease: nodes.some((n) => !n.locked && !!n.effects?.some((e) => e.type === 'envelope'))\n\t};\n}\n\nfunction gradientOverlay(state: VectorEditorState): VectorRenderGradientAnnotator | null {\n\tconst a = getVectorGradientAnnotator(state.document, state.selection, state.viewport, state.gradientEdit.target);\n\tif (!a) return null;\n\tconst hover = state.interaction ? null : state.hover?.gradient;\n\tconst handleHovered = (h: VectorGradientHandle) => hover?.kind === 'handle' && hover.handle === h;\n\tconst pt = (p: Vec2) => ({ x: fmt(p.x), y: fmt(p.y) });\n\tconst centred = isCentredVectorGradient(a.gradient.type);\n\tconst removing = state.interaction?.type === 'gradient' && !!state.interaction.removing;\n\treturn {\n\t\tnodeId: a.nodeId,\n\t\ttype: a.gradient.type,\n\t\tstart: { ...pt(a.start), hovered: handleHovered('start') },\n\t\tend: { ...pt(a.end), hovered: handleHovered(centred ? 'radius' : 'end'), handle: centred ? 'radius' : 'end' },\n\t\taspect: a.aspect ? { ...pt(a.aspect), hovered: handleHovered('aspect') } : null,\n\t\tfocal: a.focal ? { ...pt(a.focal), hovered: handleHovered('focal') } : null,\n\t\tstops: a.stops.map((s) => ({\n\t\t\tindex: s.index,\n\t\t\t...pt(s),\n\t\t\tbarX: fmt(s.x - a.normal.x * VECTOR_GRADIENT_STOP_GAP),\n\t\t\tbarY: fmt(s.y - a.normal.y * VECTOR_GRADIENT_STOP_GAP),\n\t\t\tcolor: s.color,\n\t\t\topacity: s.opacity ?? 1,\n\t\t\tselected: state.gradientEdit.stop === s.index,\n\t\t\thovered: hover?.kind === 'stop' && hover.index === s.index\n\t\t})),\n\t\tmidpoints: a.midpoints.map((m) => ({ index: m.index, ...pt(m), hovered: hover?.kind === 'midpoint' && hover.index === m.index })),\n\t\textent: a.extent,\n\t\tremoving\n\t};\n}\n\n/** Blend groups the selection covers (a selected key counts as its blend). */\nfunction selectedBlends(state: Pick<VectorEditorState, 'document' | 'selection'>): VectorGroupNode[] {\n\tconst out = new Map<string, VectorGroupNode>();\n\tfor (const id of state.selection) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tconst group = isVectorBlendGroup(node) ? node : locateVectorNode(state.document.nodes, id)?.parent;\n\t\tif (isVectorBlendGroup(group)) out.set(group.id, group);\n\t}\n\treturn [...out.values()];\n}\n\nfunction blendOverlay(state: VectorEditorState): VectorOverlayRenderData['blend'] {\n\tconst v = state.viewport;\n\tconst view: AffineMatrix = [v.zoom, 0, 0, v.zoom, v.x, v.y];\n\tconst doc = state.document;\n\tconst sc = (p: Vec2, m: AffineMatrix) => {\n\t\tconst q = { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] };\n\t\treturn { x: fmt(q.x), y: fmt(q.y) };\n\t};\n\tconst spines = selectedBlends(state).flatMap((g) => {\n\t\tconst s = vectorBlendSpine(g);\n\t\tif (!s) return [];\n\t\tconst m = multiplyMatrices(vectorWorldMatrix(doc.nodes, g.id) ?? IDENTITY_MATRIX, view);\n\t\tconst d = bezierPathToSvg(transformBezierPath(subpathsToBezier([s.spine], { corners: false }), m), { precision: 2 });\n\t\tconst keys = s.stops.map((stop) => {\n\t\t\tconst p = vectorBlendRailAt(s.rail, stop).point;\n\t\t\treturn sc({ x: p[0], y: p[1] }, m);\n\t\t});\n\t\treturn [{ id: g.id, d, keys, replaced: s.replaced }];\n\t});\n\tlet start: VectorOverlayRenderData['blend']['start'] = null;\n\tconst anchors: VectorOverlayRenderData['blend']['anchors'] = [];\n\tif (state.tool === 'blend') {\n\t\tconst from = state.blendStart ? findVectorNode(doc.nodes, state.blendStart.nodeId) : undefined;\n\t\tif (from && state.blendStart) {\n\t\t\tconst a = state.blendStart.anchor === null ? undefined : getAnchorWorld(doc, { nodeId: from.id, subpath: 0, index: state.blendStart.anchor });\n\t\t\tstart = { d: screenOutline(state, from, new Set()), anchor: a ? sc(a, view) : null };\n\t\t}\n\t\tconst hovered = state.hover?.nodeId ? findVectorNode(doc.nodes, state.hover.nodeId) : undefined;\n\t\tif (hovered?.type === 'path' && hovered.subpaths[0]) {\n\t\t\thovered.subpaths[0].anchors.forEach((_, index) => {\n\t\t\t\tconst a = getAnchorWorld(doc, { nodeId: hovered.id, subpath: 0, index });\n\t\t\t\tif (a) anchors.push({ ...sc(a, view), hovered: state.hover?.anchor?.index === index });\n\t\t\t});\n\t\t}\n\t}\n\treturn { spines, start, anchors };\n}\n\n/** What the Blend controls of a toolbar or style panel show. */\nexport interface VectorBlendControls {\n\t/** Ids of the selected blends (a selected key counts as its blend). */\n\tids: string[];\n\t/** The first selected blend's options, or the options new blends get. */\n\toptions: Required<VectorBlendOptions>;\n\t/** Two or more shapes that share a parent are selected: Blend can run. */\n\tcanBlend: boolean;\n\t/** One blend and one path are selected: Replace Spine can run. */\n\tcanReplaceSpine: boolean;\n\t/** The first selected blend follows a replaced spine. */\n\thasSpine: boolean;\n}\n\n/** State of the Blend controls for the current selection. */\nexport function getVectorBlendControls(state: Pick<VectorEditorState, 'document' | 'selection' | 'blendDefaults'>): VectorBlendControls {\n\tconst blends = selectedBlends(state);\n\tconst doc = state.document;\n\tconst roots = state.selection.filter((id) => {\n\t\tconst node = findVectorNode(doc.nodes, id);\n\t\treturn !!node && !node.blendStep && !node.locked && !state.selection.includes(locateVectorNode(doc.nodes, id)?.parent?.id ?? '');\n\t});\n\tconst parents = new Set(roots.map((id) => locateVectorNode(doc.nodes, id)?.parent?.id ?? null));\n\tconst paths = roots.filter((id) => findVectorNode(doc.nodes, id)?.type === 'path' && !isVectorBlendGroup(locateVectorNode(doc.nodes, id)?.parent));\n\tconst first = blends[0];\n\treturn {\n\t\tids: blends.map((g) => g.id),\n\t\toptions: resolveVectorBlendOptions(first ? first.blend : state.blendDefaults),\n\t\tcanBlend: roots.length >= 2 && parents.size === 1,\n\t\tcanReplaceSpine: blends.length === 1 && paths.length === 1,\n\t\thasSpine: !!first?.blend?.spine\n\t};\n}\n\n/**\n * Applies blend options from a toolbar: to the selected blends (one undo step) and to the\n * options new blends get, so the controls keep showing what was picked.\n */\nexport function applyVectorBlendOptions(controller: VectorEditorController, patch: Partial<VectorBlendOptions>): void {\n\tcontroller.setBlendDefaults(patch);\n\tif (getVectorBlendControls(controller.getState()).ids.length) controller.setBlendOptions(patch);\n}\n\n/** Labels of the blend spacing modes, for toolbars. */\nexport const VECTOR_BLEND_SPACING_LABELS: Readonly<Record<VectorBlendSpacing, string>> = { steps: 'Specified Steps', distance: 'Specified Distance', smoothColor: 'Smooth Color' };\n\n// ---------------------------------------------------------------------------\n// Event adapters (duck-typed, so they work with DOM, React and Svelte events)\n// ---------------------------------------------------------------------------\n\n/** Colours and sizes (screen pixels) the bundled canvases draw the overlay with. */\nexport const VECTOR_OVERLAY_THEME = {\n\taccent: '#0ea5e9',\n\t/** Smart guide lines and labels. */\n\tguide: '#ff3dfc',\n\thandleFill: '#ffffff',\n\tmarqueeFill: 'rgba(14, 165, 233, 0.08)',\n\t/** The eraser's swath while it is dragged. */\n\teraserFill: 'rgba(239, 68, 68, 0.25)',\n\ttransformHandleSize: 8,\n\tanchorSize: 7,\n\thandleRadius: 3.5,\n\t/** Radius of a live corner widget (a ring with a dot). */\n\tcornerWidgetRadius: 4,\n\t/** Half the diagonal of a width point's diamond. */\n\twidthPointSize: 5,\n\t/** Shape Builder faces to merge and paint bucket regions. */\n\tbuilderFill: 'rgba(14, 165, 233, 0.22)',\n\t/** Shape Builder faces and line pieces an Alt gesture deletes. */\n\tbuilderErase: '#ef4444',\n\tbuilderEraseFill: 'rgba(239, 68, 68, 0.22)',\n\t/** Opacity of the hatch lines over Shape Builder faces (drawn in the face's outline colour). */\n\tbuilderHatchOpacity: 0.6\n} as const;\n\n/** SVG path data of the diamond a width point is drawn with (screen pixels). */\nexport function vectorDiamondPath(x: number, y: number, r: number = VECTOR_OVERLAY_THEME.widthPointSize): string {\n\treturn `M${fmt(x)} ${fmt(y - r)}L${fmt(x + r)} ${fmt(y)}L${fmt(x)} ${fmt(y + r)}L${fmt(x - r)} ${fmt(y)}Z`;\n}\n\ninterface ModifierEventLike {\n\tshiftKey?: boolean;\n\taltKey?: boolean;\n\tmetaKey?: boolean;\n\tctrlKey?: boolean;\n}\n\n/** Modifiers of a mouse / pointer / key event (`mod` is Cmd or Ctrl). */\nexport function toVectorModifiers(event: ModifierEventLike): { shift: boolean; alt: boolean; mod: boolean } {\n\treturn { shift: !!event.shiftKey, alt: !!event.altKey, mod: !!(event.metaKey || event.ctrlKey) };\n}\n\n/**\n * A pointer event as `VectorEditorController.pointerDown/Move/Up` input: modifiers, button,\n * and the pressure and pointer type the pencil records as a width profile.\n */\nexport function toVectorPointerInput(event: ModifierEventLike & { button?: number; pressure?: number; pointerType?: string }) {\n\treturn {\n\t\t...toVectorModifiers(event),\n\t\tbutton: event.button,\n\t\t...(typeof event.pressure === 'number' ? { pressure: event.pressure } : {}),\n\t\t...(event.pointerType ? { pointerType: event.pointerType } : {})\n\t};\n}\n\n/** A key event as `VectorEditorController.keyDown/keyUp` input. */\nexport function toVectorKeyInput(event: ModifierEventLike & { key: string }) {\n\treturn { key: event.key, ...toVectorModifiers(event) };\n}\n\n/** True for targets that should keep their own keys (inputs, textareas, contenteditable). */\nexport function isVectorTextTarget(target: unknown): boolean {\n\tconst el = target as { tagName?: string; isContentEditable?: boolean; getAttribute?: (name: string) => string | null } | null;\n\tif (!el || typeof el !== 'object') return false;\n\tconst tag = (el.tagName ?? '').toUpperCase();\n\tif (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n\treturn !!el.isContentEditable || el.getAttribute?.('contenteditable') === 'true';\n}\n\n// ---------------------------------------------------------------------------\n// Style panel helpers\n// ---------------------------------------------------------------------------\n\n/** Style shown in a style panel: the first selected path's, with `mixed` flags when paths differ. */\nexport interface VectorSelectionStyle {\n\tfill: VectorPaint;\n\tstroke: VectorPaint;\n\tstrokeWidth: number;\n\topacity: number;\n\tstrokeAlign: VectorStrokeAlign;\n\tstartArrow: VectorArrowhead | null;\n\tendArrow: VectorArrowhead | null;\n\tarrowAlign: VectorArrowAlign;\n\tstartArrowScale: number;\n\tendArrowScale: number;\n\t/** The first path's width profile (null when uniform) and the preset it matches. */\n\tstrokeWidthProfile: VectorWidthPoint[] | null;\n\twidthProfile: VectorWidthPreset | 'custom';\n\t/**\n\t * Live corners of the selected anchors (direct tool) or of every corner of the selected\n\t * paths: the first one's radius and kind, and how many corners there are (0: none to round).\n\t */\n\tcornerRadius: number;\n\tcornerKind: VectorCornerKind;\n\tcorners: number;\n\t/** Some selected path is open, so arrowheads apply. */\n\thasOpenPath: boolean;\n\tmixed: {\n\t\tfill: boolean;\n\t\tstroke: boolean;\n\t\tstrokeWidth: boolean;\n\t\topacity: boolean;\n\t\tstrokeAlign: boolean;\n\t\tstartArrow: boolean;\n\t\tendArrow: boolean;\n\t\tarrowAlign: boolean;\n\t\tstartArrowScale: boolean;\n\t\tendArrowScale: boolean;\n\t\twidthProfile: boolean;\n\t\tcornerRadius: boolean;\n\t\tcornerKind: boolean;\n\t};\n\t/** Ids of the paths the style applies to. */\n\tpathIds: string[];\n}\n\nexport function getVectorSelectionStyle(\n\tstate: Pick<VectorEditorState, 'document' | 'selection'> & Partial<Pick<VectorEditorState, 'selectedAnchors' | 'tool'>>\n): VectorSelectionStyle | null {\n\tconst paths: VectorPathNode[] = [];\n\tfor (const id of state.selection) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node) paths.push(...collect(node));\n\t}\n\tconst anchorMode = state.tool === 'direct' && !!state.selectedAnchors?.length;\n\tif (anchorMode) {\n\t\tfor (const r of state.selectedAnchors!) {\n\t\t\tif (paths.some((p) => p.id === r.nodeId)) continue;\n\t\t\tconst node = findVectorNode(state.document.nodes, r.nodeId);\n\t\t\tif (node?.type === 'path') paths.push(node);\n\t\t}\n\t}\n\tif (!paths.length) return null;\n\tconst first = paths[0];\n\tconst same = (get: (p: VectorPathNode) => unknown) => paths.every((p) => JSON.stringify(get(p) ?? null) === JSON.stringify(get(first) ?? null));\n\t// Corners: those of the selected anchors in the direct tool, else every corner of the paths.\n\tconst corners: { radius: number; kind: VectorCornerKind }[] = [];\n\tfor (const p of paths) {\n\t\tfor (const c of vectorCorners(p.subpaths)) {\n\t\t\tif (anchorMode && !state.selectedAnchors!.some((r) => r.nodeId === p.id && r.subpath === c.subpath && r.index === c.index)) continue;\n\t\t\tconst corner = p.subpaths[c.subpath].anchors[c.index].corner;\n\t\t\tcorners.push({ radius: corner?.radius ?? 0, kind: corner?.kind ?? 'round' });\n\t\t}\n\t}\n\tconst c0 = corners[0] ?? { radius: 0, kind: 'round' as const };\n\treturn {\n\t\tfill: first.fill ?? null,\n\t\tstroke: first.stroke ?? null,\n\t\tstrokeWidth: first.strokeWidth ?? 1,\n\t\topacity: first.opacity ?? 1,\n\t\tstrokeAlign: first.strokeAlign ?? 'center',\n\t\tstartArrow: first.startArrow ?? null,\n\t\tendArrow: first.endArrow ?? null,\n\t\tarrowAlign: first.arrowAlign ?? 'extend',\n\t\tstartArrowScale: first.startArrowScale ?? 1,\n\t\tendArrowScale: first.endArrowScale ?? 1,\n\t\tstrokeWidthProfile: profileOf(first),\n\t\twidthProfile: widthProfilePresetId(profileOf(first)),\n\t\tcornerRadius: c0.radius,\n\t\tcornerKind: c0.kind,\n\t\tcorners: corners.length,\n\t\thasOpenPath: paths.some((p) => p.subpaths.some((sp) => !sp.closed && sp.anchors.length > 1)),\n\t\tmixed: {\n\t\t\tfill: !same((p) => p.fill),\n\t\t\tstroke: !same((p) => p.stroke),\n\t\t\tstrokeWidth: !same((p) => p.strokeWidth ?? 1),\n\t\t\topacity: !same((p) => p.opacity ?? 1),\n\t\t\tstrokeAlign: !same((p) => p.strokeAlign ?? 'center'),\n\t\t\tstartArrow: !same((p) => p.startArrow ?? null),\n\t\t\tendArrow: !same((p) => p.endArrow ?? null),\n\t\t\tarrowAlign: !same((p) => p.arrowAlign ?? 'extend'),\n\t\t\tstartArrowScale: !same((p) => p.startArrowScale ?? 1),\n\t\t\tendArrowScale: !same((p) => p.endArrowScale ?? 1),\n\t\t\twidthProfile: !same(profileOf),\n\t\t\tcornerRadius: corners.some((c) => c.radius !== c0.radius),\n\t\t\tcornerKind: corners.some((c) => c.kind !== c0.kind)\n\t\t},\n\t\tpathIds: paths.map((p) => p.id)\n\t};\n}\n\nfunction profileOf(p: VectorPathNode): VectorWidthPoint[] | null {\n\tconst points = sanitizeWidthProfile(p.strokeWidthProfile);\n\treturn points.length && widthProfilePresetId(points) !== 'uniform' ? points : null;\n}\n\n/** Labels of the stroke alignments, corner kinds and arrowheads, for style panels. */\nexport const VECTOR_STROKE_ALIGN_LABELS: Readonly<Record<VectorStrokeAlign, string>> = { center: 'Center', inside: 'Inside', outside: 'Outside' };\nexport const VECTOR_CORNER_KIND_LABELS: Readonly<Record<VectorCornerKind, string>> = { round: 'Round', inverted: 'Inverted', chamfer: 'Chamfer' };\nexport const VECTOR_ARROWHEAD_LABELS: Readonly<Record<VectorArrowhead, string>> = {\n\ttriangle: 'Triangle',\n\tarrow: 'Arrow',\n\topen: 'Open arrow',\n\tcircle: 'Circle',\n\tsquare: 'Square',\n\tbar: 'Bar'\n};\n\n/** A paint as `#rrggbb` for `<input type=\"color\">`, or null for none, gradients and other CSS colours. */\nexport function vectorPaintToHex(paint: VectorPaint | undefined): string | null {\n\tif (typeof paint !== 'string') return null;\n\tconst m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(paint.trim());\n\tif (!m) return null;\n\tconst hex = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];\n\treturn `#${hex.toLowerCase()}`;\n}\n\n// ---------------------------------------------------------------------------\n// Gradient editor\n// ---------------------------------------------------------------------------\n\nexport const VECTOR_GRADIENT_TYPE_LABELS: Readonly<Record<VectorGradientType, string>> = { linear: 'Linear', radial: 'Radial', conic: 'Conic', reflected: 'Reflected', diamond: 'Diamond' };\nexport const VECTOR_GRADIENT_SPREAD_LABELS: Readonly<Record<VectorGradientSpread, string>> = { pad: 'Pad', reflect: 'Reflect', repeat: 'Repeat' };\nexport const VECTOR_GRADIENT_INTERPOLATION_LABELS: Readonly<Record<VectorGradientInterpolation, string>> = { srgb: 'sRGB', linear: 'Linear light', oklab: 'Oklab' };\nexport const VECTOR_STROKE_GRADIENT_MODE_LABELS: Readonly<Record<VectorStrokeGradientMode, string>> = { within: 'Within stroke', along: 'Along stroke', across: 'Across stroke' };\n\n/** What a gradient editor shows for the selection's `target` paint (see `getVectorGradientEditor`). */\nexport interface VectorGradientEditorData {\n\ttarget: 'fill' | 'stroke';\n\t/** The first selected path's paint is a gradient. */\n\tgradient: VectorGradient | null;\n\t/** The paint as a `#rrggbb` colour when it is one (what a new gradient starts from). */\n\tcolor: string | null;\n\t/** Sorted stops; `index` is what `setGradientStop` takes. */\n\tstops: (VectorGradientStop & { index: number; selected: boolean })[];\n\tselected: (VectorGradientStop & { index: number; last: boolean }) | null;\n\t/** A CSS `linear-gradient(to right, …)` of the ramp (midpoints and colour space expanded). */\n\tpreview: string | null;\n\ttype: VectorGradientType | null;\n\tspread: VectorGradientSpread;\n\tinterpolation: VectorGradientInterpolation;\n\tsmoothness: number;\n\tstrokeMode: VectorStrokeGradientMode;\n\t/** The selected paths' gradients differ. */\n\tmixed: boolean;\n}\n\n/** The gradient editor of the selection's fill or stroke (`state.gradientEdit.target`), or null with nothing selected. */\nexport function getVectorGradientEditor(state: Pick<VectorEditorState, 'document' | 'selection' | 'gradientEdit'>): VectorGradientEditorData | null {\n\tconst paths: VectorPathNode[] = [];\n\tfor (const id of state.selection) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node) paths.push(...collect(node));\n\t}\n\tif (!paths.length) return null;\n\tconst target = state.gradientEdit.target;\n\tconst paint = paths[0][target];\n\tconst gradient = isVectorGradient(paint) ? paint : null;\n\tconst sorted = gradient ? sortedVectorGradientStops(gradient) : [];\n\tconst stopIndex = state.gradientEdit.stop;\n\tconst stops = sorted.map((s, index) => ({ ...s, index, selected: index === stopIndex }));\n\tconst sel = stopIndex !== null && sorted[stopIndex] ? { ...sorted[stopIndex], index: stopIndex, last: stopIndex === sorted.length - 1 } : null;\n\tconst preview = gradient\n\t\t? `linear-gradient(to right, ${expandVectorGradientStops(gradient)\n\t\t\t\t.map((s) => {\n\t\t\t\t\tconst c = parseVectorColor(s.color);\n\t\t\t\t\tconst a = (c?.[3] ?? 1) * (s.opacity ?? 1);\n\t\t\t\t\tconst color = c ? `rgba(${Math.round(c[0] * 255)}, ${Math.round(c[1] * 255)}, ${Math.round(c[2] * 255)}, ${Math.round(a * 1000) / 1000})` : s.color;\n\t\t\t\t\treturn `${color} ${Math.round(s.offset * 10000) / 100}%`;\n\t\t\t\t})\n\t\t\t\t.join(', ')})`\n\t\t: null;\n\treturn {\n\t\ttarget,\n\t\tgradient,\n\t\tcolor: vectorPaintToHex(paint),\n\t\tstops,\n\t\tselected: sel,\n\t\tpreview,\n\t\ttype: gradient?.type ?? null,\n\t\tspread: gradient?.spread ?? 'pad',\n\t\tinterpolation: gradient?.interpolation ?? 'srgb',\n\t\tsmoothness: gradient?.smoothness ?? 0,\n\t\tstrokeMode: gradient?.strokeMode ?? 'within',\n\t\tmixed: paths.some((p) => JSON.stringify(p[target] ?? null) !== JSON.stringify(paint ?? null))\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Toolbar helpers\n// ---------------------------------------------------------------------------\n\n/** A path-editing button of the bundled toolbars. */\nexport interface VectorPathAction {\n\tid: 'join' | 'average' | 'cut' | 'clean' | 'smooth' | 'outline';\n\tlabel: string;\n\ttitle: string;\n\t/** Shortcut after Cmd / Ctrl, if any. */\n\tshortcut?: string;\n\t/** Whether it can run with `selected` nodes and `points` selected anchors (direct tool). */\n\tenabled: (selected: number, points: number) => boolean;\n\trun: (controller: VectorEditorController) => unknown;\n}\n\n/** Join, Average, Cut at Points, Remove Redundant Points, Smooth and Outline Stroke, as the toolbars show them. */\nexport const VECTOR_PATH_ACTIONS: readonly VectorPathAction[] = [\n\t{ id: 'join', label: '⋈', title: 'Join', shortcut: 'J', enabled: (s, p) => s + p > 0, run: (c) => c.joinPaths() },\n\t{ id: 'average', label: '⊹', title: 'Average Points', shortcut: 'Alt+J', enabled: (_s, p) => p > 1, run: (c) => c.averageAnchors('both') },\n\t{ id: 'cut', label: '✂·', title: 'Cut at Points', enabled: (_s, p) => p > 0, run: (c) => c.cutAtAnchors() },\n\t{ id: 'clean', label: '⌁', title: 'Remove Redundant Points', enabled: (s, p) => s + p > 0, run: (c) => c.removeRedundantPoints() },\n\t{ id: 'smooth', label: '∿', title: 'Smooth', enabled: (s, p) => s + p > 0, run: (c) => c.smoothPaths() },\n\t{ id: 'outline', label: '⊡', title: 'Outline Stroke', enabled: (s) => s > 0, run: (c) => c.outlineStroke() }\n];\n\n/** A Pathfinder button of the bundled toolbars. */\nexport interface VectorPathfinderAction {\n\tid: VectorPathfinderOperation;\n\tlabel: string;\n\ttitle: string;\n\t/** Paths (or groups) it needs selected. */\n\tmin: number;\n}\n\n/** Divide, Trim, Merge, Crop, Outline and Minus Back, as the toolbars show them. */\nexport const VECTOR_PATHFINDER_ACTIONS: readonly VectorPathfinderAction[] = [\n\t{ id: 'divide', label: '⊞', title: 'Divide', min: 1 },\n\t{ id: 'trim', label: '⧉', title: 'Trim', min: 2 },\n\t{ id: 'merge', label: '⧈', title: 'Merge', min: 2 },\n\t{ id: 'crop', label: '⌗', title: 'Crop', min: 2 },\n\t{ id: 'outline', label: '⬚', title: 'Outline', min: 1 },\n\t{ id: 'minusBack', label: '⊖', title: 'Minus Back', min: 2 }\n];\n\n/** The on / off path-editing settings the toolbars toggle. */\nexport const VECTOR_EDIT_TOGGLES: readonly { key: 'keepShapeOnDelete' | 'curvatureMoves' | 'recognizeShapes'; label: string; title: string }[] = [\n\t{ key: 'keepShapeOnDelete', label: 'Keep', title: 'Keep shape when deleting points' },\n\t{ key: 'curvatureMoves', label: 'Curv', title: 'Curvature point moves (Alt flips while dragging)' },\n\t{ key: 'recognizeShapes', label: 'Shapes', title: 'Turn pencil scribbles into shapes' }\n];\n\n\n// ---------------------------------------------------------------------------\n// Effects panel\n// ---------------------------------------------------------------------------\n\n/** One effect of the listed stack, with what a panel needs to edit it. */\nexport interface VectorEffectsPanelItem {\n\tid: string;\n\ttype: VectorEffectType;\n\tlabel: string;\n\tenabled: boolean;\n\tparams: Record<string, unknown>;\n\t/** The parameters to edit (none for an envelope: `getVectorEnvelopePanel` and the Envelope panels edit it). */\n\tspecs: readonly VectorEffectParamSpec[];\n}\n\n/** What an Effects panel shows for the selection. */\nexport interface VectorEffectsPanelData {\n\t/** The node whose stack is listed (when one node is selected), else null. */\n\tnodeId: string | null;\n\t/** Selected nodes an added effect goes to. */\n\tcount: number;\n\t/** The listed stack, applied top to bottom. */\n\teffects: VectorEffectsPanelItem[];\n\t/** Something selected is live (Expand Appearance applies). */\n\texpandable: boolean;\n}\n\n/** Effect types in menu order, with their names. */\nexport const VECTOR_EFFECT_MENU: readonly { type: VectorEffectType; label: string }[] = VECTOR_EFFECT_TYPES.map((type) => ({ type, label: VECTOR_EFFECT_LABELS[type] }));\n\n/** The Effects panel of the selection, or null when nothing that takes effects is selected. */\nexport function getVectorEffectsPanel(state: Pick<VectorEditorState, 'document' | 'selection'>): VectorEffectsPanelData | null {\n\tconst nodes = state.selection.map((id) => findVectorNode(state.document.nodes, id)).filter((n): n is VectorNode => !!n && !n.blendStep);\n\tif (!nodes.length) return null;\n\tconst one = nodes.length === 1 ? nodes[0] : null;\n\treturn {\n\t\tnodeId: one?.id ?? null,\n\t\tcount: nodes.length,\n\t\teffects: (one?.effects ?? []).map((e) => ({\n\t\t\tid: e.id,\n\t\t\ttype: e.type,\n\t\t\tlabel: VECTOR_EFFECT_LABELS[e.type] ?? e.type,\n\t\t\tenabled: e.enabled !== false,\n\t\t\tparams: e.params as unknown as Record<string, unknown>,\n\t\t\t// The Envelope panel (`getVectorEnvelopePanel`) edits an envelope's warp and mesh.\n\t\t\tspecs: e.type === 'envelope' ? [] : (VECTOR_EFFECT_PARAM_SPECS[e.type] ?? [])\n\t\t})),\n\t\texpandable: nodes.some(hasVectorAppearance)\n\t};\n}\n","import type { CommandSpec } from '../commands/registry.js';\nimport type { VectorEditorController, VectorShapeInput } from './controller.js';\nimport { vectorNodeBounds, vectorNodeRotation, vectorParentMatrix, vectorPathData, IDENTITY_MATRIX } from './geometry.js';\nimport type { VectorAlign, VectorAnchorRef, VectorArrange, VectorAverageAxis, VectorBooleanOperation, VectorCornerKind, VectorNode, VectorPathfinderOperation, VectorStyle, VectorTool } from './types.js';\nimport { VECTOR_ARROWHEADS, VECTOR_CORNER_KINDS, VECTOR_EFFECT_TYPES, VECTOR_PATHFINDER_OPERATIONS, VECTOR_TOOLS, type VectorEffect, type VectorEffectType, type VectorWidthPoint } from './types.js';\nimport { VECTOR_WIDTH_PRESET_IDS, type VectorTaperOptions, type VectorWaveOptions, type VectorWidthPreset } from './width.js';\nimport { resolveVectorBlendOptions, vectorBlendKeys } from './blendGroup.js';\nimport { VECTOR_BLEND_SPACINGS, VECTOR_GRADIENT_INTERPOLATIONS, VECTOR_GRADIENT_SPREADS, VECTOR_GRADIENT_TYPES, VECTOR_STROKE_GRADIENT_MODES, type VectorBlendOptions } from './types.js';\nimport { sanitizeVectorGradient, type VectorGradientPatch } from './gradient.js';\nimport { isValidVectorMesh, VECTOR_WARP_STYLES } from './warp.js';\nimport type { VectorEnvelopeParams } from './appearance.js';\n\nexport interface VectorCommandOptions {\n\t/** Id prefix (default `vector.`); use one per editor when several are registered. */\n\tprefix?: string;\n\t/** Palette group (default `Vector`). */\n\tgroup?: string;\n\t/** Command scope. Omit for global commands. */\n\tscope?: string;\n}\n\n/** A node as listed for agents. */\nexport interface VectorNodeListing {\n\tid: string;\n\ttype: 'path' | 'group';\n\tname?: string;\n\tdepth: number;\n\t/** Axis-aligned bounds in document units. */\n\tbounds: { x: number; y: number; width: number; height: number } | null;\n\t/** Rotation in degrees, clockwise (ancestors' rotations included). */\n\trotation: number;\n\tvisible: boolean;\n\tlocked: boolean;\n\tselected: boolean;\n\tfill?: unknown;\n\tstroke?: unknown;\n\tstrokeWidth?: number;\n\t/** SVG path data (paths only). */\n\td?: string;\n\tchildren?: number;\n\t/** A blend group's options (its steps are listed as children with `blendStep`). */\n\tblend?: { spacing: string; steps: number; distance: number; orientToSpine: boolean; linear: boolean; spine: boolean; keys: string[] };\n\t/** An in-between generated by a blend (locked; changes come from its keys). */\n\tblendStep?: boolean;\n\t/** The node's live path effects, applied in order. */\n\teffects?: VectorEffect[];\n\t/** A live boolean group's operation (its children are the operands). */\n\tliveBoolean?: VectorBooleanOperation;\n\t/** An operand's own operation in a live boolean group. */\n\tbooleanOperation?: VectorBooleanOperation;\n}\n\nconst EFFECT_PARAMS_DESCRIPTION =\n\t'Effect parameters (missing ones keep their value or default). trim: start, end (percent), offset (degrees), mode simultaneous|individual. roundCorners: radius. puckerBloat: amount (−100…100). twist: angle, center {x, y} (offset from the middle). zigzag: size, ridges, smooth. wiggle: size, detail, smooth, speed, correlation, phase, seed, time (seconds). offset: amount, join miter|round|bevel, miterLimit, copies, copyOffset. merge: mode merge|add|subtract|intersect|exclude. repeater: copies (fractions fade the last), offset, position {x, y}, anchor {x, y} (offset from the middle), rotation, scale {x, y} (percent), startOpacity, endOpacity (percent), composite below|above. envelope: style (a warp preset: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist, or mesh), bend, horizontal, vertical (percent, −100…100), orientation horizontal|vertical, rows, columns, mesh { us, vs, points } (node space; prefer vector.envelope).';\n\nconst fail = (message: string): never => {\n\tthrow new Error(message);\n};\n\nconst IDS = { type: 'array', items: { type: 'string' }, description: 'Node ids (default: the selection).' } as const;\n\nconst ANCHORS = {\n\ttype: 'array',\n\titems: {\n\t\ttype: 'object',\n\t\tproperties: { nodeId: { type: 'string' }, subpath: { type: 'integer', minimum: 0 }, index: { type: 'integer', minimum: 0 } },\n\t\trequired: ['nodeId', 'subpath', 'index']\n\t},\n\tdescription: 'Anchors as { nodeId, subpath, index } (default: the selected points).'\n} as const;\n\nconst POINTS = {\n\ttype: 'array',\n\titems: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2 },\n\tminItems: 1,\n\tdescription: 'Polyline [[x, y], …] in document units.'\n} as const;\n\nconst WIDTH_POINTS = {\n\ttype: ['array', 'null'],\n\titems: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tt: { type: 'number', minimum: 0, maximum: 1, description: 'Position along each subpath by length (0 start, 1 end).' },\n\t\t\tleft: { type: 'number', minimum: 0, description: 'Left side as a multiple of half the stroke width (1 = uniform).' },\n\t\t\tright: { type: 'number', minimum: 0, description: 'Right side (looking along the path, y down).' }\n\t\t},\n\t\trequired: ['t', 'left', 'right']\n\t},\n\tdescription: 'Variable-width profile points, interpolated smoothly (monotone cubic); two points at one `t` make a step. `null` or `[]` strokes at a uniform width.'\n} as const;\n\nconst BLEND_PROPS = {\n\tspacing: { type: 'string', enum: ['steps', 'distance', 'smoothColor'], description: 'How in-betweens are spaced (default steps).' },\n\tsteps: { type: 'integer', minimum: 1, maximum: 1000, description: 'In-betweens between each pair of keys (steps spacing; default 5).' },\n\tdistance: { type: 'number', exclusiveMinimum: 0, description: 'Distance between in-betweens along the spine (distance spacing; default 20).' },\n\torientToSpine: { type: 'boolean', description: 'Turn the in-betweens with a replaced spine.' },\n\tlinear: { type: 'boolean', description: 'Move anchors in straight lines instead of the rotation-aware morph.' }\n} as const;\n\nconst checkBlendOptions = (params: Partial<VectorBlendOptions> | undefined) => {\n\tif (params?.spacing !== undefined && !VECTOR_BLEND_SPACINGS.includes(params.spacing)) fail(`Unknown blend spacing \"${params.spacing}\".`);\n\tif (params?.steps !== undefined && !(Number.isFinite(params.steps) && params.steps >= 1)) fail('steps must be at least 1.');\n\tif (params?.distance !== undefined && !(Number.isFinite(params.distance) && params.distance > 0)) fail('distance must be positive.');\n};\n\nconst POINT = { type: 'object', properties: { x: { type: 'number' }, y: { type: 'number' } }, required: ['x', 'y'] } as const;\n\n/** Gradient fields shared by paints and `setGradient`. */\nconst GRADIENT_PROPS = {\n\ttype: { type: 'string', enum: VECTOR_GRADIENT_TYPES, description: 'linear, radial, conic (an angle sweep), reflected (linear mirrored about the start) or diamond.' },\n\tstops: {\n\t\ttype: 'array',\n\t\tminItems: 1,\n\t\titems: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\toffset: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\tcolor: { type: 'string', description: 'A CSS colour.' },\n\t\t\t\topacity: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\tmidpoint: { type: 'number', minimum: 0.05, maximum: 0.95, description: 'Where between this stop and the next the colours are half-mixed (default 0.5).' }\n\t\t\t},\n\t\t\trequired: ['offset', 'color']\n\t\t}\n\t},\n\tangle: { type: 'number', description: 'Shorthand direction in degrees (0 up, clockwise): linear / reflected direction across the box, conic start angle, diamond turn.' },\n\tcx: { type: 'number', description: 'Shorthand centre x of radial / conic / diamond gradients, a fraction of the box (default 0.5).' },\n\tcy: { type: 'number' },\n\tr: { type: 'number', description: 'Shorthand radius, a fraction of the box (default 0.5).' },\n\tstart: { ...POINT, description: 'Explicit start (centre of radial / conic / diamond), in `units`. Wins over the shorthand.' },\n\tend: { ...POINT, description: 'Explicit end of the main axis (the radius of radial / conic / diamond).' },\n\twidth: { ...POINT, description: 'End of the secondary axis (aspect and turn of radial / conic / diamond); default square to the main axis, as long.' },\n\tfocal: { ...POINT, description: 'Radial focal point (where t = 0), in `units`.' },\n\tfocalRadius: { type: 'number', minimum: 0, maximum: 0.99, description: 'Radial focal circle radius as a fraction of the radius (SVG fr).' },\n\tunits: { type: 'string', enum: ['objectBoundingBox', 'userSpaceOnUse'], description: 'Space of start / end / width / focal: fractions of the shape box (default) or the node\\'s own coordinates.' },\n\tspread: { type: 'string', enum: VECTOR_GRADIENT_SPREADS, description: 'What paints past the ends: pad (default), reflect or repeat.' },\n\tinterpolation: { type: 'string', enum: VECTOR_GRADIENT_INTERPOLATIONS, description: 'Colour mixing space: srgb (default), linear (light) or oklab.' },\n\tsmoothness: { type: 'number', minimum: 0, maximum: 1, description: 'Bends the ramp along a smooth spline through the stops (0 = straight).' },\n\tstrokeMode: { type: 'string', enum: VECTOR_STROKE_GRADIENT_MODES, description: 'On strokes: within (default, like a fill), along the path or across it.' }\n} as const;\n\nconst PAINT = {\n\tdescription:\n\t\t'A CSS colour, `null` for none, or a gradient object: `{ type: \"linear\" | \"radial\" | \"conic\" | \"reflected\" | \"diamond\", stops: [{ offset, color, opacity?, midpoint? }] }` plus the shorthand `angle` / `cx, cy, r` or explicit `start`, `end`, `width`, `focal`, `focalRadius`, `units`, and `spread`, `interpolation`, `smoothness`, `strokeMode` (see vector.setGradient).',\n\tanyOf: [{ type: 'string' }, { type: 'null' }, { type: 'object', properties: GRADIENT_PROPS, required: ['type', 'stops'] }]\n} as const;\n\nconst STYLE_PROPS = {\n\tfill: PAINT,\n\tstroke: PAINT,\n\tstrokeWidth: { type: 'number', minimum: 0 },\n\tstrokeLinecap: { type: 'string', enum: ['butt', 'round', 'square'] },\n\tstrokeLinejoin: { type: 'string', enum: ['miter', 'round', 'bevel'] },\n\tstrokeDasharray: { type: 'array', items: { type: 'number' } },\n\tfillRule: { type: 'string', enum: ['nonzero', 'evenodd'] },\n\tstrokeAlign: { type: 'string', enum: ['center', 'inside', 'outside'], description: 'Where the stroke sits on the outline (closed shapes only; open paths stroke centred).' },\n\tstartArrow: { type: ['string', 'null'], enum: [...VECTOR_ARROWHEADS, null], description: 'Head at the start of an open path, or null for none.' },\n\tendArrow: { type: ['string', 'null'], enum: [...VECTOR_ARROWHEADS, null], description: 'Head at the end of an open path, or null for none.' },\n\tarrowAlign: { type: 'string', enum: ['extend', 'tip'], description: '`extend`: the tip sits past the end point; `tip`: on it, the stroke shortened under the head.' },\n\tstartArrowScale: { type: 'number', exclusiveMinimum: 0, description: 'Start head size as a multiple of the stroke width (default 1).' },\n\tendArrowScale: { type: 'number', exclusiveMinimum: 0, description: 'End head size as a multiple of the stroke width (default 1).' },\n\tstrokeWidthProfile: WIDTH_POINTS\n} as const;\n\nconst pickStyle = (params: Record<string, unknown>): VectorStyle => {\n\tconst out: Record<string, unknown> = {};\n\tfor (const key of Object.keys(STYLE_PROPS)) if (params[key] !== undefined) out[key] = params[key];\n\tfor (const key of ['fill', 'stroke'] as const) {\n\t\tconst paint = out[key];\n\t\tif (paint && typeof paint === 'object') out[key] = sanitizeVectorGradient(paint) ?? fail(`${key} is not a valid gradient: give a type and at least one stop { offset, color }.`);\n\t}\n\treturn out as VectorStyle;\n};\n\nconst check = (result: { ok: boolean; message?: string }) => {\n\tif (!result.ok) fail(result.message ?? 'The command failed.');\n};\n\n/**\n * Palette and agent commands for a vector editor: list, select, add shapes and paths, style,\n * transform, align, arrange, group, boolean operations and SVG import / export. Register them\n * in a `CommandRegistry` and agents get them through `createCommandToolProvider`. Failures\n * throw sentences, which the registry returns as `{ ok: false, code: 'failed', message }`.\n */\nexport function createVectorCommands(controller: VectorEditorController, options: VectorCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'vector.';\n\tconst group = options.group ?? 'Vector';\n\tconst base = { group, ...(options.scope ? { scope: options.scope } : {}) };\n\tconst hasSelection = () => (controller.getState().selection.length ? true : 'Nothing is selected.');\n\tconst ids = (params: { ids?: string[] } | undefined) => {\n\t\tconst list = params?.ids ?? controller.getState().selection;\n\t\tfor (const id of list) if (!controller.getNode(id)) fail(`There is no node \"${id}\".`);\n\t\tif (!list.length) fail('Nothing is selected; pass ids.');\n\t\treturn list;\n\t};\n\tconst enabledFor = (_: unknown, params: { ids?: string[] } | undefined) => (params?.ids?.length ? true : hasSelection());\n\tconst anchorsOf = (refs: VectorAnchorRef[] | undefined): VectorAnchorRef[] => {\n\t\tif (!refs) return [...controller.getState().selectedAnchors];\n\t\tfor (const r of refs) {\n\t\t\tconst node = controller.getNode(r.nodeId);\n\t\t\tif (node?.type !== 'path' || !node.subpaths[r.subpath]?.anchors[r.index]) fail(`There is no anchor ${r.index} on subpath ${r.subpath} of \"${r.nodeId}\".`);\n\t\t}\n\t\treturn refs;\n\t};\n\n\tconst list = (): { width: number; height: number; nodes: VectorNodeListing[]; selection: readonly string[]; tool: VectorTool } => {\n\t\tconst state = controller.getState();\n\t\tconst out: VectorNodeListing[] = [];\n\t\tconst visit = (nodes: readonly VectorNode[], depth: number) => {\n\t\t\tfor (const n of nodes) {\n\t\t\t\tconst parent = vectorParentMatrix(state.document.nodes, n.id) ?? IDENTITY_MATRIX;\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tout.push({\n\t\t\t\t\tid: n.id,\n\t\t\t\t\ttype: n.type,\n\t\t\t\t\t...(n.name ? { name: n.name } : {}),\n\t\t\t\t\tdepth,\n\t\t\t\t\trotation: Math.round(vectorNodeRotation(n, parent) * 100) / 100,\n\t\t\t\t\tbounds: b && { x: Math.round(b.x * 100) / 100, y: Math.round(b.y * 100) / 100, width: Math.round(b.width * 100) / 100, height: Math.round(b.height * 100) / 100 },\n\t\t\t\t\tvisible: n.visible !== false,\n\t\t\t\t\tlocked: !!n.locked,\n\t\t\t\t\tselected: state.selection.includes(n.id),\n\t\t\t\t\t...(n.type === 'path'\n\t\t\t\t\t\t? { fill: n.fill ?? null, stroke: n.stroke ?? null, strokeWidth: n.strokeWidth ?? 1, d: vectorPathData(n, 2) }\n\t\t\t\t\t\t: { children: n.children.length }),\n\t\t\t\t\t...(n.type === 'group' && n.blend\n\t\t\t\t\t\t? { blend: { ...resolveVectorBlendOptions(n.blend), spine: !!n.blend.spine, keys: vectorBlendKeys(n).map((k) => k.id) } }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(n.blendStep ? { blendStep: true } : {}),\n\t\t\t\t\t...(n.effects?.length ? { effects: n.effects } : {}),\n\t\t\t\t\t...(n.type === 'group' && n.liveBoolean ? { liveBoolean: n.liveBoolean } : {}),\n\t\t\t\t\t...(n.booleanOperation ? { booleanOperation: n.booleanOperation } : {})\n\t\t\t\t});\n\t\t\t\tif (n.type === 'group') visit(n.children, depth + 1);\n\t\t\t}\n\t\t};\n\t\tvisit(state.document.nodes, 0);\n\t\treturn { width: state.document.width, height: state.document.height, nodes: out, selection: state.selection, tool: state.tool };\n\t};\n\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}list`,\n\t\t\tlabel: 'List Vector Nodes',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['layers', 'shapes', 'document', 'outline'],\n\t\t\tdescription: 'Lists every node (paths and groups, depth first) with bounds, style, path data and selection.',\n\t\t\trun: list\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}select`,\n\t\t\tlabel: 'Select Nodes',\n\t\t\tkeywords: ['pick', 'choose'],\n\t\t\tdescription: 'Selects nodes by id (empty list clears the selection).',\n\t\t\tparams: { type: 'object', properties: { ids: { type: 'array', items: { type: 'string' } }, add: { type: 'boolean' } }, required: ['ids'] },\n\t\t\trun: (_ctx: unknown, params: { ids: string[]; add?: boolean }) => {\n\t\t\t\tfor (const id of params.ids) if (!controller.getNode(id)) fail(`There is no node \"${id}\".`);\n\t\t\t\tif (!params.ids.length && !params.add) controller.clearSelection();\n\t\t\t\telse controller.select(params.ids, { add: params.add });\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addShape`,\n\t\t\tlabel: 'Add Shape…',\n\t\t\tkeywords: ['rectangle', 'ellipse', 'circle', 'polygon', 'star', 'line', 'draw'],\n\t\t\tdescription: 'Adds a rectangle, ellipse, polygon, star or line in document units, using the current default style unless overridden.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tkind: { type: 'string', enum: ['rect', 'ellipse', 'polygon', 'star', 'line'] },\n\t\t\t\t\tx: { type: 'number' },\n\t\t\t\t\ty: { type: 'number' },\n\t\t\t\t\twidth: { type: 'number', description: 'For a line: the x offset of its end.' },\n\t\t\t\t\theight: { type: 'number', description: 'For a line: the y offset of its end.' },\n\t\t\t\t\tcornerRadius: { type: 'number', minimum: 0, description: 'Live corner radius of a rect, polygon or star.' },\n\t\t\t\t\tcornerKind: { type: 'string', enum: VECTOR_CORNER_KINDS },\n\t\t\t\t\tsides: { type: 'integer', minimum: 3 },\n\t\t\t\t\tpoints: { type: 'integer', minimum: 3 },\n\t\t\t\t\tinnerRatio: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\tname: { type: 'string' },\n\t\t\t\t\t...STYLE_PROPS\n\t\t\t\t},\n\t\t\t\trequired: ['kind', 'x', 'y', 'width', 'height']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: VectorShapeInput) => ({ id: controller.addShape(params) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addPath`,\n\t\t\tlabel: 'Add Path…',\n\t\t\tkeywords: ['svg', 'path data', 'bezier', 'curve'],\n\t\t\tdescription: 'Adds a path from SVG path data (`d`), in document units.',\n\t\t\tparams: { type: 'object', properties: { d: { type: 'string' }, name: { type: 'string' }, ...STYLE_PROPS }, required: ['d'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { d: string; name?: string } & Record<string, unknown>) => {\n\t\t\t\tconst id = controller.addPath(params.d, { ...pickStyle(params), ...(params.name ? { name: params.name } : {}) });\n\t\t\t\tconst node = controller.getNode(id);\n\t\t\t\tif (node?.type === 'path' && !node.subpaths.length) {\n\t\t\t\t\tcontroller.undo();\n\t\t\t\t\tfail('The path data has no points.');\n\t\t\t\t}\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setStyle`,\n\t\t\tlabel: 'Set Style…',\n\t\t\tkeywords: ['fill', 'stroke', 'colour', 'color', 'gradient', 'width'],\n\t\t\tdescription: 'Sets fill, stroke and stroke settings of nodes (groups apply to every path inside).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, ...STYLE_PROPS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } & Record<string, unknown>) => {\n\t\t\t\tconst style = pickStyle(params);\n\t\t\t\tif (!Object.keys(style).length) fail('Pass at least one style property.');\n\t\t\t\tcheck(controller.setStyle(style, ids(params)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setGradient`,\n\t\t\tlabel: 'Gradient…',\n\t\t\tkeywords: ['gradient', 'linear', 'radial', 'conic', 'angle', 'reflected', 'diamond', 'stops', 'midpoint', 'oklab', 'spread', 'focal', 'along stroke', 'across stroke', 'reverse'],\n\t\t\tdescription:\n\t\t\t\t'Edits the gradient of the fill (default) or stroke of paths (groups apply to every path inside): any gradient field (missing ones keep their value; a colour becomes a gradient from it to white), `aspect` (secondary axis over main axis), `reverse` (flip the stops and midpoints), `focal` / `width` null to remove them. Midpoints, smoothness and oklab / linear interpolation export to SVG as extra stops; conic and diamond gradients as patterns.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, target: { type: 'string', enum: ['fill', 'stroke'] }, ...GRADIENT_PROPS, aspect: { type: 'number' }, reverse: { type: 'boolean' } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: ({ ids?: string[]; target?: 'fill' | 'stroke' } & VectorGradientPatch) | undefined) => {\n\t\t\t\tconst { ids: _i, target, ...patch } = params ?? {};\n\t\t\t\tif (patch.type !== undefined && !VECTOR_GRADIENT_TYPES.includes(patch.type)) fail(`Unknown gradient type \"${patch.type}\".`);\n\t\t\t\tif (patch.stops !== undefined && !(Array.isArray(patch.stops) && patch.stops.length)) fail('stops needs at least one { offset, color }.');\n\t\t\t\tcheck(controller.setGradient(patch, { ids: ids(params), target: target ?? 'fill' }));\n\t\t\t\tconst id = ids(params)[0];\n\t\t\t\tconst node = id ? controller.getNode(id) : undefined;\n\t\t\t\tconst path = node?.type === 'path' ? node : undefined;\n\t\t\t\treturn { ok: true, ...(path ? { gradient: path[target ?? 'fill'] } : {}) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setCorners`,\n\t\t\tlabel: 'Corner Radius…',\n\t\t\tkeywords: ['round', 'rounded', 'corners', 'radius', 'fillet', 'chamfer', 'live corners'],\n\t\t\tdescription:\n\t\t\t\t'Sets the live corner radius (and optionally `kind`: round, inverted or chamfer) of `anchors`, else the selected points (direct tool), else every corner of `ids` / the selection. Radius 0 makes corners sharp; radii shrink to fit short sides. The anchors stay editable.',\n\t\t\tparams: { type: 'object', properties: { radius: { type: 'number', minimum: 0 }, kind: { type: 'string', enum: VECTOR_CORNER_KINDS }, ids: IDS, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { radius?: number; kind?: VectorCornerKind; ids?: string[]; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tconst refs = params?.anchors ? anchorsOf(params.anchors) : undefined;\n\t\t\t\tconst target = { refs, ids: params?.ids ? ids(params) : undefined };\n\t\t\t\tif (params?.radius !== undefined) check(controller.setCornerRadius(params.radius, { ...target, kind: params.kind }));\n\t\t\t\telse if (params?.kind) check(controller.setCornerKind(params.kind, target));\n\t\t\t\telse fail('Pass `radius` and / or `kind`.');\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setWidthProfile`,\n\t\t\tlabel: 'Width Profile…',\n\t\t\tkeywords: ['variable width', 'taper', 'tapered', 'pressure', 'profile', 'brush', 'calligraphy', 'bulge', 'thick', 'thin'],\n\t\t\tdescription:\n\t\t\t\t'Gives the stroke of paths a variable width: a `preset` (`uniform` removes the profile), explicit `points` ({ t, left, right }: side scales along each subpath), or a parametric `taper` (startLength / endLength as fractions of the path, startWidth / endWidth 0–1, startEase / endEase 0–1) and / or `wave` (amount 0–1, cycles, phase in degrees). Profiled strokes draw as filled outlines; Outline Stroke bakes them.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tpreset: { type: 'string', enum: VECTOR_WIDTH_PRESET_IDS },\n\t\t\t\t\tpoints: WIDTH_POINTS,\n\t\t\t\t\ttaper: {\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tstartLength: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendLength: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tstartWidth: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendWidth: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tstartEase: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendEase: { type: 'number', minimum: 0, maximum: 1 }\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\twave: { type: 'object', properties: { amount: { type: 'number', minimum: 0, maximum: 1 }, cycles: { type: 'number', exclusiveMinimum: 0 }, phase: { type: 'number' } } }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (\n\t\t\t\t_ctx: unknown,\n\t\t\t\tparams: { ids?: string[]; preset?: VectorWidthPreset; points?: VectorWidthPoint[] | null; taper?: VectorTaperOptions; wave?: VectorWaveOptions } | undefined\n\t\t\t) => {\n\t\t\t\tconst target = { ids: ids(params) };\n\t\t\t\tif (params?.preset) check(controller.setWidthProfile(params.preset, target));\n\t\t\t\telse if (params?.points !== undefined) check(controller.setWidthProfile(params.points ?? null, target));\n\t\t\t\telse if (params?.taper || params?.wave) check(controller.setWidthProfile({ taper: params.taper, wave: params.wave }, target));\n\t\t\t\telse fail('Pass `preset`, `points`, `taper` or `wave`.');\n\t\t\t\tconst node = controller.getNode(target.ids[0]);\n\t\t\t\treturn { ok: true, points: node?.type === 'path' ? (node.strokeWidthProfile ?? []) : [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setWidthPoint`,\n\t\t\tlabel: 'Width Point…',\n\t\t\tkeywords: ['width point', 'variable width', 'stroke width at', 'taper', 'profile'],\n\t\t\tdescription:\n\t\t\t\t'Sets one width point of a path\\'s stroke profile numerically: `index` names an existing point (see `vector.setWidthProfile`\\'s result), leave it out to add one at `t`. `left` / `right` are side widths in document units (how far the stroke reaches on each side), `t` the position along each subpath (0–1); a point moved onto another\\'s `t` makes a step. Returns the profile.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tid: { type: 'string', description: 'The path.' },\n\t\t\t\t\tindex: { type: 'integer', minimum: 0 },\n\t\t\t\t\tt: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\tleft: { type: 'number', minimum: 0 },\n\t\t\t\t\tright: { type: 'number', minimum: 0 }\n\t\t\t\t},\n\t\t\t\trequired: ['id']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { id: string; index?: number; t?: number; left?: number; right?: number } | undefined) => {\n\t\t\t\tif (!params?.id) fail('Pass the path `id`.');\n\t\t\t\tcheck(controller.setWidthPoint({ nodeId: params!.id, index: params!.index ?? null }, { t: params!.t, left: params!.left, right: params!.right }));\n\t\t\t\tconst node = controller.getNode(params!.id);\n\t\t\t\treturn { ok: true, points: node?.type === 'path' ? (node.strokeWidthProfile ?? []) : [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}outlineStroke`,\n\t\t\tlabel: 'Outline Stroke',\n\t\t\tkeywords: ['expand', 'stroke to path', 'outline', 'convert stroke'],\n\t\t\tdescription: 'Turns the stroke of paths into filled shapes of the area it paints (alignment, caps, joins, dashes and arrowheads included). Returns the new ids.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst created = controller.outlineStroke({ ids: params?.ids ? ids(params) : undefined });\n\t\t\t\tif (!created.length) fail('No selected path has a stroke.');\n\t\t\t\treturn { ids: created };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}distort`,\n\t\t\tlabel: 'Free Distort…',\n\t\t\tkeywords: ['distort', 'perspective', 'free distort', 'corners', 'projective', 'keystone'],\n\t\t\tdescription:\n\t\t\t\t'Free Distort: moves the four corners of the selection box (clockwise from the top left, in the box’s own rotation) to `corners` in document units, distorting the nodes in perspective (straight lines stay straight; curves are followed within `tolerance`). The corners must make a convex quadrilateral. One undo step.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tcorners: { type: 'array', items: POINT, minItems: 4, maxItems: 4, description: 'New top-left, top-right, bottom-right and bottom-left corners.' },\n\t\t\t\t\ttolerance: { type: 'number', exclusiveMinimum: 0, description: 'How closely curves follow the distortion (document units, default 0.05).' }\n\t\t\t\t},\n\t\t\t\trequired: ['corners']\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; corners: { x: number; y: number }[]; tolerance?: number }) => {\n\t\t\t\tcheck(controller.distort(params.corners, { ids: ids(params), tolerance: params.tolerance }));\n\t\t\t\tconst frame = controller.getState().selectionFrame;\n\t\t\t\treturn { ok: true, bounds: frame ? { x: frame.x, y: frame.y, width: frame.width, height: frame.height } : null };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}skew`,\n\t\t\tlabel: 'Skew…',\n\t\t\tkeywords: ['skew', 'shear', 'slant', 'oblique'],\n\t\t\tdescription:\n\t\t\t\t'Skews nodes along the selection box’s axes: `ax` degrees horizontally (vertical lines lean right for positive angles) and `ay` degrees vertically, about the box centre or `origin`. One undo step.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tax: { type: 'number', minimum: -89.9, maximum: 89.9 },\n\t\t\t\t\tay: { type: 'number', minimum: -89.9, maximum: 89.9 },\n\t\t\t\t\torigin: POINT\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; ax?: number; ay?: number; origin?: { x: number; y: number } }) => {\n\t\t\t\tcheck(controller.skew(params.ax ?? 0, params.ay ?? 0, { ids: ids(params), origin: params.origin }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}envelope`,\n\t\t\tlabel: 'Envelope Distort…',\n\t\t\tkeywords: ['envelope', 'warp', 'mesh', 'arc', 'arch', 'bulge', 'flag', 'wave', 'fish', 'rise', 'fisheye', 'inflate', 'squeeze', 'twist', 'shell', 'bend', 'distort'],\n\t\t\tdescription:\n\t\t\t\t'Envelope distortion that stays editable (a live `envelope` effect). Give `preset` (with `bend`, `horizontal`, `vertical` in percent, −100…100, and `orientation`) to warp, or `mesh` ({ rows, columns } and optionally `points`, the control grid row by row in the node’s own space) for an editable mesh; a node that already has an envelope is changed. `topObject: true` uses the topmost selected closed path as the envelope of the others; `release: true` removes the envelope and gives back its shape as a path; `expand: true` bakes it (Expand Appearance). One undo step.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tpreset: { type: 'string', enum: VECTOR_WARP_STYLES },\n\t\t\t\t\tbend: { type: 'number', minimum: -100, maximum: 100 },\n\t\t\t\t\thorizontal: { type: 'number', minimum: -100, maximum: 100 },\n\t\t\t\t\tvertical: { type: 'number', minimum: -100, maximum: 100 },\n\t\t\t\t\torientation: { type: 'string', enum: ['horizontal', 'vertical'] },\n\t\t\t\t\tmesh: {\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\trows: { type: 'integer', minimum: 1, maximum: 16 },\n\t\t\t\t\t\t\tcolumns: { type: 'integer', minimum: 1, maximum: 16 },\n\t\t\t\t\t\t\tpoints: { type: 'array', items: POINT, description: '(3·columns + 1) × (3·rows + 1) control points, row by row (node space).' }\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\ttopObject: { type: 'boolean' },\n\t\t\t\t\trelease: { type: 'boolean' },\n\t\t\t\t\texpand: { type: 'boolean' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (\n\t\t\t\t_ctx: unknown,\n\t\t\t\tparams: {\n\t\t\t\t\tids?: string[];\n\t\t\t\t\tpreset?: string;\n\t\t\t\t\tbend?: number;\n\t\t\t\t\thorizontal?: number;\n\t\t\t\t\tvertical?: number;\n\t\t\t\t\torientation?: 'horizontal' | 'vertical';\n\t\t\t\t\tmesh?: { rows?: number; columns?: number; points?: { x: number; y: number }[] };\n\t\t\t\t\ttopObject?: boolean;\n\t\t\t\t\trelease?: boolean;\n\t\t\t\t\texpand?: boolean;\n\t\t\t\t}\n\t\t\t) => {\n\t\t\t\tconst target = ids(params);\n\t\t\t\tif (params.release) return { released: target, shapes: controller.releaseEnvelope({ ids: target }) };\n\t\t\t\tif (params.expand) return { expanded: controller.expandAppearance({ ids: target }) };\n\t\t\t\tif (params.topObject) {\n\t\t\t\t\tconst r = controller.makeEnvelopeWithTopObject({ ids: target, rows: params.mesh?.rows, columns: params.mesh?.columns });\n\t\t\t\t\tcheck(r);\n\t\t\t\t\treturn { nodeId: r.nodeId };\n\t\t\t\t}\n\t\t\t\tif (params.preset !== undefined && !(VECTOR_WARP_STYLES as readonly string[]).includes(params.preset)) fail(`Unknown warp preset \"${params.preset}\".`);\n\t\t\t\tconst patch: Partial<VectorEnvelopeParams> = {};\n\t\t\t\tif (params.preset) patch.style = params.preset as VectorEnvelopeParams['style'];\n\t\t\t\tfor (const k of ['bend', 'horizontal', 'vertical'] as const) if (params[k] !== undefined) patch[k] = params[k];\n\t\t\t\tif (params.orientation) patch.orientation = params.orientation;\n\t\t\t\tif (params.mesh) {\n\t\t\t\t\tif (params.preset) fail('Give either `preset` or `mesh`, not both.');\n\t\t\t\t\tpatch.style = 'mesh';\n\t\t\t\t\tconst columns = params.mesh.columns ?? 2;\n\t\t\t\t\tconst rows = params.mesh.rows ?? 2;\n\t\t\t\t\tpatch.columns = columns;\n\t\t\t\t\tpatch.rows = rows;\n\t\t\t\t\tif (params.mesh.points) {\n\t\t\t\t\t\tconst even = (n: number) => Array.from({ length: n + 1 }, (_, i) => i / n);\n\t\t\t\t\t\tconst mesh = { us: even(columns), vs: even(rows), points: params.mesh.points.map((p) => ({ x: p.x, y: p.y })) };\n\t\t\t\t\t\tif (!isValidVectorMesh(mesh)) fail(`A ${columns} × ${rows} mesh needs ${(3 * columns + 1) * (3 * rows + 1)} finite points.`);\n\t\t\t\t\t\tpatch.mesh = mesh;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst made = controller.envelope(patch, { ids: target });\n\t\t\t\tif (!made.length) fail('Nothing to envelope.');\n\t\t\t\treturn { envelopes: made };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}transform`,\n\t\t\tlabel: 'Transform…',\n\t\t\tkeywords: ['move', 'translate', 'scale', 'resize', 'rotate', 'flip'],\n\t\t\tdescription:\n\t\t\t\t'Moves (dx, dy), scales (sx, sy, along the selection box axes) and/or rotates (`rotate`: by degrees clockwise around the combined centre; `angle`: to an absolute rotation, each node around its own centre), in that order.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tdx: { type: 'number' },\n\t\t\t\t\tdy: { type: 'number' },\n\t\t\t\t\tsx: { type: 'number' },\n\t\t\t\t\tsy: { type: 'number' },\n\t\t\t\t\trotate: { type: 'number' },\n\t\t\t\t\tangle: { type: 'number' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; dx?: number; dy?: number; sx?: number; sy?: number; rotate?: number; angle?: number }) => {\n\t\t\t\tconst target = ids(params);\n\t\t\t\tif (params.dx || params.dy) check(controller.translate(params.dx ?? 0, params.dy ?? 0, { ids: target }));\n\t\t\t\tif (params.sx !== undefined || params.sy !== undefined) check(controller.scale(params.sx ?? 1, params.sy ?? params.sx ?? 1, { ids: target }));\n\t\t\t\tif (params.rotate) check(controller.rotate(params.rotate, { ids: target }));\n\t\t\t\tif (params.angle !== undefined) check(controller.setRotation(params.angle, { ids: target }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}delete`,\n\t\t\tlabel: 'Delete',\n\t\t\tkeywords: ['remove'],\n\t\t\tdescription: 'Deletes nodes.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tcheck(controller.removeNodes(ids(params)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}boolean`,\n\t\t\tlabel: 'Boolean Operation…',\n\t\t\tkeywords: ['union', 'unite', 'subtract', 'intersect', 'exclude', 'combine', 'pathfinder'],\n\t\t\tdescription:\n\t\t\t\t'Combines two or more paths with union, subtract (upper shapes from the lowest), intersect or exclude. With `live`, the shapes stay editable operands of a live boolean group instead (a lone live group gets the operation; its operands get their own).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\toperation: { type: 'string', enum: ['union', 'subtract', 'intersect', 'exclude'] },\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tlive: { type: 'boolean', description: 'Keep the operands editable in a live boolean group (default false: one new path).' }\n\t\t\t\t},\n\t\t\t\trequired: ['operation']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { operation: VectorBooleanOperation; ids?: string[]; live?: boolean }) => {\n\t\t\t\tconst id = controller.booleanOp(params.operation, { ids: ids(params), live: params.live });\n\t\t\t\tif (!id) fail(params.live ? 'Select two or more nodes with one parent, a live boolean group or its operands.' : 'Select at least two overlapping paths (the result was empty).');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addEffect`,\n\t\t\tlabel: 'Add Path Effect…',\n\t\t\tkeywords: ['effect', 'trim', 'round corners', 'pucker', 'bloat', 'twist', 'zig zag', 'wiggle', 'offset', 'merge', 'repeater', 'appearance', 'live'],\n\t\t\tdescription: 'Adds a live path effect to the bottom of the effect stack of nodes (paths or groups). Effects apply top to bottom; effects after a repeater act on its copies. Returns the new effect ids.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\ttype: { type: 'string', enum: VECTOR_EFFECT_TYPES },\n\t\t\t\t\tparams: { type: 'object', description: EFFECT_PARAMS_DESCRIPTION },\n\t\t\t\t\tindex: { type: 'integer', minimum: 0, description: 'Position in the stack (default: last).' },\n\t\t\t\t\tids: IDS\n\t\t\t\t},\n\t\t\t\trequired: ['type']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\tenabled: enabledFor,\n\t\t\trun: (_ctx: unknown, params: { type: VectorEffectType; params?: Record<string, unknown>; index?: number; ids?: string[] }) => {\n\t\t\t\tif (!VECTOR_EFFECT_TYPES.includes(params.type)) fail(`Unknown effect type \"${params.type}\".`);\n\t\t\t\tconst targets = ids(params);\n\t\t\t\tconst created = controller.addEffect(params.type, { ids: targets, params: params.params, index: params.index });\n\t\t\t\tif (!created.length) fail('Nothing to add the effect to.');\n\t\t\t\treturn { effects: targets.map((id, i) => ({ nodeId: id, effectId: created[i] })) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}updateEffect`,\n\t\t\tlabel: 'Edit Path Effect…',\n\t\t\tkeywords: ['effect', 'parameters', 'enable', 'disable', 'reorder'],\n\t\t\tdescription: 'Changes a path effect: its parameters, whether it is enabled, and its position in the stack.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tnodeId: { type: 'string' },\n\t\t\t\t\teffectId: { type: 'string' },\n\t\t\t\t\tparams: { type: 'object', description: EFFECT_PARAMS_DESCRIPTION },\n\t\t\t\t\tenabled: { type: 'boolean' },\n\t\t\t\t\tindex: { type: 'integer', minimum: 0, description: 'Move it to this position in the stack (0 applies first).' }\n\t\t\t\t},\n\t\t\t\trequired: ['nodeId', 'effectId']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId: string; effectId: string; params?: Record<string, unknown>; enabled?: boolean; index?: number }) => {\n\t\t\t\tif (params.params !== undefined || params.enabled !== undefined) check(controller.updateEffect(params.nodeId, params.effectId, { params: params.params, enabled: params.enabled }));\n\t\t\t\tif (params.index !== undefined) check(controller.moveEffect(params.nodeId, params.effectId, params.index));\n\t\t\t\treturn { effects: controller.getNode(params.nodeId)?.effects ?? [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeEffect`,\n\t\t\tlabel: 'Remove Path Effect',\n\t\t\tkeywords: ['effect', 'delete'],\n\t\t\tdescription: 'Removes a path effect from a node.',\n\t\t\tparams: { type: 'object', properties: { nodeId: { type: 'string' }, effectId: { type: 'string' } }, required: ['nodeId', 'effectId'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId: string; effectId: string }) => {\n\t\t\t\tcheck(controller.removeEffect(params.nodeId, params.effectId));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}expandAppearance`,\n\t\t\tlabel: 'Expand Appearance',\n\t\t\tkeywords: ['effects', 'bake', 'flatten', 'live boolean', 'expand'],\n\t\t\tdescription: 'Bakes the path effects and live booleans of nodes (and everything inside them) into plain paths.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tundoable: true,\n\t\t\tenabled: enabledFor,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst expanded = controller.expandAppearance({ ids: ids(params) });\n\t\t\t\tif (!expanded.length) fail('Nothing selected has path effects or a live boolean.');\n\t\t\t\treturn { ids: expanded };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}blend`,\n\t\t\tlabel: 'Make Blend…',\n\t\t\tkeywords: ['blend', 'morph', 'tween', 'interpolate', 'in-between', 'steps', 'transition'],\n\t\t\tdescription:\n\t\t\t\t'Blends two or more paths or groups (sharing a parent; bottom to top, or in the order given with keepOrder) into a live blend group: the in-betweens morph shape (anchors matched by arc length, the start and winding that twist least, rotation-aware so turning shapes turn) and paint (OKLab colours, gradients, stroke width, opacity, width profiles), and regenerate whenever a key changes. Spacing: `steps` (count between each pair of keys), `distance` (along the spine) or `smoothColor`. `starts` maps key ids to the anchor of their first subpath the blend starts from. Returns the blend id.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\t...BLEND_PROPS,\n\t\t\t\t\tkeepOrder: { type: 'boolean', description: 'Blend in the order of `ids` instead of stacking order.' },\n\t\t\t\t\tstarts: { type: 'object', additionalProperties: { type: 'integer', minimum: 0 }, description: 'Start anchor per key id.' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: (VectorBlendOptions & { ids?: string[]; keepOrder?: boolean; starts?: Record<string, number> }) | undefined) => {\n\t\t\t\tcheckBlendOptions(params);\n\t\t\t\tconst id = controller.blend({ ...params, ids: ids(params) });\n\t\t\t\tif (!id) fail('Select two or more shapes that share a parent.');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}blendOptions`,\n\t\t\tlabel: 'Blend Options…',\n\t\t\tkeywords: ['blend', 'steps', 'spacing', 'distance', 'smooth color', 'orientation', 'align to path'],\n\t\t\tdescription: 'Changes the spacing (steps, distance or smoothColor), step count, distance, orient-to-spine and linear morph of the given (or selected) blends; their steps regenerate.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, ...BLEND_PROPS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: (VectorBlendOptions & { ids?: string[] }) | undefined) => {\n\t\t\t\tcheckBlendOptions(params);\n\t\t\t\tconst r = controller.setBlendOptions(params ?? {}, { ids: params?.ids });\n\t\t\t\tif (!r.ok) fail(r.message);\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}expandBlend`,\n\t\t\tlabel: 'Expand Blend',\n\t\t\tkeywords: ['blend', 'expand', 'flatten', 'bake'],\n\t\t\tdescription: 'Expands the given (or selected) blends into plain groups of their keys and in-betweens (editable paths with fresh ids). Returns the group ids.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst groups = controller.expandBlend({ ids: params?.ids });\n\t\t\t\tif (!groups.length) fail('Select a blend to expand.');\n\t\t\t\treturn { ids: groups };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}releaseBlend`,\n\t\t\tlabel: 'Release Blend',\n\t\t\tkeywords: ['blend', 'release', 'undo blend'],\n\t\t\tdescription: 'Releases the given (or selected) blends: the in-betweens go and the keys (plus a replaced spine, as an unpainted path) take the blend\\'s place. Returns their ids.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst released = controller.releaseBlend({ ids: params?.ids });\n\t\t\t\tif (!released.length) fail('Select a blend to release.');\n\t\t\t\treturn { ids: released };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}replaceSpine`,\n\t\t\tlabel: 'Replace Spine',\n\t\t\tkeywords: ['blend', 'spine', 'path', 'follow', 'along path'],\n\t\t\tdescription: 'With one blend and one path given (or selected): the path becomes the blend\\'s spine (it is removed) and the keys move onto it, spread evenly by arc length; the in-betweens follow it.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst r = controller.replaceBlendSpine({ ids: params?.ids });\n\t\t\t\tif (!r.ok) fail(r.message);\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}pathfinder`,\n\t\t\tlabel: 'Pathfinder…',\n\t\t\tkeywords: ['divide', 'trim', 'merge', 'crop', 'outline', 'minus back', 'split', 'faces'],\n\t\t\tdescription:\n\t\t\t\t'Pathfinder over the given paths (bottom to top): divide (every face its own shape, painted like the top-most shape over it; open unfilled paths cut), trim (hidden parts removed), merge (trim, then touching parts of one fill joined), crop (the top shape crops the others), outline (outlines cut into open strokes where they meet) or minusBack (the top shape minus everything below). Results replace the paths, grouped when there are several.',\n\t\t\tparams: { type: 'object', properties: { operation: { type: 'string', enum: [...VECTOR_PATHFINDER_OPERATIONS] }, ids: IDS }, required: ['operation'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { operation: VectorPathfinderOperation; ids?: string[] }) => {\n\t\t\t\tif (!VECTOR_PATHFINDER_OPERATIONS.includes(params.operation)) fail(`Unknown Pathfinder operation \"${params.operation}\".`);\n\t\t\t\tconst created = controller.pathfinder(params.operation, { ids: ids(params) });\n\t\t\t\tif (!created.length) fail('Nothing came out: select paths that overlap (two or more, except for divide and outline).');\n\t\t\t\treturn { ids: created, selection: [...controller.getState().selection] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}shapeBuilderFaces`,\n\t\t\tlabel: 'List Shape Builder Faces',\n\t\t\tkeywords: ['shape builder', 'regions', 'faces', 'planar'],\n\t\t\tdescription: 'Lists the faces the given paths divide the plane into: path data, area, a point inside and the ids of the paths filling each (empty when only outlines enclose it).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => ({ faces: controller.getShapeBuilderFaces({ ids: ids(params) }) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}shapeBuilder`,\n\t\t\tlabel: 'Shape Builder',\n\t\t\tkeywords: ['merge faces', 'build shape', 'combine regions', 'delete region'],\n\t\t\tdescription:\n\t\t\t\t'Shape Builder gesture over the faces of the given paths: `points` is the pointer path in document units (one point is a click; [[x, y], …]; use the points from shapeBuilderFaces). Merges the faces it touches into one shape, or with `erase: true` deletes them, the pieces of unfilled open paths and the edges of other outlines (cut where paths meet) within `tolerance`; a deleted edge opens its path there, and edges bounding a deleted face go with it. Shapes covering those faces lose that area. Returns the counts of faces, line pieces and edges.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { points: POINTS, erase: { type: 'boolean' }, tolerance: { type: 'number', minimum: 0 }, ids: IDS },\n\t\t\t\trequired: ['points']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; erase?: boolean; tolerance?: number; ids?: string[] }) => {\n\t\t\t\tconst result = controller.shapeBuilder(params.points.map(([x, y]) => ({ x, y })), { ids: ids(params), erase: params.erase, tolerance: params.tolerance });\n\t\t\t\tcheck(result);\n\t\t\t\treturn { merged: result.merged, faces: result.faces, lines: result.lines, edges: result.edges };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}fillRegion`,\n\t\t\tlabel: 'Fill Region',\n\t\t\tkeywords: ['paint bucket', 'live paint', 'fill area', 'enclosed'],\n\t\t\tdescription:\n\t\t\t\t'Paint bucket: fills the area the visible outlines enclose around `point` (crossings split, nested shapes left as holes) with a new path in the current fill, below the selection or on top. `gap` closes gaps up to that size between loose ends.',\n\t\t\tparams: { type: 'object', properties: { point: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2, description: '[x, y] in document units.' }, gap: { type: 'number', minimum: 0 } }, required: ['point'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { point: [number, number]; gap?: number }) => {\n\t\t\t\tconst id = controller.fillRegion({ x: params.point[0], y: params.point[1] }, { gap: params.gap });\n\t\t\t\tif (!id) fail('No closed region surrounds that point.');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}align`,\n\t\t\tlabel: 'Align…',\n\t\t\tkeywords: ['left', 'right', 'center', 'top', 'bottom', 'middle'],\n\t\t\tdescription: 'Aligns nodes to their combined bounds, or to the artboard (`to: \"artboard\"`, or when only one node is given).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { edge: { type: 'string', enum: ['left', 'center', 'right', 'top', 'middle', 'bottom'] }, to: { type: 'string', enum: ['selection', 'artboard'] }, ids: IDS },\n\t\t\t\trequired: ['edge']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { edge: VectorAlign; to?: 'selection' | 'artboard'; ids?: string[] }) => {\n\t\t\t\tcheck(controller.align(params.edge, { ids: ids(params), to: params.to }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}distribute`,\n\t\t\tlabel: 'Distribute…',\n\t\t\tkeywords: ['space', 'evenly', 'gaps'],\n\t\t\tdescription: 'Spaces three or more nodes with equal gaps.',\n\t\t\tparams: { type: 'object', properties: { direction: { type: 'string', enum: ['horizontal', 'vertical'] }, ids: IDS }, required: ['direction'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { direction: 'horizontal' | 'vertical'; ids?: string[] }) => {\n\t\t\t\tcheck(controller.distribute(params.direction, { ids: ids(params) }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}arrange`,\n\t\t\tlabel: 'Arrange…',\n\t\t\tkeywords: ['order', 'front', 'back', 'forward', 'backward', 'z-index', 'stack'],\n\t\t\tdescription: 'Changes stacking order within each node’s parent.',\n\t\t\tparams: { type: 'object', properties: { order: { type: 'string', enum: ['front', 'forward', 'backward', 'back'] }, ids: IDS }, required: ['order'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { order: VectorArrange; ids?: string[] }) => {\n\t\t\t\tcheck(controller.arrange(params.order, { ids: ids(params) }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}group`,\n\t\t\tlabel: 'Group',\n\t\t\tshortcut: 'Mod+G',\n\t\t\tdescription: 'Groups nodes that share a parent.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, name: { type: 'string' } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; name?: string } | undefined) => {\n\t\t\t\tconst id = controller.group({ ids: ids(params), name: params?.name });\n\t\t\t\tif (!id) fail('Only nodes that share a parent can be grouped.');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}ungroup`,\n\t\t\tlabel: 'Ungroup',\n\t\t\tshortcut: 'Mod+Shift+G',\n\t\t\tdescription: 'Replaces groups with their children.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tcheck(controller.ungroup({ ids: ids(params) }));\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}deleteAnchors`,\n\t\t\tlabel: 'Delete Points',\n\t\t\tkeywords: ['remove', 'anchor', 'point', 'node'],\n\t\t\tdescription:\n\t\t\t\t'Deletes anchors. With `keepShape` (default: the editor setting, on) the neighbouring handles are refitted so the outline keeps its shape; off, the neighbours are joined as they are.',\n\t\t\tparams: { type: 'object', properties: { anchors: ANCHORS, keepShape: { type: 'boolean' } } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { anchors?: VectorAnchorRef[]; keepShape?: boolean } | undefined) => {\n\t\t\t\tcheck(controller.deleteAnchors(anchorsOf(params?.anchors), { keepShape: params?.keepShape }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}moveAnchor`,\n\t\t\tlabel: 'Move Point…',\n\t\t\tkeywords: ['anchor', 'drag', 'curvature'],\n\t\t\tdescription: 'Moves one anchor to (x, y) in document units. `curvature: true` bends its two segments like the Curvature tool instead of carrying its handles along.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { nodeId: { type: 'string' }, subpath: { type: 'integer', minimum: 0 }, index: { type: 'integer', minimum: 0 }, x: { type: 'number' }, y: { type: 'number' }, curvature: { type: 'boolean' } },\n\t\t\t\trequired: ['nodeId', 'subpath', 'index', 'x', 'y']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: VectorAnchorRef & { x: number; y: number; curvature?: boolean }) => {\n\t\t\t\tcheck(controller.moveAnchor({ nodeId: params.nodeId, subpath: params.subpath, index: params.index }, { x: params.x, y: params.y }, { curvature: params.curvature }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}bendSegment`,\n\t\t\tlabel: 'Bend Segment…',\n\t\t\tkeywords: ['curve', 'segment', 'drag'],\n\t\t\tdescription: 'Bends segment `segment` (from anchor `segment` to the next) so the curve passes through (x, y) at parameter `t` (default 0.5).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tnodeId: { type: 'string' },\n\t\t\t\t\tsubpath: { type: 'integer', minimum: 0 },\n\t\t\t\t\tsegment: { type: 'integer', minimum: 0 },\n\t\t\t\t\tx: { type: 'number' },\n\t\t\t\t\ty: { type: 'number' },\n\t\t\t\t\tt: { type: 'number', minimum: 0, maximum: 1 }\n\t\t\t\t},\n\t\t\t\trequired: ['nodeId', 'subpath', 'segment', 'x', 'y']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId: string; subpath: number; segment: number; x: number; y: number; t?: number }) => {\n\t\t\t\tcheck(controller.bendSegment({ nodeId: params.nodeId, subpath: params.subpath, segment: params.segment }, { x: params.x, y: params.y }, params.t));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}join`,\n\t\t\tlabel: 'Join',\n\t\t\tshortcut: 'Mod+J',\n\t\t\tkeywords: ['connect', 'close', 'merge', 'endpoints'],\n\t\t\tdescription: 'Joins the open subpaths of paths nearest endpoints first (ends within `tolerance` merge); a single open path is closed.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, tolerance: { type: 'number', minimum: 0 } } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; tolerance?: number } | undefined) => {\n\t\t\t\tcheck(controller.joinPaths({ ids: params?.ids ? ids(params) : undefined, tolerance: params?.tolerance }));\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}average`,\n\t\t\tlabel: 'Average Points…',\n\t\t\tshortcut: 'Mod+Alt+J',\n\t\t\tkeywords: ['align', 'points', 'anchors', 'collapse'],\n\t\t\tdescription: 'Moves anchors onto their average position: the same y (`horizontal`), the same x (`vertical`) or the same point (`both`, default).',\n\t\t\tparams: { type: 'object', properties: { axis: { type: 'string', enum: ['horizontal', 'vertical', 'both'] }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { axis?: VectorAverageAxis; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tcheck(controller.averageAnchors(params?.axis ?? 'both', anchorsOf(params?.anchors)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeRedundantPoints`,\n\t\t\tlabel: 'Remove Redundant Points',\n\t\t\tkeywords: ['simplify', 'clean up', 'anchors', 'collinear'],\n\t\t\tdescription: 'Drops anchors that can go without moving the outline more than `tolerance` document units (default 0.5).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, tolerance: { type: 'number', minimum: 0 } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; tolerance?: number } | undefined) => {\n\t\t\t\tcheck(controller.removeRedundantPoints({ ids: params?.ids ? ids(params) : undefined, tolerance: params?.tolerance }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}smooth`,\n\t\t\tlabel: 'Smooth Path',\n\t\t\tkeywords: ['round', 'soften', 'handles', 'curves'],\n\t\t\tdescription: 'Pulls the handles of paths (or of the selected points) towards smooth tangents by `amount` (0–1, default 1).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, amount: { type: 'number', minimum: 0, maximum: 1 }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; amount?: number; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tcheck(controller.smoothPaths({ ids: params?.ids ? ids(params) : undefined, amount: params?.amount, refs: params?.anchors }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}cut`,\n\t\t\tlabel: 'Cut Path (Scissors)…',\n\t\t\tkeywords: ['scissors', 'split', 'open', 'break'],\n\t\t\tdescription: 'Scissors: cuts path `nodeId` at the outline point nearest (x, y), or cuts at `anchors`. A closed path opens; an open one splits in two.',\n\t\t\tparams: { type: 'object', properties: { nodeId: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId?: string; x?: number; y?: number; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tif (params?.nodeId !== undefined) {\n\t\t\t\t\tif (!controller.getNode(params.nodeId)) fail(`There is no node \"${params.nodeId}\".`);\n\t\t\t\t\tif (params.x === undefined || params.y === undefined) fail('Pass x and y with nodeId.');\n\t\t\t\t\tconst created = controller.cutPathAt(params.nodeId, { x: params.x!, y: params.y! });\n\t\t\t\t\tif (!created) fail('Nothing to cut there (the end of an open path, or a locked path).');\n\t\t\t\t\treturn { ids: created };\n\t\t\t\t}\n\t\t\t\tcheck(controller.cutAtAnchors(anchorsOf(params?.anchors)));\n\t\t\t\treturn { ids: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}knife`,\n\t\t\tlabel: 'Knife…',\n\t\t\tkeywords: ['slice', 'cut', 'split', 'divide'],\n\t\t\tdescription: 'Cuts closed paths along a polyline wherever it crosses them edge to edge (no gap between pieces). Cuts `ids`, else the selection, else every path the line crosses.',\n\t\t\tparams: { type: 'object', properties: { points: { ...POINTS, minItems: 2 }, ids: IDS }, required: ['points'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; ids?: string[] }) => {\n\t\t\t\tconst created = controller.knife(params.points.map(([x, y]) => ({ x, y })), { ids: params.ids ? ids(params) : undefined });\n\t\t\t\tif (!created.length) fail('The knife did not cross any closed path from edge to edge.');\n\t\t\t\treturn { ids: created };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}erase`,\n\t\t\tlabel: 'Erase…',\n\t\t\tkeywords: ['eraser', 'rub out', 'remove'],\n\t\t\tdescription:\n\t\t\t\t'Erases a round stroke of diameter `size` (default: the eraser size setting) along a polyline: filled shapes lose the area, outlines are cut under it. Erases from `ids`, else the selection, else every path it reaches.',\n\t\t\tparams: { type: 'object', properties: { points: POINTS, size: { type: 'number', exclusiveMinimum: 0 }, ids: IDS }, required: ['points'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; size?: number; ids?: string[] }) => {\n\t\t\t\tconst changed = controller.erase(params.points.map(([x, y]) => ({ x, y })), { size: params.size, ids: params.ids ? ids(params) : undefined });\n\t\t\t\tif (!changed.length) fail('The eraser did not touch any path.');\n\t\t\t\treturn { ids: changed.filter((id) => controller.getNode(id)) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setEditing`,\n\t\t\tlabel: 'Path Editing Options…',\n\t\t\tkeywords: ['settings', 'curvature', 'pencil', 'smoothing', 'lazy mouse', 'shapes', 'eraser'],\n\t\t\tdescription:\n\t\t\t\t'Sets how editing behaves: `keepShapeOnDelete`, `curvatureMoves` (anchor drags bend like the Curvature tool), `pencilSmoothing` (lazy mouse, 0–1), `recognizeShapes` (pencil scribbles become lines, rectangles, ellipses, polygons), `eraserSize` and `pencilPressure` (`pen`: record pen pressure on pencil strokes as a width profile, `all`: any pointer reporting pressure, `off`).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tkeepShapeOnDelete: { type: 'boolean' },\n\t\t\t\t\tcurvatureMoves: { type: 'boolean' },\n\t\t\t\t\tpencilSmoothing: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\trecognizeShapes: { type: 'boolean' },\n\t\t\t\t\teraserSize: { type: 'number', exclusiveMinimum: 0 },\n\t\t\t\t\tpencilPressure: { type: 'string', enum: ['pen', 'all', 'off'] }\n\t\t\t\t}\n\t\t\t},\n\t\t\trun: (_ctx: unknown, params: Record<string, unknown> | undefined) => {\n\t\t\t\tconst patch: Record<string, unknown> = {};\n\t\t\t\tfor (const key of ['keepShapeOnDelete', 'curvatureMoves', 'pencilSmoothing', 'recognizeShapes', 'eraserSize', 'pencilPressure']) if (params?.[key] !== undefined) patch[key] = params[key];\n\t\t\t\tcontroller.setEditing(patch);\n\t\t\t\treturn { editing: controller.getState().editing };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setTool`,\n\t\t\tlabel: 'Choose Tool…',\n\t\t\tkeywords: ['pen', 'pencil', 'select', 'rectangle', 'ellipse'],\n\t\t\tdescription: 'Switches the canvas tool.',\n\t\t\tparams: { type: 'object', properties: { tool: { type: 'string', enum: [...VECTOR_TOOLS] } }, required: ['tool'] },\n\t\t\trun: (_ctx: unknown, params: { tool: VectorTool }) => {\n\t\t\t\tcontroller.setTool(params.tool);\n\t\t\t\treturn { tool: params.tool };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportSvg`,\n\t\t\tlabel: 'Export SVG',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['download', 'save', 'markup'],\n\t\t\tdescription: 'Returns the document as SVG markup.',\n\t\t\tparams: { type: 'object', properties: { precision: { type: 'integer', minimum: 0, maximum: 8 } } },\n\t\t\trun: (_ctx: unknown, params: { precision?: number } | undefined) => ({ svg: controller.toSvg({ precision: params?.precision }) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}importSvg`,\n\t\t\tlabel: 'Import SVG…',\n\t\t\tkeywords: ['open', 'load', 'paste', 'markup'],\n\t\t\tdescription: 'Adds the shapes of SVG markup on top of the document (or replaces it with `replace: true`).',\n\t\t\tparams: { type: 'object', properties: { svg: { type: 'string' }, replace: { type: 'boolean' } }, required: ['svg'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { svg: string; replace?: boolean }) => {\n\t\t\t\tcheck(params.replace ? controller.loadSvg(params.svg) : controller.importSvg(params.svg));\n\t\t\t\treturn { nodes: controller.getState().document.nodes.length, selection: controller.getState().selection };\n\t\t\t}\n\t\t}\n\t];\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/vector/index.cjs","../../src/vector/gradientTool.ts","../../src/vector/blendGroup.ts","../../src/vector/distort.ts","../../src/vector/snap.ts","../../src/vector/pathEdit.ts","../../src/vector/pathCut.ts","../../src/vector/ink.ts","../../src/vector/builder.ts","../../src/vector/controller.ts","../../src/vector/render.ts","../../src/vector/commands.ts"],"names":["lines","near","fi","r","key","node","fmt","corners","list"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACA;ACvRO,IAAM,yBAAA,EAA2B,EAAA;AACjC,IAAM,6BAAA,EAA+B,CAAA;AAErC,IAAM,w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AAC3C,MAAA;AAC0D,MAAA;AACf,QAAA;AACC,QAAA;AACtD,MAAA;AACD,IAAA;AACD,EAAA;AACD;AX+mP6D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/vector/index.cjs","sourcesContent":[null,"/**\n * The Gradient tool's on-canvas annotator: a bar from the start (or centre) handle to the end (or\n * radius) handle with the colour stops under it and midpoint diamonds above it, plus a radial,\n * conic or diamond gradient's extent outline, aspect handle and (radial) focal point. All in\n * screen pixels, for hit-testing and the overlay.\n *\n * After vectorcraft `crates/tools/src/xform/gradient.rs` (`Annotator`: stop chips below the bar,\n * midpoints above it, a stop dragged off the bar is removed, a click on the bar adds one), ArtCraft,\n * MIT OR Apache-2.0 — see THIRD_PARTY_NOTICES.md.\n */\nimport { collectPathNodes, findVectorNode, vectorWorldMatrix, IDENTITY_MATRIX, multiplyMatrices, type AffineMatrix } from './geometry.js';\nimport { vectorPathLocalBounds } from './svg.js';\nimport {\n\tisCentredVectorGradient,\n\tisVectorGradient,\n\tsortedVectorGradientStops,\n\tvectorGradientHandles,\n\tvectorGradientMatrix,\n\tvectorGradientMidpointPosition,\n\ttype VectorGradientHandle\n} from './gradient.js';\nimport type { Vec2, VectorBounds, VectorDocument, VectorGradient, VectorGradientStop, VectorPathNode, VectorViewport } from './types.js';\n\n/** Which paint of the selection the Gradient tool and the gradient editor work on. */\nexport type VectorGradientTarget = 'fill' | 'stroke';\n\n/** A part of the annotator under the pointer. */\nexport type VectorGradientPart =\n\t| { kind: 'handle'; handle: VectorGradientHandle }\n\t| { kind: 'stop'; index: number }\n\t| { kind: 'midpoint'; index: number }\n\t/** The bar at `offset` (0–1): a click adds a stop there, a drag moves the gradient. */\n\t| { kind: 'bar'; offset: number };\n\n/** Distance of the stop chips below the bar, the midpoint diamonds above it (screen pixels). */\nexport const VECTOR_GRADIENT_STOP_GAP = 12;\nexport const VECTOR_GRADIENT_MIDPOINT_GAP = 9;\n/** How far off the bar a dragged stop goes before it is removed (screen pixels). */\nexport const VECTOR_GRADIENT_OFF_BAR = 24;\nconst STOP_HIT = 6;\nconst MIDPOINT_HIT = 5;\nconst HANDLE_HIT = 6;\nconst BAR_HIT = 5;\n\nexport interface VectorGradientAnnotator {\n\tnodeId: string;\n\ttarget: VectorGradientTarget;\n\tgradient: VectorGradient;\n\t/** The path's box in its own space. */\n\tbounds: VectorBounds | null;\n\t/** The path's own space → document. */\n\tworld: AffineMatrix;\n\t/** Screen positions of the handles. */\n\tstart: Vec2;\n\tend: Vec2;\n\t/** Radial, conic and diamond gradients. */\n\taspect: Vec2 | null;\n\t/** Radial gradients. */\n\tfocal: Vec2 | null;\n\t/** Unit normal to the bar towards the stop chips (screen). */\n\tnormal: Vec2;\n\t/** Stops (sorted, as the gradient stores them) with their chips' screen positions. */\n\tstops: (VectorGradientStop & { index: number; x: number; y: number })[];\n\t/** The midpoint diamond after each stop but the last (screen). */\n\tmidpoints: { index: number; x: number; y: number; midpoint: number }[];\n\t/** Screen path of the extent: an ellipse (radial, conic) or a rhombus (diamond). */\n\textent: string | null;\n}\n\nconst fmt = (n: number) => Math.round(n * 100) / 100;\nconst apply = (m: AffineMatrix, p: Vec2): Vec2 => ({ x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] });\n\n/** The path whose `target` paint the annotator shows: the first path of the selection with a gradient there. */\nexport function vectorGradientTargetPath(doc: VectorDocument, selection: readonly string[], target: VectorGradientTarget): VectorPathNode | null {\n\tfor (const id of selection) {\n\t\tconst node = findVectorNode(doc.nodes, id);\n\t\tif (!node) continue;\n\t\tconst path = collectPathNodes(node).find((p) => isVectorGradient(p[target]));\n\t\tif (path) return path;\n\t}\n\treturn null;\n}\n\n/** The annotator of the selection's gradient (`target` paint), in screen pixels, or null when it has none. */\nexport function getVectorGradientAnnotator(\n\tdoc: VectorDocument,\n\tselection: readonly string[],\n\tviewport: VectorViewport,\n\ttarget: VectorGradientTarget\n): VectorGradientAnnotator | null {\n\tconst path = vectorGradientTargetPath(doc, selection, target);\n\tif (!path) return null;\n\tconst gradient = path[target] as VectorGradient;\n\tconst world = vectorWorldMatrix(doc.nodes, path.id) ?? IDENTITY_MATRIX;\n\tconst screen = multiplyMatrices(world, [viewport.zoom, 0, 0, viewport.zoom, viewport.x, viewport.y]);\n\tconst bounds = vectorPathLocalBounds(path);\n\tconst h = vectorGradientHandles(gradient, bounds, screen);\n\tconst v = { x: h.end.x - h.start.x, y: h.end.y - h.start.y };\n\tconst len = Math.hypot(v.x, v.y);\n\tconst normal = len > 1e-9 ? { x: -v.y / len, y: v.x / len } : { x: 0, y: 1 };\n\tconst at = (t: number, gap: number) => ({ x: h.start.x + v.x * t + normal.x * gap, y: h.start.y + v.y * t + normal.y * gap });\n\tconst sorted = sortedVectorGradientStops(gradient);\n\tconst stops = sorted.map((s, index) => ({ ...s, index, ...at(s.offset, VECTOR_GRADIENT_STOP_GAP) }));\n\tconst midpoints = sorted.slice(0, -1).flatMap((s, index) => {\n\t\tconst pos = vectorGradientMidpointPosition(sorted, index);\n\t\treturn pos === null || sorted[index + 1].offset - s.offset < 1e-6 ? [] : [{ index, midpoint: s.midpoint ?? 0.5, ...at(pos, -VECTOR_GRADIENT_MIDPOINT_GAP) }];\n\t});\n\tlet extent: string | null = null;\n\tif (isCentredVectorGradient(gradient.type)) {\n\t\tconst frame = multiplyMatrices(vectorGradientMatrix(gradient, bounds), screen);\n\t\tconst pts =\n\t\t\tgradient.type === 'diamond'\n\t\t\t\t? [{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }, { x: 0, y: -1 }]\n\t\t\t\t: Array.from({ length: 48 }, (_, k) => ({ x: Math.cos((k * Math.PI) / 24), y: Math.sin((k * Math.PI) / 24) }));\n\t\textent = `M${pts.map((p) => apply(frame, p)).map((p) => `${fmt(p.x)} ${fmt(p.y)}`).join('L')}Z`;\n\t}\n\treturn { nodeId: path.id, target, gradient, bounds, world, start: h.start, end: h.end, aspect: h.aspect, focal: h.focal, normal, stops, midpoints, extent };\n}\n\n/** Where `p` lies relative to the bar: offset along it (0 at the start, 1 at the end) and distance towards the stop chips. */\nexport function vectorGradientBarPosition(a: Pick<VectorGradientAnnotator, 'start' | 'end' | 'normal'>, p: Vec2): { offset: number; across: number } {\n\tconst v = { x: a.end.x - a.start.x, y: a.end.y - a.start.y };\n\tconst l2 = v.x * v.x + v.y * v.y;\n\tconst d = { x: p.x - a.start.x, y: p.y - a.start.y };\n\tif (l2 < 1e-12) return { offset: 0, across: Math.hypot(d.x, d.y) };\n\treturn { offset: (d.x * v.x + d.y * v.y) / l2, across: d.x * a.normal.x + d.y * a.normal.y };\n}\n\n/** The annotator part under screen point `p`: stops, then midpoints, the handles and the bar. */\nexport function hitVectorGradientAnnotator(a: VectorGradientAnnotator, p: Vec2): VectorGradientPart | null {\n\tconst near = (q: Vec2 | null, r: number) => !!q && Math.hypot(q.x - p.x, q.y - p.y) <= r;\n\tfor (let i = a.stops.length - 1; i >= 0; i--) if (near(a.stops[i], STOP_HIT)) return { kind: 'stop', index: a.stops[i].index };\n\tfor (const m of a.midpoints) if (near(m, MIDPOINT_HIT)) return { kind: 'midpoint', index: m.index };\n\tconst centred = isCentredVectorGradient(a.gradient.type);\n\tif (near(a.end, HANDLE_HIT)) return { kind: 'handle', handle: centred ? 'radius' : 'end' };\n\t// The focal point sits on the centre until moved: grab it with Alt there (see the controller).\n\tif (a.focal && near(a.focal, HANDLE_HIT) && !near(a.start, 1)) return { kind: 'handle', handle: 'focal' };\n\tif (near(a.start, HANDLE_HIT)) return { kind: 'handle', handle: 'start' };\n\tif (near(a.aspect, HANDLE_HIT)) return { kind: 'handle', handle: 'aspect' };\n\tconst { offset, across } = vectorGradientBarPosition(a, p);\n\tif (offset >= 0 && offset <= 1 && across >= -BAR_HIT && across <= VECTOR_GRADIENT_STOP_GAP + STOP_HIT) return { kind: 'bar', offset };\n\treturn null;\n}\n","// Portions ported from vectorcraft-main/crates/doc/src/blend.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\n/**\n * Live blend groups: a group whose `blend` is set keeps its key shapes as children and\n * regenerates the in-betweens (`blendStep` children, locked) whenever a key or the options\n * change. Steps follow the straight lines between the keys' centres, or a replaced spine.\n *\n * - **Spacing** (`vectorBlendStepCount`): a number of steps per pair of keys, a fixed distance\n * along the spine, or smooth colour — one step per two levels of the largest colour channel\n * difference, by distance when the colours match.\n * - **Spine**: with a replaced spine the keys sit along it, spread evenly by arc length; each\n * step is moved by how far the spine bends away from the chord between its keys, so a step\n * lands on the spine and the keys stay where they are. Orient to spine also turns the steps\n * by how much the spine's direction differs from the keys' (keys keep their orientation);\n * without a replaced spine the steps run straight and keep their orientation.\n */\nimport type { Point } from '../canvas/types.js';\nimport { hexToRgba } from '../tokens/color.js';\nimport { segmentPoint, segmentTangent } from '../canvas/pathops/bezier.js';\nimport { createVectorMorph, type VectorMorph } from './blend.js';\nimport {\n\tcollectPathNodes,\n\tIDENTITY_MATRIX,\n\trotateMatrix,\n\tsubpathSegment,\n\tsubpathSegmentCount,\n\ttransformVectorNode,\n\ttranslateMatrix,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\tvectorNodeBounds,\n\ttype AffineMatrix\n} from './geometry.js';\nimport type { VectorBlend, VectorBlendOptions, VectorGroupNode, VectorNode, VectorPaint, VectorPathNode, VectorSubpath } from './types.js';\n\nexport const DEFAULT_VECTOR_BLEND_STEPS = 5;\nexport const DEFAULT_VECTOR_BLEND_DISTANCE = 20;\n/** Most steps between two keys. */\nexport const VECTOR_BLEND_MAX_STEPS = 1000;\n/** Most steps smooth colour makes between two keys. */\nexport const VECTOR_BLEND_MAX_SMOOTH_STEPS = 256;\n\n/** Whether a node is a live blend group. */\nexport function isVectorBlendGroup(node: VectorNode | null | undefined): node is VectorGroupNode & { blend: VectorBlend } {\n\treturn !!node && node.type === 'group' && !!node.blend;\n}\n\n/** The keys of a blend group (its children that are not generated steps), in stacking order. */\nexport function vectorBlendKeys(group: VectorGroupNode): VectorNode[] {\n\treturn group.children.filter((c) => !c.blendStep);\n}\n\n/** The full options of a blend, defaults filled in. */\nexport function resolveVectorBlendOptions(options: VectorBlendOptions | null | undefined): Required<VectorBlendOptions> {\n\treturn {\n\t\tspacing: options?.spacing ?? 'steps',\n\t\tsteps: options?.steps ?? DEFAULT_VECTOR_BLEND_STEPS,\n\t\tdistance: options?.distance ?? DEFAULT_VECTOR_BLEND_DISTANCE,\n\t\torientToSpine: options?.orientToSpine ?? false,\n\t\tlinear: options?.linear ?? false\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Step counts\n// ---------------------------------------------------------------------------\n\nfunction paintColors(p: VectorPaint | undefined): string[] {\n\tif (typeof p === 'string') return [p];\n\tif (p && typeof p === 'object') return p.stops.map((s) => s.color);\n\treturn [];\n}\n\n/** Largest channel difference (0–1) between the colours of two shapes' fills and strokes. */\nexport function vectorBlendColorDistance(a: VectorNode, b: VectorNode): number {\n\tconst pa = collectPathNodes(a)[0];\n\tconst pb = collectPathNodes(b)[0];\n\tif (!pa || !pb) return 0;\n\tlet d = 0;\n\tfor (const key of ['fill', 'stroke'] as const) {\n\t\tconst ca = paintColors(pa[key]);\n\t\tconst cb = paintColors(pb[key]);\n\t\tca.forEach((c, i) => {\n\t\t\tconst other = cb[i] ?? cb[0];\n\t\t\tif (other === undefined) return;\n\t\t\tconst x = hexToRgba(c);\n\t\t\tconst y = hexToRgba(other);\n\t\t\tif (!x || !y) return;\n\t\t\td = Math.max(d, Math.abs(x.r - y.r), Math.abs(x.g - y.g), Math.abs(x.b - y.b), Math.abs(x.a - y.a));\n\t\t});\n\t}\n\treturn d;\n}\n\nconst centreOf = (n: VectorNode): Point => {\n\tconst b = vectorNodeBounds(n);\n\treturn b ? [b.x + b.width / 2, b.y + b.height / 2] : [0, 0];\n};\n\n/** Number of in-betweens between two keys `length` apart along the spine. */\nexport function vectorBlendStepCount(a: VectorNode, b: VectorNode, options: VectorBlendOptions | null | undefined, length: number): number {\n\tconst o = resolveVectorBlendOptions(options);\n\tif (o.spacing === 'distance') {\n\t\tconst d = Math.max(0.01, o.distance);\n\t\treturn Math.min(VECTOR_BLEND_MAX_STEPS, Math.max(0, Math.round(length / d) - 1));\n\t}\n\tif (o.spacing === 'smoothColor') {\n\t\tconst cd = vectorBlendColorDistance(a, b);\n\t\tif (cd > 1 / 255) return Math.min(VECTOR_BLEND_MAX_SMOOTH_STEPS, Math.max(1, Math.ceil((cd * 255) / 2)));\n\t\t// Same colours: base the count on how far the shapes are apart.\n\t\tconst ba = vectorNodeBounds(a);\n\t\tconst bb = vectorNodeBounds(b);\n\t\tconst dist =\n\t\t\tba && bb\n\t\t\t\t? Math.max(Math.abs(ba.x - bb.x), Math.abs(ba.y - bb.y), Math.abs(ba.x + ba.width - bb.x - bb.width), Math.abs(ba.y + ba.height - bb.y - bb.height))\n\t\t\t\t: length;\n\t\treturn Math.min(VECTOR_BLEND_MAX_SMOOTH_STEPS, Math.max(1, Math.ceil(dist / 2)));\n\t}\n\treturn Math.min(VECTOR_BLEND_MAX_STEPS, Math.max(1, Math.round(Number.isFinite(o.steps) ? o.steps : DEFAULT_VECTOR_BLEND_STEPS)));\n}\n\n// ---------------------------------------------------------------------------\n// Spine\n// ---------------------------------------------------------------------------\n\n/** A subpath flattened to a polyline with cumulative arc lengths and tangent angles. */\nexport interface VectorBlendRail {\n\tpts: Point[];\n\tcum: number[];\n\tangles: number[];\n\ttotal: number;\n\tclosed: boolean;\n}\n\n/** Flattens a spine subpath (32 samples per curve). Null with fewer than two distinct points. */\nexport function vectorBlendRail(sp: VectorSubpath): VectorBlendRail | null {\n\tconst pts: Point[] = [];\n\tconst angles: number[] = [];\n\tconst push = (p: Point, tangent: Point) => {\n\t\tconst last = pts[pts.length - 1];\n\t\tif (last && Math.hypot(p[0] - last[0], p[1] - last[1]) < 1e-9) return;\n\t\tpts.push(p);\n\t\tangles.push(Math.atan2(tangent[1], tangent[0]));\n\t};\n\tconst count = subpathSegmentCount(sp);\n\tfor (let i = 0; i < count; i++) {\n\t\tconst seg = subpathSegment(sp, i);\n\t\tconst samples = seg.length === 2 ? 1 : 32;\n\t\tif (i === 0) push(seg[0], segmentTangent(seg, 0));\n\t\tfor (let k = 1; k <= samples; k++) push(segmentPoint(seg, k / samples), segmentTangent(seg, k / samples));\n\t}\n\tif (pts.length < 2) return null;\n\tconst cum = [0];\n\tfor (let i = 1; i < pts.length; i++) cum.push(cum[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));\n\treturn { pts, cum, angles, total: cum[cum.length - 1], closed: sp.closed };\n}\n\n/** Point and direction (radians) at arc length `s` (clamped; a closed rail wraps). */\nexport function vectorBlendRailAt(rail: VectorBlendRail, s: number): { point: Point; angle: number } {\n\tlet len = Number.isFinite(s) ? s : 0;\n\tif (rail.closed && rail.total > 0) len = ((len % rail.total) + rail.total) % rail.total;\n\tlen = Math.min(rail.total, Math.max(0, len));\n\tlet lo = 0;\n\tlet hi = rail.cum.length - 1;\n\twhile (hi - lo > 1) {\n\t\tconst mid = (lo + hi) >> 1;\n\t\tif (rail.cum[mid] <= len) lo = mid;\n\t\telse hi = mid;\n\t}\n\tconst span = rail.cum[hi] - rail.cum[lo];\n\tconst u = span > 1e-12 ? (len - rail.cum[lo]) / span : 0;\n\tconst a = rail.pts[lo];\n\tconst b = rail.pts[hi];\n\treturn { point: [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u], angle: Math.atan2(b[1] - a[1], b[0] - a[0]) };\n}\n\n/**\n * The spine of a blend in the group's space and where along it each key sits: the replaced\n * spine (keys spread evenly by arc length) or the straight lines between the keys' centres.\n */\nexport function vectorBlendSpine(group: VectorGroupNode): { spine: VectorSubpath; rail: VectorBlendRail; stops: number[]; replaced: boolean } | null {\n\tconst keys = vectorBlendKeys(group);\n\tif (keys.length < 2) return null;\n\tconst stored = group.blend?.spine;\n\tif (stored && stored.anchors.length >= 2) {\n\t\tconst rail = vectorBlendRail(stored);\n\t\tif (rail) {\n\t\t\tconst end = rail.closed ? rail.total * (1 - 1 / keys.length) : rail.total;\n\t\t\treturn { spine: stored, rail, stops: keys.map((_, i) => (end * i) / (keys.length - 1)), replaced: true };\n\t\t}\n\t}\n\tconst centres = keys.map(centreOf);\n\tconst spine: VectorSubpath = { closed: false, anchors: centres.map((c) => ({ x: c[0], y: c[1] })) };\n\tconst stops = [0];\n\tfor (let i = 1; i < centres.length; i++) stops.push(stops[i - 1] + Math.hypot(centres[i][0] - centres[i - 1][0], centres[i][1] - centres[i - 1][1]));\n\tconst rail = vectorBlendRail(spine) ?? { pts: centres, cum: stops, angles: centres.map(() => 0), total: stops[stops.length - 1], closed: false };\n\treturn { spine, rail, stops, replaced: false };\n}\n\n/** Where key `i` of a blend with spine `spine` should sit: its stop on the spine. */\nexport function vectorBlendKeyTargets(group: VectorGroupNode): Point[] {\n\tconst s = vectorBlendSpine(group);\n\treturn s ? s.stops.map((stop) => vectorBlendRailAt(s.rail, stop).point) : [];\n}\n\n// ---------------------------------------------------------------------------\n// Generating steps\n// ---------------------------------------------------------------------------\n\nconst morphCache = new WeakMap<VectorNode, WeakMap<VectorNode, Map<string, VectorMorph>>>();\n\nfunction morphFor(a: VectorNode, b: VectorNode, blend: VectorBlend): VectorMorph {\n\tconst starts = [blend.starts?.[a.id] ?? null, blend.starts?.[b.id] ?? null] as const;\n\tconst key = JSON.stringify([!!blend.linear, starts]);\n\tlet inner = morphCache.get(a);\n\tif (!inner) morphCache.set(a, (inner = new WeakMap()));\n\tlet byKey = inner.get(b);\n\tif (!byKey) inner.set(b, (byKey = new Map()));\n\tlet morph = byKey.get(key);\n\tif (!morph) byKey.set(key, (morph = createVectorMorph(a, b, { linear: blend.linear, starts })));\n\treturn morph;\n}\n\nconst wrapAngle = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));\n\n/** A step marked as generated: locked, flagged, ids derived from `id`. */\nfunction asStep(node: VectorNode, id: string): VectorNode {\n\tconst rename = (n: VectorNode, nid: string): VectorNode =>\n\t\tn.type === 'group' ? { ...n, id: nid, children: n.children.map((c, i) => rename(c, `${nid}.${i}`)) } : { ...n, id: nid };\n\treturn { ...rename(node, id), blendStep: true, locked: true };\n}\n\n/**\n * A blend group's children with fresh steps: each key followed by the in-betweens to the next,\n * bottom to top. Groups with fewer than two keys keep just their keys.\n */\nexport function generateVectorBlendChildren(group: VectorGroupNode): VectorNode[] {\n\tconst keys = vectorBlendKeys(group);\n\tconst blend = group.blend;\n\tif (!blend || keys.length < 2) return keys;\n\tconst spine = vectorBlendSpine(group);\n\tif (!spine) return keys;\n\tconst out: VectorNode[] = [];\n\tlet counter = 0;\n\tkeys.forEach((a, i) => {\n\t\tout.push(a);\n\t\tconst b = keys[i + 1];\n\t\tif (!b) return;\n\t\tconst s0 = spine.stops[i];\n\t\tconst s1 = spine.stops[i + 1];\n\t\tconst n = vectorBlendStepCount(a, b, blend, Math.abs(s1 - s0));\n\t\tconst morph = morphFor(a, b, blend);\n\t\tconst p0 = vectorBlendRailAt(spine.rail, s0);\n\t\tconst p1 = vectorBlendRailAt(spine.rail, s1);\n\t\tfor (let j = 1; j <= n; j++) {\n\t\t\tconst t = j / (n + 1);\n\t\t\tlet step = morph.at(t);\n\t\t\tif (spine.replaced) {\n\t\t\t\tconst p = vectorBlendRailAt(spine.rail, s0 + (s1 - s0) * t);\n\t\t\t\tconst dx = p.point[0] - (p0.point[0] + (p1.point[0] - p0.point[0]) * t);\n\t\t\t\tconst dy = p.point[1] - (p0.point[1] + (p1.point[1] - p0.point[1]) * t);\n\t\t\t\tlet m: AffineMatrix = Math.hypot(dx, dy) > 1e-9 ? translateMatrix(dx, dy) : IDENTITY_MATRIX;\n\t\t\t\tif (blend.orientToSpine) {\n\t\t\t\t\tconst turn = wrapAngle(p.angle - (p0.angle + wrapAngle(p1.angle - p0.angle) * t));\n\t\t\t\t\tif (Math.abs(turn) > 1e-9) {\n\t\t\t\t\t\tconst c = centreOf(step);\n\t\t\t\t\t\tconst origin = { x: c[0] + m[4], y: c[1] + m[5] };\n\t\t\t\t\t\tm = multiplyMatrices(m, rotateMatrix((turn * 180) / Math.PI, origin));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (m !== IDENTITY_MATRIX) step = transformVectorNode(step, m);\n\t\t\t}\n\t\t\tout.push(asStep(step, `${group.id}~${++counter}`));\n\t\t}\n\t});\n\treturn out;\n}\n\nconst childrenCache = new WeakMap<VectorNode, { sig: string; keys: VectorNode[]; children: VectorNode[] }>();\n\nconst sameList = (a: readonly VectorNode[], b: readonly VectorNode[]) => a.length === b.length && a.every((n, i) => n === b[i]);\n\nfunction blendChildren(group: VectorGroupNode): VectorNode[] {\n\tconst keys = vectorBlendKeys(group);\n\tconst sig = `${group.id}|${JSON.stringify(group.blend)}`;\n\tconst cached = keys[0] ? childrenCache.get(keys[0]) : undefined;\n\tlet children: VectorNode[];\n\tif (cached && cached.sig === sig && sameList(cached.keys, keys)) children = cached.children;\n\telse {\n\t\tchildren = generateVectorBlendChildren(group);\n\t\tif (keys[0]) childrenCache.set(keys[0], { sig, keys, children });\n\t}\n\treturn sameList(children, group.children) ? group.children : children;\n}\n\n/**\n * Nodes with every blend group's steps brought up to date (nested blends first). Returns the\n * same array when nothing changed; steps are cached per set of keys, so calling this after\n * every edit is cheap.\n */\nexport function refreshVectorBlends(nodes: readonly VectorNode[]): VectorNode[] {\n\tlet changed = false;\n\tconst out = nodes.map((n) => {\n\t\tif (n.type !== 'group') return n;\n\t\tconst inner = refreshVectorBlends(n.children);\n\t\tlet next: VectorGroupNode = inner === n.children ? n : { ...n, children: inner };\n\t\tif (next.blend) {\n\t\t\tconst children = blendChildren(next);\n\t\t\tif (children !== next.children) next = { ...next, children };\n\t\t}\n\t\tif (next !== n) changed = true;\n\t\treturn next;\n\t});\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\n/** A step or key with the generated flags dropped and fresh ids. */\nfunction plain(node: VectorNode, newId: () => string): VectorNode {\n\tconst { blendStep: _s, locked: _l, ...rest } = node;\n\tconst renamed = { ...rest, id: newId() } as VectorNode;\n\tif (renamed.type === 'group') renamed.children = renamed.children.map((c) => plain(c, newId));\n\treturn renamed;\n}\n\n/** Expand: the blend as a plain group of its keys and steps (steps get fresh ids). */\nexport function expandVectorBlend(group: VectorGroupNode, newId: () => string): VectorGroupNode {\n\tconst { blend: _b, ...rest } = group;\n\treturn { ...rest, children: group.children.map((c) => (c.blendStep ? plain(c, newId) : c)) };\n}\n\n/**\n * Release: the blend's keys in the group's parent space (the group's transform and opacity\n * applied), followed by the replaced spine as an unpainted path when there is one.\n */\nexport function releaseVectorBlend(group: VectorGroupNode, newId: () => string): VectorNode[] {\n\tconst m = nodeMatrix(group);\n\tconst opacity = group.opacity;\n\tconst keys = vectorBlendKeys(group)\n\t\t.map((c) => (group.transform ? transformVectorNode(c, m) : c))\n\t\t.map((c) => (opacity !== undefined && opacity < 1 ? { ...c, opacity: (c.opacity ?? 1) * opacity } : c));\n\tconst spine = group.blend?.spine;\n\tif (!spine || spine.anchors.length < 2) return keys;\n\tconst path: VectorPathNode = { id: newId(), type: 'path', name: 'Spine', fill: null, stroke: null, subpaths: [{ closed: spine.closed, anchors: spine.anchors.map((a) => ({ ...a })) }] };\n\treturn [...keys, group.transform ? transformVectorNode(path, m) : path];\n}\n","/**\n * Free Distort, perspective and skew: the selection box's corners or sides dragged, and nodes sent\n * through a map of document space while each keeps its own (rigid) transform.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): vectorcraft `crates/tools/src/xform/free.rs` (`distort_quad`: a corner\n * moved freely, or with its partner mirrored along the dominant axis for perspective, and a side's\n * two corners moved together; `shear_for_side`: a side handle shears about the opposite side, or\n * the centre with Alt).\n */\nimport { mapVectorSubpaths, type VectorPointMap } from './pathMap.js';\nimport { mapVectorPaint } from './gradient.js';\nimport { applyMatrix, invertMatrix, multiplyMatrices, nodeMatrix, type AffineMatrix } from './geometry.js';\nimport { vectorEffectInputBounds, vectorEnvelopeMap, vectorEnvelopeMesh } from './appearance.js';\nimport { mapVectorMeshPoints } from './warp.js';\nimport { matrixAbout, skewMatrix } from '../geom/affine.js';\nimport type { Vec2, VectorBounds, VectorEffect, VectorGroupNode, VectorNode, VectorPathNode, VectorTransformHandle } from './types.js';\n\n/** Default tolerance (document units) of Free Distort's adaptive path mapping. */\nexport const VECTOR_DISTORT_TOLERANCE = 0.05;\n\n/** How dragging a selection box handle distorts it: each corner freely, or in symmetric perspective. */\nexport type VectorDistortMode = 'distort' | 'perspective';\n\nconst CORNER_INDEX: Partial<Record<VectorTransformHandle, number>> = { nw: 0, ne: 1, se: 2, sw: 3 };\nconst SIDE_CORNERS: Partial<Record<VectorTransformHandle, [number, number]>> = { n: [0, 1], e: [1, 2], s: [2, 3], w: [3, 0] };\n\n/** A box's corners clockwise from the top left. */\nexport const vectorBoxCorners = (b: VectorBounds): Vec2[] => [\n\t{ x: b.x, y: b.y },\n\t{ x: b.x + b.width, y: b.y },\n\t{ x: b.x + b.width, y: b.y + b.height },\n\t{ x: b.x, y: b.y + b.height }\n];\n\n/**\n * The quad (clockwise from the top left) box `b` becomes when handle `handle` is dragged by `d`: a\n * corner moves by `d` (`distort`), or along the drag's dominant axis with the corner beside it on\n * that side moving the opposite way (`perspective`); a side moves both its corners.\n */\nexport function vectorDistortQuad(b: VectorBounds, handle: VectorTransformHandle, d: Vec2, mode: VectorDistortMode = 'distort'): Vec2[] {\n\tconst q = vectorBoxCorners(b);\n\tconst i = CORNER_INDEX[handle];\n\tif (i !== undefined) {\n\t\tif (mode === 'perspective') {\n\t\t\tif (Math.abs(d.x) >= Math.abs(d.y)) {\n\t\t\t\tconst partner = [1, 0, 3, 2][i];\n\t\t\t\tq[i].x += d.x;\n\t\t\t\tq[partner].x -= d.x;\n\t\t\t} else {\n\t\t\t\tconst partner = [3, 2, 1, 0][i];\n\t\t\t\tq[i].y += d.y;\n\t\t\t\tq[partner].y -= d.y;\n\t\t\t}\n\t\t} else {\n\t\t\tq[i].x += d.x;\n\t\t\tq[i].y += d.y;\n\t\t}\n\t\treturn q;\n\t}\n\tconst side = SIDE_CORNERS[handle];\n\tif (side) for (const k of side) q[k] = { x: q[k].x + d.x, y: q[k].y + d.y };\n\treturn q;\n}\n\nconst about = (o: Vec2, m: AffineMatrix): AffineMatrix => matrixAbout(m, o);\n\n/**\n * The skew for dragging side `handle` of box `b` by `d`: along that side, about the opposite side\n * (or the centre, `fromCenter`). Corners give the identity.\n */\nexport function vectorShearForSide(b: VectorBounds, handle: VectorTransformHandle, d: Vec2, fromCenter = false): AffineMatrix {\n\tconst center = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\tif (handle === 'n' || handle === 's') {\n\t\tconst o = fromCenter ? center : { x: center.x, y: handle === 'n' ? b.y + b.height : b.y };\n\t\tconst lever = (handle === 'n' ? b.y : b.y + b.height) - o.y;\n\t\treturn about(o, [1, 0, Math.abs(lever) > 1e-9 ? d.x / lever : 0, 1, 0, 0]);\n\t}\n\tif (handle === 'e' || handle === 'w') {\n\t\tconst o = fromCenter ? center : { x: handle === 'w' ? b.x + b.width : b.x, y: center.y };\n\t\tconst lever = (handle === 'w' ? b.x : b.x + b.width) - o.x;\n\t\treturn about(o, [1, Math.abs(lever) > 1e-9 ? d.y / lever : 0, 0, 1, 0, 0]);\n\t}\n\treturn [1, 0, 0, 1, 0, 0];\n}\n\n/**\n * A skew by `ax` degrees horizontally (vertical lines lean right for positive angles: x' = x + tan(ax)·y)\n * and `ay` degrees vertically (y' = y + tan(ay)·x), about `origin`.\n */\nexport function vectorSkewMatrix(ax: number, ay: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n\treturn skewMatrix(ax, ay, origin);\n}\n\n/** Effects after their node's geometry went through a non-affine map: envelope meshes follow it (a preset becomes the mesh it stood for). */\nfunction mapEffects(node: VectorNode, f: VectorPointMap): VectorEffect[] | undefined {\n\tif (!node.effects?.length) return undefined;\n\treturn node.effects.map((e) => {\n\t\tif (e.type !== 'envelope') return e;\n\t\tif (e.params.style === 'mesh') return e.params.mesh ? { ...e, params: { ...e.params, mesh: mapVectorMeshPoints(e.params.mesh, f) } } : e;\n\t\tconst bounds = vectorEffectInputBounds(node, e.id);\n\t\tif (!bounds || !vectorEnvelopeMap(e.params, bounds)) return e;\n\t\treturn { ...e, params: { ...e.params, style: 'mesh', mesh: mapVectorMeshPoints(vectorEnvelopeMesh(e.params, bounds), f) } };\n\t});\n}\n\n/**\n * A node sent through `f`, a map of the space `parentToDoc` maps its parent to (the document):\n * every anchor and handle is mapped in the node's own space, adaptively so curves stay within\n * `tolerance`, and the node keeps its rigid `transform`. Gradients in the node's space have their\n * handles mapped (bounding-box ones follow the new bounds), envelope meshes and a blend's spine\n * are mapped too; stroke widths, live corner radii and effect parameters are kept.\n */\nexport function distortVectorNode<T extends VectorNode>(node: T, parentToDoc: AffineMatrix, f: VectorPointMap, tolerance = VECTOR_DISTORT_TOLERANCE): T {\n\tconst toDoc = multiplyMatrices(nodeMatrix(node), parentToDoc);\n\tconst inv = invertMatrix(toDoc);\n\tconst local: VectorPointMap = (p) => applyMatrix(inv, f(applyMatrix(toDoc, p)));\n\tconst effects = mapEffects(node, local);\n\tif (node.type === 'group') {\n\t\tconst group = node as VectorGroupNode;\n\t\tconst children = group.children.map((c) => distortVectorNode(c, toDoc, f, tolerance));\n\t\tconst spine = group.blend?.spine;\n\t\treturn {\n\t\t\t...group,\n\t\t\tchildren,\n\t\t\t...(effects ? { effects } : {}),\n\t\t\t...(spine ? { blend: { ...group.blend, spine: mapVectorSubpaths([spine], local, tolerance)[0] } } : {})\n\t\t} as T;\n\t}\n\tconst path = node as VectorPathNode;\n\treturn {\n\t\t...path,\n\t\t...(effects ? { effects } : {}),\n\t\t...(path.fill !== undefined ? { fill: mapVectorPaint(path.fill, local) } : {}),\n\t\t...(path.stroke !== undefined ? { stroke: mapVectorPaint(path.stroke, local) } : {}),\n\t\tsubpaths: mapVectorSubpaths(path.subpaths, local, tolerance)\n\t} as T;\n}\n","/**\n * Smart guides and object snapping for the vector editor. Targets — anchors, bounding-box\n * edges and centres, path segments and the artboard — are gathered once per gesture in\n * document space (rotated nodes included) and kept sorted by x and y, so each pointer move\n * finds the few near the pointer by bisection. A point snaps, in this order of priority: kept\n * to its Shift angle and slid into line with a target, onto an anchor or centre, onto an\n * intersection of two paths, onto the perpendicular foot or tangent point from where it\n * leaves, onto a path, onto a construction angle, then into line with targets on x and y. A\n * moved box lines its edges and centre up with targets, or spaces itself evenly in its row\n * and column; a resized box lands its moving edges on targets, or matches another object's\n * width or height. Every snap reports labelled guide lines in document units.\n *\n * Portions ported from vectorcraft-main/crates/tools/src/guides.rs (`Targets`, `within`,\n * `for_move`, `for_drawing`, `for_handle`, `for_anchor_drag`, `push_segments`, `snap_from`,\n * `slide`, `lined_up`, `on_segment`, `crossing`, `align_rects`, `snap_rects`, `even_spacing`,\n * `gap_marks`, `snap_scale`, `Leave`), figcraft-main/crates/engine/src/snap.rs (`spacings`,\n * `equal_spacing`, `spacing_guides`: equal-spacing cases and gap labels),\n * designcraft-main/crates/tools/src/snap.rs (`pass_dimensions`: matching other objects'\n * sizes) and cadcraft-main/crates/engine/src/snap/curves.rs (`Param::solve`: perpendicular and\n * tangent points by sign-change sampling and bisection) (MIT OR Apache-2.0, © ArtCraft Team\n * and contributors). See THIRD_PARTY_NOTICES.md.\n */\nimport type { Point } from '../canvas/types.js';\nimport { expandVectorAppearance } from './appearance.js';\nimport { segmentDerivative, segmentNearest, segmentPoint, type BezierSegment } from '../canvas/pathops/bezier.js';\nimport { segmentIntersections } from '../canvas/pathops/boolean.js';\nimport {\n\tapplyMatrix,\n\tIDENTITY_MATRIX,\n\tmatrixRotation,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\trotateMatrix,\n\tsubpathSegment,\n\tsubpathSegmentCount,\n\tvectorNodeBounds,\n\ttype AffineMatrix\n} from './geometry.js';\nimport type { VectorAnchorRef, VectorBounds, VectorDocument, VectorNode, VectorSubpath, VectorTransformHandle, Vec2 } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * What a guide line shows: `align` lines run from a target through the snapped point or box,\n * `construction` lines from where a drawn point leaves, `spacing` marks equal gaps and `size`\n * the side whose length matches another object's.\n */\nexport type VectorGuideKind = 'align' | 'construction' | 'spacing' | 'size';\n\n/** A guide line in document units. */\nexport interface VectorGuideLine {\n\tkind: VectorGuideKind;\n\tx1: number;\n\ty1: number;\n\tx2: number;\n\ty2: number;\n}\n\n/** What a point or box snapped to. */\nexport type VectorSnapKind = 'anchor' | 'centre' | 'intersect' | 'perpendicular' | 'tangent' | 'path' | 'construction' | 'align' | 'spacing' | 'size';\n\n/** A guide label in document units: the snap kind's name, or a distance for gaps and sizes. */\nexport interface VectorGuideLabel {\n\tkind: VectorSnapKind;\n\tx: number;\n\ty: number;\n\ttext: string;\n}\n\nexport interface VectorSnapGuides {\n\tlines: VectorGuideLine[];\n\tlabels: VectorGuideLabel[];\n}\n\nexport interface VectorPointSnap extends VectorSnapGuides {\n\tpoint: Vec2;\n\t/** The rule that placed the point, or null when nothing was in reach. */\n\tkind: VectorSnapKind | null;\n\t/** Whether x / y were set by a target (for falling back to the grid on the other axis). */\n\tx: boolean;\n\ty: boolean;\n}\n\nexport interface VectorRectSnap extends VectorSnapGuides {\n\t/** Correction to add to the move. */\n\tdx: number;\n\tdy: number;\n\tx: boolean;\n\ty: boolean;\n}\n\nexport interface VectorScaleSnap extends VectorSnapGuides {\n\tsx: number;\n\tsy: number;\n\tsnapped: boolean;\n}\n\n/**\n * The point a drawn point leaves from (the anchor before it, a shape's start, a handle's\n * anchor) and how it keeps to it.\n */\nexport interface VectorSnapLeave {\n\tat: Vec2;\n\t/**\n\t * Shift held: keep to 45° steps round `at` (`angle`), to a diagonal (`square`, a box's\n\t * corner) or to the nearer axis (`axis`, a dragged point).\n\t */\n\tconstrain?: 'angle' | 'square' | 'axis' | null;\n\t/** Construction guide angles through `at`, degrees counter-clockwise on screen. */\n\tangles?: readonly number[];\n\t/** Snap to the perpendicular foot and tangent points from `at` on paths (default true). */\n\tcurves?: boolean;\n}\n\n/** The construction guide angles new editors start with. */\nexport const VECTOR_CONSTRUCTION_ANGLES: readonly number[] = [0, 45, 90, 135];\n\n/** Where `constrain` puts `p` (unchanged without one). */\nexport function constrainToLeave(leave: VectorSnapLeave | null | undefined, p: Vec2): Vec2 {\n\tif (!leave?.constrain) return p;\n\tconst dx = p.x - leave.at.x;\n\tconst dy = p.y - leave.at.y;\n\tswitch (leave.constrain) {\n\t\tcase 'axis':\n\t\t\treturn Math.abs(dx) > Math.abs(dy) ? { x: p.x, y: leave.at.y } : { x: leave.at.x, y: p.y };\n\t\tcase 'square': {\n\t\t\tconst s = Math.max(Math.abs(dx), Math.abs(dy));\n\t\t\treturn { x: leave.at.x + Math.sign(dx || 1) * s, y: leave.at.y + Math.sign(dy || 1) * s };\n\t\t}\n\t\tdefault: {\n\t\t\tconst len = Math.hypot(dx, dy);\n\t\t\tconst a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);\n\t\t\treturn { x: leave.at.x + Math.cos(a) * len, y: leave.at.y + Math.sin(a) * len };\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Targets\n// ---------------------------------------------------------------------------\n\ntype TargetKind = 'anchor' | 'centre' | 'edge' | 'artboard';\n\ninterface PointTarget {\n\tp: Vec2;\n\tkind: 'anchor' | 'centre';\n}\n\n/** A line to line up with: where it runs on its axis and the target point it comes from. */\ninterface LineTarget {\n\tv: number;\n\tfrom: Vec2;\n\tkind: TargetKind;\n}\n\ninterface SegmentTarget {\n\tseg: Point[];\n\tminX: number;\n\tminY: number;\n\tmaxX: number;\n\tmaxY: number;\n}\n\n/** How many anchors, and how many segments, the targets gather at most. */\nconst BUDGET = 20_000;\n/** The first near segments paired up when looking for intersections. */\nconst CROSSING_PAIRS = 32;\n/** Parameter samples per segment for perpendicular / tangent roots, and bisection steps. */\nconst CURVE_SAMPLES = 48;\nconst BISECT = 50;\nconst EQUAL = 1e-6;\n\n/** First index of `sorted` whose key is not below `v` (`strict`: above `v`). */\nfunction bound<T>(sorted: readonly T[], key: (e: T) => number, v: number, strict: boolean): number {\n\tlet lo = 0;\n\tlet hi = sorted.length;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi) >>> 1;\n\t\tconst k = key(sorted[mid]);\n\t\tif (strict ? k <= v : k < v) lo = mid + 1;\n\t\telse hi = mid;\n\t}\n\treturn lo;\n}\n\n/** The entries of `sorted` (ascending by `key`) whose key is within `tol` of `v`, by bisection. */\nfunction within<T>(sorted: readonly T[], key: (e: T) => number, v: number, tol: number): readonly T[] {\n\treturn sorted.slice(bound(sorted, key, v - tol, false), bound(sorted, key, v + tol, true));\n}\n\nconst linesNear = (lines: readonly LineTarget[], v: number, tol: number) => within(lines, (l) => l.v, v, tol);\n\nconst distance = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\nconst toPoint = (p: Vec2): Point => [p.x, p.y];\nconst toVec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\n\n/** What `collect` gathers from each path besides its anchors and bounds. */\ntype Gather = 'bounds' | 'segments' | 'drawing';\n\nconst LABELS: Record<VectorSnapKind, string> = {\n\tanchor: 'anchor',\n\tcentre: 'centre',\n\tintersect: 'intersect',\n\tperpendicular: 'perpendicular',\n\ttangent: 'tangent',\n\tpath: 'path',\n\tconstruction: 'angle',\n\talign: 'align',\n\tspacing: 'spacing',\n\tsize: 'size'\n};\n\nconst fmtLength = (n: number) => String(Math.round(n * 100) / 100);\n\n/** A node's own (possibly rotated) frame: its size there and its centre in document space. */\nfunction nodeFrame(node: VectorNode, parent: AffineMatrix, aabb?: VectorBounds | null): { width: number; height: number; centre: Vec2 } | null {\n\tconst angle = matrixRotation(multiplyMatrices(nodeMatrix(node), parent));\n\tconst b = angle ? vectorNodeBounds(node, multiplyMatrices(parent, rotateMatrix(-angle))) : aabb !== undefined ? aabb : vectorNodeBounds(node, parent);\n\tif (!b) return null;\n\tconst c = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\treturn { width: b.width, height: b.height, centre: angle ? applyMatrix(rotateMatrix(angle), c) : c };\n}\n\n/** True when `id` is `node` or inside it. */\nfunction contains(node: VectorNode, ids: ReadonlySet<string>): boolean {\n\tif (ids.has(node.id)) return true;\n\treturn node.type === 'group' && node.children.some((c) => contains(c, ids));\n}\n\n/**\n * Snap targets in document space, gathered once per gesture. Build them with `forMove`,\n * `forResize`, `forDrawing`, `forAnchorDrag` or `forHandle`, then call `snapFrom`,\n * `snapRect` or `snapScale` on every pointer move. Tolerances are in document units (screen\n * pixels divided by the zoom).\n */\nexport class VectorSnapTargets {\n\tprivate readonly points: PointTarget[] = [];\n\tprivate readonly xs: LineTarget[] = [];\n\tprivate readonly ys: LineTarget[] = [];\n\tprivate readonly segments: SegmentTarget[] = [];\n\t/** Bounds of the objects a moved box spaces itself evenly with. */\n\tprivate readonly boxes: VectorBounds[] = [];\n\t/** Side lengths of the other objects (in their own frames), which a resize may match. */\n\tprivate readonly sizes: number[] = [];\n\n\tprivate constructor() {}\n\n\t/** How many targets of each sort were gathered. */\n\tget counts(): { points: number; lines: number; segments: number; boxes: number } {\n\t\treturn { points: this.points.length, lines: this.xs.length + this.ys.length, segments: this.segments.length, boxes: this.boxes.length };\n\t}\n\n\t/** Targets for moving nodes `ids`: the other art's anchors, bounds and centres, the artboard, and boxes to space evenly with. */\n\tstatic forMove(doc: VectorDocument, ids: readonly string[]): VectorSnapTargets {\n\t\treturn VectorSnapTargets.collect(doc, new Set(ids), 'bounds');\n\t}\n\n\t/** Targets for resizing nodes `ids`: as for a move, plus the other objects' sizes. */\n\tstatic forResize(doc: VectorDocument, ids: readonly string[]): VectorSnapTargets {\n\t\treturn VectorSnapTargets.collect(doc, new Set(ids), 'bounds');\n\t}\n\n\t/**\n\t * Targets for a drawn point (pen, shape tools): the art but `exclude`, its anchors (as\n\t * points and in line), centres, edges and segments. The anchors and segments of `exclude`\n\t * (the path being drawn, whose bounds grow with it) stay targets.\n\t */\n\tstatic forDrawing(doc: VectorDocument, exclude: readonly string[] = []): VectorSnapTargets {\n\t\tconst skip = new Set(exclude);\n\t\tconst t = VectorSnapTargets.collect(doc, skip, 'drawing', false);\n\t\tt.pushPaths(doc, skip, () => false, true);\n\t\treturn t.index();\n\t}\n\n\t/**\n\t * Targets for dragging anchors: the other art with its segments, and the anchors and\n\t * segments that stay put on the paths being reshaped (their bounds move along, so they are\n\t * no targets). The moving anchors are left out.\n\t */\n\tstatic forAnchorDrag(doc: VectorDocument, anchors: readonly VectorAnchorRef[]): VectorSnapTargets {\n\t\tconst moving = new Map<string, Set<string>>();\n\t\tfor (const r of anchors) {\n\t\t\tconst set = moving.get(r.nodeId) ?? new Set<string>();\n\t\t\tset.add(`${r.subpath}:${r.index}`);\n\t\t\tmoving.set(r.nodeId, set);\n\t\t}\n\t\tconst t = VectorSnapTargets.collect(doc, new Set(moving.keys()), 'segments', false);\n\t\tt.pushPaths(doc, new Set(moving.keys()), (id, s, i) => !!moving.get(id)?.has(`${s}:${i}`), true);\n\t\treturn t.index();\n\t}\n\n\t/**\n\t * Targets for dragging a handle of path `nodeId`: the other art and that path's anchors\n\t * (its bounds and the segments through the handle move with it, so they would chase it).\n\t */\n\tstatic forHandle(doc: VectorDocument, nodeId: string): VectorSnapTargets {\n\t\tconst skip = new Set([nodeId]);\n\t\tconst t = VectorSnapTargets.collect(doc, skip, 'bounds', false);\n\t\tt.pushPaths(doc, skip, () => false, false);\n\t\treturn t.index();\n\t}\n\n\t/** The anchors of the paths `ids` as targets (on them and in line), and their segments when `segments`. */\n\tprivate pushPaths(doc: VectorDocument, ids: ReadonlySet<string>, moving: (id: string, subpath: number, index: number) => boolean, segments: boolean) {\n\t\tlet anchors = BUDGET;\n\t\tlet segmentBudget = segments ? BUDGET : 0;\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') visit(n.children, m);\n\t\t\t\telse if (ids.has(n.id) && n.visible !== false) {\n\t\t\t\t\tn.subpaths.forEach((sp, s) => {\n\t\t\t\t\t\tsp.anchors.forEach((a, i) => {\n\t\t\t\t\t\t\tif (anchors <= 0 || moving(n.id, s, i)) return;\n\t\t\t\t\t\t\tthis.pushAnchor(applyMatrix(m, a));\n\t\t\t\t\t\t\tanchors--;\n\t\t\t\t\t\t});\n\t\t\t\t\t\tsegmentBudget = this.pushSegments(sp, m, (i) => moving(n.id, s, i), segmentBudget);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvisit(doc.nodes, IDENTITY_MATRIX);\n\t}\n\n\tprivate pushAnchor(p: Vec2) {\n\t\tthis.points.push({ p, kind: 'anchor' });\n\t\tthis.xs.push({ v: p.x, from: p, kind: 'anchor' });\n\t\tthis.ys.push({ v: p.y, from: p, kind: 'anchor' });\n\t}\n\n\t/** The segments of `sp` (mapped by `m`) that stay put while the anchors `moving` accepts move. */\n\tprivate pushSegments(sp: VectorSubpath, m: AffineMatrix, moving: (index: number) => boolean, budget: number): number {\n\t\tconst n = sp.anchors.length;\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count && budget > 0; i++) {\n\t\t\tif (moving(i) || moving((i + 1) % n)) continue;\n\t\t\tconst seg = subpathSegment(sp, i).map((q) => toPoint(applyMatrix(m, toVec(q))));\n\t\t\tlet minX = Infinity;\n\t\t\tlet minY = Infinity;\n\t\t\tlet maxX = -Infinity;\n\t\t\tlet maxY = -Infinity;\n\t\t\tfor (const [x, y] of seg) {\n\t\t\t\tminX = Math.min(minX, x);\n\t\t\t\tminY = Math.min(minY, y);\n\t\t\t\tmaxX = Math.max(maxX, x);\n\t\t\t\tmaxY = Math.max(maxY, y);\n\t\t\t}\n\t\t\tthis.segments.push({ seg, minX, minY, maxX, maxY });\n\t\t\tbudget--;\n\t\t}\n\t\treturn budget;\n\t}\n\n\tprivate pushRect(r: VectorBounds, kind: TargetKind, centre: Vec2 | null) {\n\t\tconst corners = [\n\t\t\t{ x: r.x, y: r.y },\n\t\t\t{ x: r.x + r.width, y: r.y },\n\t\t\t{ x: r.x + r.width, y: r.y + r.height },\n\t\t\t{ x: r.x, y: r.y + r.height }\n\t\t];\n\t\tfor (const p of corners) {\n\t\t\tthis.xs.push({ v: p.x, from: p, kind });\n\t\t\tthis.ys.push({ v: p.y, from: p, kind });\n\t\t}\n\t\tif (centre) {\n\t\t\tthis.points.push({ p: centre, kind: 'centre' });\n\t\t\tthis.xs.push({ v: centre.x, from: centre, kind: 'centre' });\n\t\t\tthis.ys.push({ v: centre.y, from: centre, kind: 'centre' });\n\t\t}\n\t}\n\n\t/** Sorts the targets for `within` (stable: of targets alike, the first gathered wins). */\n\tprivate index(): this {\n\t\tthis.points.sort((a, b) => a.p.x - b.p.x);\n\t\tthis.xs.sort((a, b) => a.v - b.v);\n\t\tthis.ys.sort((a, b) => a.v - b.v);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Gathers targets from the artboard and every visible node but `exclude` (and what is inside\n\t * those): each leaf's anchors (also as lines for `drawing`), its segments (`segments`,\n\t * `drawing`), its bounds' corners as lines and its centre; and the top-level objects' boxes and\n\t * sizes (inside a group holding an excluded node, that group's other members).\n\t */\n\tprivate static collect(doc: VectorDocument, exclude: ReadonlySet<string>, gather: Gather, sort = true): VectorSnapTargets {\n\t\tconst self = new VectorSnapTargets();\n\t\tconst artboard = { x: 0, y: 0, width: doc.width, height: doc.height };\n\t\tself.pushRect(artboard, 'artboard', { x: doc.width / 2, y: doc.height / 2 });\n\t\tlet anchors = BUDGET;\n\t\tlet segments = BUDGET;\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const stored of list) {\n\t\t\t\tif (exclude.has(stored.id) || stored.visible === false) continue;\n\t\t\t\t// Other art snaps where it draws (path effects and live booleans applied).\n\t\t\t\tconst n = contains(stored, exclude) ? stored : expandVectorAppearance(stored);\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tvisit(n.children, m);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (anchors <= 0) continue;\n\t\t\t\tfor (const sp of n.subpaths) {\n\t\t\t\t\tfor (const a of sp.anchors) {\n\t\t\t\t\t\tif (anchors-- <= 0) break;\n\t\t\t\t\t\tconst p = applyMatrix(m, a);\n\t\t\t\t\t\tif (gather === 'drawing') self.pushAnchor(p);\n\t\t\t\t\t\telse self.points.push({ p, kind: 'anchor' });\n\t\t\t\t\t}\n\t\t\t\t\tif (gather !== 'bounds') segments = self.pushSegments(sp, m, () => false, segments);\n\t\t\t\t}\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tconst f = nodeFrame(n, parent, b);\n\t\t\t\tif (b) self.pushRect(b, 'edge', f?.centre ?? null);\n\t\t\t}\n\t\t};\n\t\tvisit(doc.nodes, IDENTITY_MATRIX);\n\t\t// Boxes to space evenly with and sizes to match: whole objects, opening groups that hold an excluded node.\n\t\tconst objects = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tif (exclude.has(n.id) || n.visible === false || self.boxes.length >= BUDGET) continue;\n\t\t\t\tif (n.type === 'group' && contains(n, exclude)) {\n\t\t\t\t\tobjects(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tif (b) self.boxes.push(b);\n\t\t\t\tconst f = nodeFrame(n, parent, b);\n\t\t\t\tif (f) self.sizes.push(f.width, f.height);\n\t\t\t}\n\t\t};\n\t\tobjects(doc.nodes, IDENTITY_MATRIX);\n\t\treturn sort ? self.index() : self;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Points\n\t// -------------------------------------------------------------------------\n\n\t/** Snaps a single point (see `snapFrom`). */\n\tsnapPoint(p: Vec2, tol: number): VectorPointSnap {\n\t\treturn this.snapFrom(p, null, tol);\n\t}\n\n\t/**\n\t * Snaps a point `p`, drawn or dragged from `leave` when given. With `leave.constrain` it keeps\n\t * to its angle round `leave.at`, sliding along that way into line with the nearest target.\n\t * Otherwise it lands, in order, on an anchor or centre, an intersection of two paths, the\n\t * perpendicular foot or a tangent point from `leave.at`, a path, a construction guide\n\t * through `leave.at` (where a target's line crosses it if one does nearby), or else lines up\n\t * with targets on x and y.\n\t */\n\tsnapFrom(p: Vec2, leave: VectorSnapLeave | null | undefined, tol: number): VectorPointSnap {\n\t\tconst none = (q: Vec2): VectorPointSnap => ({ point: q, kind: null, x: false, y: false, lines: [], labels: [] });\n\t\tconst at = (q: Vec2, kind: VectorSnapKind, lines: VectorGuideLine[] = []): VectorPointSnap => ({\n\t\t\tpoint: q,\n\t\t\tkind,\n\t\t\tx: true,\n\t\t\ty: true,\n\t\t\tlines,\n\t\t\tlabels: [this.label(q, kind)]\n\t\t});\n\t\tif (leave?.constrain) {\n\t\t\tconst q = constrainToLeave(leave, p);\n\t\t\tconst hit = this.slide(leave.at, { x: q.x - leave.at.x, y: q.y - leave.at.y }, q, tol, true);\n\t\t\treturn hit ? { point: hit.point, x: true, y: true, ...this.linedUp(hit.point, hit.from) } : none(q);\n\t\t}\n\t\tconst point = this.nearestPoint(p, tol);\n\t\tif (point) return at(point.p, point.kind);\n\t\tconst near = this.segmentsNear(p, tol);\n\t\tconst crossing = this.crossing(near, p, tol);\n\t\tif (crossing) return at(crossing, 'intersect');\n\t\tif (leave && leave.curves !== false) {\n\t\t\tconst foot = this.curvePoint(near, leave.at, p, tol);\n\t\t\tif (foot) return at(foot.point, foot.kind, [line('construction', leave.at, foot.point)]);\n\t\t}\n\t\tconst on = this.onSegment(near);\n\t\tif (on) return at(on, 'path');\n\t\tif (leave?.angles?.length) {\n\t\t\tconst c = construction(leave, p, tol);\n\t\t\tif (c) {\n\t\t\t\tconst hit = this.slide(leave.at, c.dir, c.point, tol, false);\n\t\t\t\tif (hit) {\n\t\t\t\t\tconst lined = this.linedUp(hit.point, hit.from);\n\t\t\t\t\treturn { point: hit.point, x: true, y: true, kind: lined.kind, lines: [line('construction', leave.at, hit.point), ...lined.lines], labels: lined.labels };\n\t\t\t\t}\n\t\t\t\treturn { point: c.point, kind: 'construction', x: true, y: true, lines: [line('construction', leave.at, c.point)], labels: [] };\n\t\t\t}\n\t\t}\n\t\tconst nearest = (lines: readonly LineTarget[], v: number) => {\n\t\t\tlet best: LineTarget | null = null;\n\t\t\tfor (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.v - v)) best = l;\n\t\t\treturn best;\n\t\t};\n\t\tconst bx = nearest(this.xs, p.x);\n\t\tconst by = nearest(this.ys, p.y);\n\t\tif (!bx && !by) return none(p);\n\t\tconst out = { x: bx ? bx.v : p.x, y: by ? by.v : p.y };\n\t\tconst lines: VectorGuideLine[] = [];\n\t\tif (bx) lines.push(line('align', bx.from, { x: out.x, y: out.y }));\n\t\tif (by) lines.push(line('align', by.from, { x: out.x, y: out.y }));\n\t\treturn { point: out, kind: 'align', x: !!bx, y: !!by, lines, labels: [this.label(out, 'align')] };\n\t}\n\n\tprivate label(p: Vec2, kind: VectorSnapKind, text = LABELS[kind]): VectorGuideLabel {\n\t\treturn { kind, x: p.x, y: p.y, text };\n\t}\n\n\t/** The anchor or centre nearest `p`, within `tol`. */\n\tprivate nearestPoint(p: Vec2, tol: number): PointTarget | null {\n\t\tlet best: PointTarget | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const t of within(this.points, (e) => e.p.x, p.x, tol)) {\n\t\t\tconst d = distance(t.p, p);\n\t\t\tif (d <= tol && d < bestD) {\n\t\t\t\tbest = t;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * Slides `q`, on the line through `at` along `dir` (beyond `at` only for a `ray`), to where\n\t * the nearest target line crosses it, at most twice `tol` away: where it lands and the\n\t * target point that line comes from.\n\t */\n\tprivate slide(at: Vec2, dir: Vec2, q: Vec2, tol: number, ray: boolean): { point: Vec2; from: Vec2 } | null {\n\t\tconst len2 = dir.x * dir.x + dir.y * dir.y;\n\t\tif (!Number.isFinite(len2) || len2 <= 1e-18) return null;\n\t\tconst reach = 2 * tol;\n\t\tlet best: { moved: number; point: Vec2; from: Vec2 } | null = null;\n\t\tfor (const vertical of [true, false]) {\n\t\t\tconst d = vertical ? dir.x : dir.y;\n\t\t\tif (Math.abs(d) <= 1e-9) continue;\n\t\t\tconst a = vertical ? at.x : at.y;\n\t\t\tfor (const l of linesNear(vertical ? this.xs : this.ys, vertical ? q.x : q.y, reach)) {\n\t\t\t\tconst s = (l.v - a) / d;\n\t\t\t\t// Exactly on the line, whatever the rounding along the way.\n\t\t\t\tconst hit = vertical ? { x: l.v, y: at.y + dir.y * s } : { x: at.x + dir.x * s, y: l.v };\n\t\t\t\tconst moved = distance(hit, q);\n\t\t\t\tif (moved <= reach && (!ray || s > 0) && (!best || moved < best.moved)) best = { moved, point: hit, from: l.from };\n\t\t\t}\n\t\t}\n\t\treturn best && { point: best.point, from: best.from };\n\t}\n\n\t/** The guides of a point `q` slid into line with the target at `from`: the line and \"align\", or the target's own label when `q` sits on it. */\n\tprivate linedUp(q: Vec2, from: Vec2): { kind: VectorSnapKind } & VectorSnapGuides {\n\t\tconst on = this.nearestPoint(q, 1e-9);\n\t\tif (on) return { kind: on.kind, lines: [], labels: [this.label(on.p, on.kind)] };\n\t\treturn { kind: 'align', lines: [line('align', from, q)], labels: [this.label(q, 'align')] };\n\t}\n\n\t/** Target segments whose control box reaches `p` and which pass within `tol` of it, nearest first. */\n\tprivate segmentsNear(p: Vec2, tol: number): { seg: Point[]; t: number; distance: number }[] {\n\t\tconst out: { seg: Point[]; t: number; distance: number }[] = [];\n\t\tconst pt = toPoint(p);\n\t\tfor (const s of this.segments) {\n\t\t\tif (p.x < s.minX - tol || p.x > s.maxX + tol || p.y < s.minY - tol || p.y > s.maxY + tol) continue;\n\t\t\tconst hit = segmentNearest(s.seg, pt);\n\t\t\tif (hit.distance <= tol) out.push({ seg: s.seg, t: hit.t, distance: hit.distance });\n\t\t}\n\t\treturn out.sort((a, b) => a.distance - b.distance);\n\t}\n\n\tprivate onSegment(near: readonly { seg: Point[]; t: number }[]): Vec2 | null {\n\t\treturn near.length ? toVec(segmentPoint(near[0].seg, near[0].t)) : null;\n\t}\n\n\t/** Where two of the target segments near `p` cross, the crossing nearest `p` within `tol`. */\n\tprivate crossing(near: readonly { seg: Point[] }[], p: Vec2, tol: number): Vec2 | null {\n\t\tconst list = near.slice(0, CROSSING_PAIRS);\n\t\tlet best: Vec2 | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (let i = 0; i < list.length; i++) {\n\t\t\tfor (let j = i + 1; j < list.length; j++) {\n\t\t\t\tfor (const hit of segmentIntersections(list[i].seg as BezierSegment, list[j].seg as BezierSegment)) {\n\t\t\t\t\tconst q = toVec(hit.point);\n\t\t\t\t\tconst d = distance(q, p);\n\t\t\t\t\tif (d <= tol && d < bestD) {\n\t\t\t\t\t\tbest = q;\n\t\t\t\t\t\tbestD = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * The foot of a perpendicular, or a tangent point, from `base` on a target segment near `p`\n\t * (within `tol` of it): roots of `(B(t) − base) · B′(t)` and `(B(t) − base) × B′(t)`\n\t * bracketed by sign changes of samples and narrowed by bisection.\n\t */\n\tprivate curvePoint(near: readonly { seg: Point[] }[], base: Vec2, p: Vec2, tol: number): { point: Vec2; kind: 'perpendicular' | 'tangent' } | null {\n\t\tlet best: { point: Vec2; kind: 'perpendicular' | 'tangent'; d: number } | null = null;\n\t\tfor (const { seg } of near) {\n\t\t\tfor (const kind of ['perpendicular', 'tangent'] as const) {\n\t\t\t\tif (kind === 'tangent' && seg.length === 2) continue;\n\t\t\t\tfor (const q of solveOnSegment(seg, base, kind === 'perpendicular' ? dotCondition : crossCondition)) {\n\t\t\t\t\tconst d = distance(q, p);\n\t\t\t\t\tif (d <= tol && (!best || d < best.d)) best = { point: q, kind, d };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best && { point: best.point, kind: best.kind };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Boxes\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Snaps a moving box `r` (the moved selection's bounds): its edge or centre nearest a target\n\t * line on each axis (`axes` limits which may move). With `spacing`, an axis that lines up\n\t * with nothing spaces the box evenly in its row or column. Returns the correction and guides.\n\t */\n\tsnapRect(r: VectorBounds, tol: number, options: { spacing?: boolean; axes?: { x?: boolean; y?: boolean } } = {}): VectorRectSnap {\n\t\tconst axes = { x: options.axes?.x !== false, y: options.axes?.y !== false };\n\t\tconst nearest = (lines: readonly LineTarget[], values: number[]) => {\n\t\t\tlet best: { d: number; from: Vec2 } | null = null;\n\t\t\tfor (const v of values) for (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.d)) best = { d: l.v - v, from: l.from };\n\t\t\treturn best;\n\t\t};\n\t\tconst bx = axes.x ? nearest(this.xs, [r.x, r.x + r.width / 2, r.x + r.width]) : null;\n\t\tconst by = axes.y ? nearest(this.ys, [r.y, r.y + r.height / 2, r.y + r.height]) : null;\n\t\tconst out: VectorRectSnap = { dx: bx?.d ?? 0, dy: by?.d ?? 0, x: !!bx, y: !!by, lines: [], labels: [] };\n\t\tconst done = { ...r, x: r.x + out.dx, y: r.y + out.dy };\n\t\tif (bx) {\n\t\t\tconst x = bx.from.x;\n\t\t\tout.lines.push({ kind: 'align', x1: x, y1: Math.min(bx.from.y, done.y), x2: x, y2: Math.max(bx.from.y, done.y + done.height) });\n\t\t}\n\t\tif (by) {\n\t\t\tconst y = by.from.y;\n\t\t\tout.lines.push({ kind: 'align', x1: Math.min(by.from.x, done.x), y1: y, x2: Math.max(by.from.x, done.x + done.width), y2: y });\n\t\t}\n\t\tif (options.spacing && this.boxes.length) {\n\t\t\tfor (const horizontal of [true, false]) {\n\t\t\t\tif (horizontal ? out.x || !axes.x : out.y || !axes.y) continue;\n\t\t\t\tconst moved = { ...r, x: r.x + out.dx, y: r.y + out.dy };\n\t\t\t\tconst even = this.evenSpacing(moved, horizontal, tol);\n\t\t\t\tif (!even) continue;\n\t\t\t\tif (horizontal) {\n\t\t\t\t\tout.dx += even.shift;\n\t\t\t\t\tout.x = true;\n\t\t\t\t} else {\n\t\t\t\t\tout.dy += even.shift;\n\t\t\t\t\tout.y = true;\n\t\t\t\t}\n\t\t\t\tfor (const gap of even.gaps) this.gapMarks(gap, horizontal, tol, out);\n\t\t\t}\n\t\t}\n\t\tif (bx || by) out.labels.unshift(this.label({ x: r.x + out.dx + r.width / 2, y: r.y + out.dy + r.height / 2 }, 'align'));\n\t\treturn out;\n\t}\n\n\t/**\n\t * Equal spacing along x (`horizontal`) or y for the moved box `r`, among the objects of its\n\t * row (column): the shift within `tol` that centres it between its neighbours, or leaves it\n\t * as far from the neighbour before or after it as two other objects of the row are apart;\n\t * and the gaps that are equal then, as (start, end, where across).\n\t */\n\tprivate evenSpacing(r: VectorBounds, horizontal: boolean, tol: number): { shift: number; gaps: [number, number, number][] } | null {\n\t\tconst span = (b: VectorBounds, x: boolean): [number, number] => (x ? [b.x, b.x + b.width] : [b.y, b.y + b.height]);\n\t\tconst [r0, r1] = span(r, horizontal);\n\t\tconst len = r1 - r0;\n\t\tconst [c0, c1] = span(r, !horizontal);\n\t\tconst row = this.boxes\n\t\t\t.map((b) => ({ b, a0: span(b, horizontal)[0], a1: span(b, horizontal)[1] }))\n\t\t\t.filter((e) => span(e.b, !horizontal)[0] < c1 && span(e.b, !horizontal)[1] > c0 && (e.a1 <= r0 + tol || e.a0 >= r1 - tol))\n\t\t\t.sort((a, b) => a.a0 - b.a0);\n\t\tif (!row.length) return null;\n\t\t// Across the middle of what two boxes share (or of the space between them).\n\t\tconst mid = (a: VectorBounds, b: VectorBounds) => (Math.max(span(a, !horizontal)[0], span(b, !horizontal)[0]) + Math.min(span(a, !horizontal)[1], span(b, !horizontal)[1])) / 2;\n\t\tconst pairs: { g: number; gap: [number, number, number] }[] = [];\n\t\tfor (const p of row) {\n\t\t\tconst next = bound(row, (e) => e.a0, p.a1, false);\n\t\t\tconst q = row[next];\n\t\t\tif (!q) continue;\n\t\t\tconst straddles = p.a1 <= r0 + tol && q.a0 >= r1 - tol;\n\t\t\tif (q.a0 > p.a1 && !straddles) pairs.push({ g: q.a0 - p.a1, gap: [p.a1, q.a0, mid(p.b, q.b)] });\n\t\t}\n\t\tlet before: (typeof row)[number] | null = null;\n\t\tlet after: (typeof row)[number] | null = null;\n\t\tfor (const e of row) {\n\t\t\tif (e.a1 <= r0 + tol && (!before || e.a1 > before.a1)) before = e;\n\t\t\tif (e.a0 >= r1 - tol && (!after || e.a0 < after.a0)) after = e;\n\t\t}\n\t\tconst starts: { start: number; repeats: number | null }[] = [];\n\t\tif (before && after && after.a0 - before.a1 > len) starts.push({ start: (before.a1 + after.a0 - len) / 2, repeats: null });\n\t\tfor (const { g } of pairs) {\n\t\t\tif (before) starts.push({ start: before.a1 + g, repeats: g });\n\t\t\tif (after) starts.push({ start: after.a0 - g - len, repeats: g });\n\t\t}\n\t\tlet pick: { start: number; repeats: number | null } | null = null;\n\t\tfor (const s of starts) if (Math.abs(s.start - r0) <= tol && (!pick || Math.abs(s.start - r0) < Math.abs(pick.start - r0))) pick = s;\n\t\tif (!pick) return null;\n\t\tconst { start, repeats } = pick;\n\t\tconst at = horizontal ? { ...r, x: start } : { ...r, y: start };\n\t\tconst end = start + len;\n\t\tconst gaps: [number, number, number][] = [];\n\t\tif (before && (repeats === null || Math.abs(start - before.a1 - repeats) <= EQUAL)) gaps.push([before.a1, start, mid(before.b, at)]);\n\t\tif (after && (repeats === null || Math.abs(after.a0 - end - repeats) <= EQUAL)) gaps.push([end, after.a0, mid(after.b, at)]);\n\t\tif (repeats !== null) for (const p of pairs) if (Math.abs(p.g - repeats) <= EQUAL) gaps.push(p.gap);\n\t\treturn { shift: start - r0, gaps };\n\t}\n\n\t/** A gap mark: a line across the gap with a tick at each end, and its length as a label. */\n\tprivate gapMarks([u0, u1, c]: [number, number, number], horizontal: boolean, tick: number, out: VectorSnapGuides) {\n\t\tconst pt = (u: number, v: number): Vec2 => (horizontal ? { x: u, y: v } : { x: v, y: u });\n\t\tout.lines.push(line('spacing', pt(u0, c), pt(u1, c)), line('spacing', pt(u0, c - tick), pt(u0, c + tick)), line('spacing', pt(u1, c - tick), pt(u1, c + tick)));\n\t\tout.labels.push(this.label(pt((u0 + u1) / 2, c), 'spacing', fmtLength(u1 - u0)));\n\t}\n\n\t/** The other objects' side length nearest `length`, within `tol`, or null. */\n\tmatchSize(length: number, tol: number): number | null {\n\t\tlet best: number | null = null;\n\t\tfor (const s of this.sizes) if (Math.abs(s - length) <= tol && (best === null || Math.abs(s - length) < Math.abs(best - length))) best = s;\n\t\treturn best;\n\t}\n\n\t/**\n\t * Snaps a selection-box resize. `sx / sy` are the scale `scaleFor` gave for dragging\n\t * `handle` of `frame` (in the box's own, possibly rotated frame), `mods.shift` keeps the\n\t * proportions and `mods.alt` scales about the centre. The handle lands on an anchor or\n\t * centre within `tol`, else the corner or the side it moves lines up with the nearest\n\t * target, whatever the box's angle; a handle with one way to go (a side, or a proportional\n\t * corner) slides along it until one of them is on a target. An axis that snaps to nothing\n\t * may match another object's width or height instead.\n\t */\n\tsnapScale(\n\t\tframe: VectorBounds & { angle: number },\n\t\thandle: Exclude<VectorTransformHandle, 'rotate'>,\n\t\tsx: number,\n\t\tsy: number,\n\t\tmods: { shift?: boolean; alt?: boolean },\n\t\ttol: number\n\t): VectorScaleSnap {\n\t\tconst toDoc = frame.angle ? rotateMatrix(frame.angle) : IDENTITY_MATRIX;\n\t\tconst toLocal = frame.angle ? rotateMatrix(-frame.angle) : IDENTITY_MATRIX;\n\t\tconst corner = handle.length === 2;\n\t\tconst proportional = !!mods.shift;\n\t\tconst centre = { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 };\n\t\tconst origin = mods.alt ? centre : handlePos(opposite(handle), frame);\n\t\tconst hp = handlePos(handle, frame);\n\t\tconst d0 = { x: hp.x - origin.x, y: hp.y - origin.y };\n\t\tconst valid = (n: number, s: number) => Number.isFinite(n) && n * s > 0;\n\t\tconst nearest = (v: number, lines: readonly LineTarget[]) => {\n\t\t\tlet best: LineTarget | null = null;\n\t\t\tfor (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.v - v)) best = l;\n\t\t\treturn best;\n\t\t};\n\t\ttype Snap = { hx: LineTarget | null; hy: LineTarget | null; on: PointTarget | null };\n\t\tlet nx = sx;\n\t\tlet ny = sy;\n\t\tlet snap: Snap = { hx: null, hy: null, on: null };\n\t\tif (corner && !proportional) {\n\t\t\t// The corner goes anywhere: onto an anchor or centre, else it takes a target's x, its y, or both.\n\t\t\tconst p = applyMatrix(toDoc, { x: origin.x + d0.x * sx, y: origin.y + d0.y * sy });\n\t\t\tconst hx = nearest(p.x, this.xs);\n\t\t\tconst hy = nearest(p.y, this.ys);\n\t\t\tconst on = this.nearestPoint(p, tol);\n\t\t\tconst tries: { tx: number | null; ty: number | null; s: Snap }[] = [];\n\t\t\tif (on) tries.push({ tx: on.p.x, ty: on.p.y, s: { hx: null, hy: null, on } });\n\t\t\ttries.push({ tx: hx?.v ?? null, ty: hy?.v ?? null, s: { hx, hy, on: null } });\n\t\t\ttries.push({ tx: hx?.v ?? null, ty: null, s: { hx, hy: null, on: null } });\n\t\t\ttries.push({ tx: null, ty: hy?.v ?? null, s: { hx: null, hy, on: null } });\n\t\t\tfor (const { tx, ty, s } of tries) {\n\t\t\t\tif (tx === null && ty === null) continue;\n\t\t\t\tconst q = applyMatrix(toLocal, { x: tx ?? p.x, y: ty ?? p.y });\n\t\t\t\tlet cx = (q.x - origin.x) / d0.x;\n\t\t\t\tlet cy = (q.y - origin.y) / d0.y;\n\t\t\t\t// Square to the page, the axis without a target stays exactly where it was.\n\t\t\t\tif (!frame.angle) {\n\t\t\t\t\tif (tx === null) cx = sx;\n\t\t\t\t\tif (ty === null) cy = sy;\n\t\t\t\t}\n\t\t\t\tif (valid(cx, sx) && valid(cy, sy)) {\n\t\t\t\t\tnx = cx;\n\t\t\t\t\tny = cy;\n\t\t\t\t\tsnap = s;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// One parameter `s`: the scale is `c + s·e` on each axis.\n\t\t\tconst movesX = handle === 'e' || handle === 'w';\n\t\t\tlet e: Vec2;\n\t\t\tlet c: Vec2;\n\t\t\tlet s0: number;\n\t\t\tif (corner) [e, c, s0] = [{ x: Math.sign(sx), y: Math.sign(sy) }, { x: 0, y: 0 }, Math.abs(sx)];\n\t\t\telse if (movesX) [e, c, s0] = proportional ? [{ x: 1, y: Math.sign(sx) }, { x: 0, y: 0 }, sx] : [{ x: 1, y: 0 }, { x: 0, y: 1 }, sx];\n\t\t\telse [e, c, s0] = proportional ? [{ x: Math.sign(sy), y: 1 }, { x: 0, y: 0 }, sy] : [{ x: 0, y: 1 }, { x: 1, y: 0 }, sy];\n\t\t\t// The points that may land on a target: the handle, and the two ends of its side.\n\t\t\tconst i = RING.indexOf(handle);\n\t\t\tconst ends = corner ? [] : [RING[(i + 1) % 8], RING[(i + 7) % 8]];\n\t\t\t// How far the handle travels per unit of `s`: a snap may not drag it far from the pointer.\n\t\t\tconst travel = Math.hypot(e.x * d0.x, e.y * d0.y);\n\t\t\tlet best: { s: number; inLine: boolean; moved: number; snap: Snap } | null = null;\n\t\t\tconst consider = (s: number, inLine: boolean, found: Snap) => {\n\t\t\t\tconst moved = Math.abs(s - s0) * travel;\n\t\t\t\tif (!valid(s, s0) || moved > 2 * tol) return;\n\t\t\t\tif (!best || (inLine === best.inLine ? moved < best.moved : !inLine)) best = { s, inLine, moved, snap: found };\n\t\t\t};\n\t\t\tfor (const h of [handle, ...ends]) {\n\t\t\t\tconst hv = handlePos(h, frame);\n\t\t\t\tconst v = { x: hv.x - origin.x, y: hv.y - origin.y };\n\t\t\t\tconst base = applyMatrix(toDoc, { x: origin.x + c.x * v.x, y: origin.y + c.y * v.y });\n\t\t\t\tconst dir = applyMatrix(toDoc, { x: e.x * v.x, y: e.y * v.y });\n\t\t\t\tconst p = { x: base.x + dir.x * s0, y: base.y + dir.y * s0 };\n\t\t\t\tconst l2 = dir.x * dir.x + dir.y * dir.y;\n\t\t\t\tconst on = l2 > 1e-18 ? this.nearestPoint(p, tol) : null;\n\t\t\t\t// An anchor or centre beside its way: it stops at the nearest point of the way.\n\t\t\t\tif (on) consider(((on.p.x - base.x) * dir.x + (on.p.y - base.y) * dir.y) / l2, false, { hx: null, hy: null, on });\n\t\t\t\tif (Math.abs(dir.x) > 1e-9) {\n\t\t\t\t\tconst hit = nearest(p.x, this.xs);\n\t\t\t\t\tif (hit) consider((hit.v - base.x) / dir.x, true, { hx: hit, hy: null, on: null });\n\t\t\t\t}\n\t\t\t\tif (Math.abs(dir.y) > 1e-9) {\n\t\t\t\t\tconst hit = nearest(p.y, this.ys);\n\t\t\t\t\tif (hit) consider((hit.v - base.y) / dir.y, true, { hx: null, hy: hit, on: null });\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst found = best as { s: number; snap: Snap } | null;\n\t\t\tif (found) {\n\t\t\t\tnx = c.x + found.s * e.x;\n\t\t\t\tny = c.y + found.s * e.y;\n\t\t\t\tsnap = found.snap;\n\t\t\t}\n\t\t}\n\t\tconst out: VectorScaleSnap = { sx: nx, sy: ny, snapped: false, lines: [], labels: [] };\n\t\tconst handleAt = () => applyMatrix(toDoc, { x: origin.x + d0.x * out.sx, y: origin.y + d0.y * out.sy });\n\t\tif (snap.on) {\n\t\t\tout.snapped = true;\n\t\t\tout.labels.push(this.label(snap.on.p, snap.on.kind));\n\t\t\treturn out;\n\t\t}\n\t\t// Sides that line up with nothing may match another object's width or height.\n\t\tconst movesX = handle !== 'n' && handle !== 's';\n\t\tconst movesY = handle !== 'e' && handle !== 'w';\n\t\tconst sized: ('x' | 'y')[] = [];\n\t\tif (!proportional) {\n\t\t\tif (movesX && !snap.hx && !(frame.angle && snap.hy) && frame.width > 1e-9) {\n\t\t\t\tconst len = this.matchSize(Math.abs(out.sx) * frame.width, tol);\n\t\t\t\tif (len !== null && len > 0) {\n\t\t\t\t\tout.sx = Math.sign(out.sx || 1) * (len / frame.width);\n\t\t\t\t\tsized.push('x');\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (movesY && !snap.hy && !(frame.angle && snap.hx) && frame.height > 1e-9) {\n\t\t\t\tconst len = this.matchSize(Math.abs(out.sy) * frame.height, tol);\n\t\t\t\tif (len !== null && len > 0) {\n\t\t\t\t\tout.sy = Math.sign(out.sy || 1) * (len / frame.height);\n\t\t\t\t\tsized.push('y');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// The resized box in its frame, and its corners on the page.\n\t\tconst x0 = origin.x + (frame.x - origin.x) * out.sx;\n\t\tconst x1 = origin.x + (frame.x + frame.width - origin.x) * out.sx;\n\t\tconst y0 = origin.y + (frame.y - origin.y) * out.sy;\n\t\tconst y1 = origin.y + (frame.y + frame.height - origin.y) * out.sy;\n\t\tconst box = { x0: Math.min(x0, x1), x1: Math.max(x0, x1), y0: Math.min(y0, y1), y1: Math.max(y0, y1) };\n\t\tconst page = [\n\t\t\t{ x: box.x0, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y1 },\n\t\t\t{ x: box.x0, y: box.y1 }\n\t\t].map((q) => applyMatrix(toDoc, q));\n\t\tconst pminY = Math.min(...page.map((q) => q.y));\n\t\tconst pmaxY = Math.max(...page.map((q) => q.y));\n\t\tconst pminX = Math.min(...page.map((q) => q.x));\n\t\tconst pmaxX = Math.max(...page.map((q) => q.x));\n\t\tif (snap.hx) out.lines.push({ kind: 'align', x1: snap.hx.v, y1: Math.min(snap.hx.from.y, pminY), x2: snap.hx.v, y2: Math.max(snap.hx.from.y, pmaxY) });\n\t\tif (snap.hy) out.lines.push({ kind: 'align', x1: Math.min(snap.hy.from.x, pminX), y1: snap.hy.v, x2: Math.max(snap.hy.from.x, pmaxX), y2: snap.hy.v });\n\t\tif (snap.hx || snap.hy) {\n\t\t\tout.snapped = true;\n\t\t\tout.labels.push(this.label(handleAt(), 'align'));\n\t\t}\n\t\tfor (const axis of sized) {\n\t\t\tout.snapped = true;\n\t\t\t// Along the matched side, just outside the box.\n\t\t\tconst off = tol * 2;\n\t\t\tconst [a, b] = axis === 'x' ? [{ x: box.x0, y: box.y1 + off }, { x: box.x1, y: box.y1 + off }] : [{ x: box.x1 + off, y: box.y0 }, { x: box.x1 + off, y: box.y1 }];\n\t\t\tconst pa = applyMatrix(toDoc, a);\n\t\t\tconst pb = applyMatrix(toDoc, b);\n\t\t\tout.lines.push(line('size', pa, pb));\n\t\t\tout.labels.push(this.label({ x: (pa.x + pb.x) / 2, y: (pa.y + pb.y) / 2 }, 'size', `${axis === 'x' ? 'W' : 'H'} ${fmtLength(axis === 'x' ? box.x1 - box.x0 : box.y1 - box.y0)}`));\n\t\t}\n\t\treturn out;\n\t}\n}\n\n/** The eight resize handles clockwise from the top left (each side sits between its two corners). */\nconst RING: readonly Exclude<VectorTransformHandle, 'rotate'>[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];\n\nfunction opposite(h: Exclude<VectorTransformHandle, 'rotate'>): Exclude<VectorTransformHandle, 'rotate'> {\n\treturn RING[(RING.indexOf(h) + 4) % 8];\n}\n\nfunction handlePos(h: Exclude<VectorTransformHandle, 'rotate'>, r: VectorBounds): Vec2 {\n\tconst x = h.includes('w') ? r.x : h.includes('e') ? r.x + r.width : r.x + r.width / 2;\n\tconst y = h.startsWith('n') ? r.y : h.startsWith('s') ? r.y + r.height : r.y + r.height / 2;\n\treturn { x, y };\n}\n\nfunction line(kind: VectorGuideKind, a: Vec2, b: Vec2): VectorGuideLine {\n\treturn { kind, x1: a.x, y1: a.y, x2: b.x, y2: b.y };\n}\n\n/** The construction guide through `leave.at` nearest `p`, within `tol` (and `p` farther than that from `at`): its direction and where `p` lands. */\nfunction construction(leave: VectorSnapLeave, p: Vec2, tol: number): { dir: Vec2; point: Vec2 } | null {\n\tconst v = { x: p.x - leave.at.x, y: p.y - leave.at.y };\n\tif (Math.hypot(v.x, v.y) <= tol) return null;\n\tlet best: { dir: Vec2; point: Vec2; d: number } | null = null;\n\tfor (const a of leave.angles ?? []) {\n\t\t// Counter-clockwise as seen on the y-down page.\n\t\tconst r = (a * Math.PI) / 180;\n\t\t// Exactly along an axis for multiples of 90°.\n\t\tconst exact = (n: number) => (Math.abs(n) < 1e-12 ? 0 : n);\n\t\tconst dir = { x: exact(Math.cos(r)), y: exact(-Math.sin(r)) };\n\t\tconst k = v.x * dir.x + v.y * dir.y;\n\t\tconst point = { x: leave.at.x + dir.x * k, y: leave.at.y + dir.y * k };\n\t\tconst d = distance(point, p);\n\t\tif (d <= tol && (!best || d < best.d)) best = { dir, point, d };\n\t}\n\treturn best && { dir: best.dir, point: best.point };\n}\n\nconst dotCondition = (r: Point, d: Point) => r[0] * d[0] + r[1] * d[1];\nconst crossCondition = (r: Point, d: Point) => r[0] * d[1] - r[1] * d[0];\n\n/**\n * The points of a segment where `cond(B(t) − base, B′(t))` is zero: sign changes of samples,\n * narrowed by bisection, kept when the normalised condition is (nearly) zero there.\n */\nfunction solveOnSegment(seg: readonly Point[], base: Vec2, cond: (r: Point, d: Point) => number): Vec2[] {\n\tconst b: Point = [base.x, base.y];\n\tconst g = (t: number) => {\n\t\tconst p = segmentPoint(seg, t);\n\t\treturn cond([p[0] - b[0], p[1] - b[1]], segmentDerivative(seg, t));\n\t};\n\tconst vals: number[] = [];\n\tlet scale = 0;\n\tfor (let i = 0; i <= CURVE_SAMPLES; i++) {\n\t\tconst t = i / CURVE_SAMPLES;\n\t\tconst p = segmentPoint(seg, t);\n\t\tconst d = segmentDerivative(seg, t);\n\t\tconst r: Point = [p[0] - b[0], p[1] - b[1]];\n\t\tvals.push(cond(r, d));\n\t\tscale = Math.max(scale, Math.hypot(r[0], r[1]) * Math.hypot(d[0], d[1]));\n\t}\n\t// Every point qualifies (a line seen from a point on it): no particular solution.\n\tif (!(scale > 0) || vals.every((v) => Math.abs(v) <= scale * 1e-12)) return [];\n\tconst out: Vec2[] = [];\n\tfor (let i = 0; i < CURVE_SAMPLES; i++) {\n\t\tconst ga = vals[i];\n\t\tconst gb = vals[i + 1];\n\t\tif (!(Number.isFinite(ga) && Number.isFinite(gb)) || (ga > 0 === gb > 0 && ga !== 0)) continue;\n\t\tlet lo = i / CURVE_SAMPLES;\n\t\tlet hi = (i + 1) / CURVE_SAMPLES;\n\t\tlet flo = ga;\n\t\tfor (let k = 0; k < BISECT; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = g(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm > 0 === flo > 0) {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t} else hi = m;\n\t\t}\n\t\tconst t = (lo + hi) / 2;\n\t\tconst p = segmentPoint(seg, t);\n\t\tconst dv = segmentDerivative(seg, t);\n\t\tconst r = Math.hypot(p[0] - b[0], p[1] - b[1]);\n\t\tconst dl = Math.hypot(dv[0], dv[1]);\n\t\tif (!(r > 1e-9 && dl > 0) || Math.abs(cond([p[0] - b[0], p[1] - b[1]], dv)) > 1e-6 * r * dl) continue;\n\t\tif (!out.some((q) => Math.hypot(q.x - p[0], q.y - p[1]) <= 1e-9 * (1 + r))) out.push({ x: p[0], y: p[1] });\n\t}\n\treturn out;\n}\n","/**\n * Path editing on subpaths in a node's own space: anchor deletion that keeps the shape,\n * segment bending, Curvature-tool anchor moves, cutting at anchors (Scissors), Join, Average,\n * Remove Redundant Points and Smooth.\n *\n * Portions ported from (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md):\n * - vectorcraft-main/crates/pathops/src/edit.rs (`remove_anchor`, `golden_min`, `smooth`,\n * `remove_redundant_points`, `merge_pair`, `average`, `join`)\n * - vectorcraft-main/crates/geom/src/path.rs (`SubPath::cut_at`)\n * - vectorcraft-main/crates/tools/src/draw2/curvature.rs (`curvature_move`)\n * - figcraft-main/crates/engine/src/vectoredit/ops.rs (`bend`)\n */\nimport type { Point } from '../canvas/types.js';\nimport { fitCubicWithTangents } from '../canvas/curveFit.js';\nimport { segmentPoint } from '../canvas/pathops/bezier.js';\nimport { cloneAnchor, inferAnchorType, insertAnchor, moveAnchorHandle, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath, Vec2 } from './types.js';\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nconst unit = (x: number, y: number): Point | null => {\n\tconst l = Math.hypot(x, y);\n\treturn l > 1e-12 && Number.isFinite(l) ? [x / l, y / l] : null;\n};\n\n/** Segment `i` as four control points (a line has its controls at the thirds of its chord). */\nfunction cubicOf(sp: VectorSubpath, i: number): Point[] {\n\tconst s = subpathSegment(sp, i);\n\tif (s.length === 4) return s;\n\tconst [a, b] = s;\n\treturn [a, [a[0] + (b[0] - a[0]) / 3, a[1] + (b[1] - a[1]) / 3], [a[0] + (2 * (b[0] - a[0])) / 3, a[1] + (2 * (b[1] - a[1])) / 3], b];\n}\n\nconst isLine = (sp: VectorSubpath, i: number) => subpathSegment(sp, i).length === 2;\n\n/** Direction the curve leaves `c[0]`. */\nfunction startTangent(c: readonly Point[]): Point {\n\tfor (let k = 1; k < 4; k++) {\n\t\tconst u = unit(c[k][0] - c[0][0], c[k][1] - c[0][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** Direction the curve arrives at `c[3]` (forward along the curve). */\nfunction endTangent(c: readonly Point[]): Point {\n\tfor (let k = 2; k >= 0; k--) {\n\t\tconst u = unit(c[3][0] - c[k][0], c[3][1] - c[k][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** `n + 1` points of a cubic at even parameters (`withStart` false skips the first). */\nfunction sample(c: readonly Point[], n: number, out: Point[], withStart: boolean) {\n\tfor (let i = withStart ? 0 : 1; i <= n; i++) out.push(segmentPoint(c, i / n));\n}\n\nconst onAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n/** Drops handles that sit on their anchor and sets the type the handles show (a symmetric pair that is no longer equal becomes smooth). */\nfunction tidy(a: VectorAnchor, keepType = true): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tif (onAnchor(next, next.in)) delete next.in;\n\tif (onAnchor(next, next.out)) delete next.out;\n\tconst shown = inferAnchorType(next);\n\tconst type = keepType && a.type ? (a.type === 'symmetric' && shown !== 'symmetric' ? (shown === 'corner' ? 'corner' : 'smooth') : a.type === 'smooth' && shown === 'corner' ? 'corner' : a.type) : shown;\n\tif (type === 'corner') delete next.type;\n\telse next.type = type;\n\treturn next;\n}\n\n/** Index of the anchor before / after `i` (round the start of a closed subpath), or -1. */\nfunction neighbours(sp: VectorSubpath, i: number): [number, number] {\n\tconst n = sp.anchors.length;\n\tconst wrap = sp.closed && n > 1;\n\treturn [i > 0 ? i - 1 : wrap ? n - 1 : -1, i < n - 1 ? i + 1 : wrap ? 0 : -1];\n}\n\n// ---------------------------------------------------------------------------\n// Deleting anchors without changing the shape\n// ---------------------------------------------------------------------------\n\n/**\n * The value of `f` with the least error for an argument in [a, b], by a golden-section search\n * (a fixed number of steps). An error that is not a number never wins.\n */\nfunction goldenMin<T extends { error: number }>(f: (x: number) => T, a: number, b: number): T {\n\tconst R = 0.618033988749895;\n\tlet x1 = b - R * (b - a);\n\tlet x2 = a + R * (b - a);\n\tlet f1 = f(x1);\n\tlet f2 = f(x2);\n\tfor (let i = 0; i < 40; i++) {\n\t\tif (f1.error < f2.error || Number.isNaN(f2.error)) {\n\t\t\tb = x2;\n\t\t\tx2 = x1;\n\t\t\tf2 = f1;\n\t\t\tx1 = b - R * (b - a);\n\t\t\tf1 = f(x1);\n\t\t} else {\n\t\t\ta = x1;\n\t\t\tx1 = x2;\n\t\t\tf1 = f2;\n\t\t\tx2 = a + R * (b - a);\n\t\t\tf2 = f(x2);\n\t\t}\n\t}\n\treturn f1.error <= f2.error ? f1 : f2;\n}\n\n/**\n * One cubic through `pts`: `N + 1` samples of a left curve then `N` of a right one. The new\n * curve passes their joint at some parameter k: the left samples sit at k·i/N, the right ones\n * at k + (1 − k)·i/N. Searches k for the closest fit.\n */\nfunction fitAcross(pts: Point[], N: number, t0: Point, t1: Point) {\n\tconst fit = (k: number) => {\n\t\tconst u: number[] = [];\n\t\tfor (let i = 0; i <= N; i++) u.push((k * i) / N);\n\t\tfor (let i = 1; i <= N; i++) u.push(k + ((1 - k) * i) / N);\n\t\treturn fitCubicWithTangents(pts, u, t0, t1);\n\t};\n\treturn goldenMin(fit, 0, 1);\n}\n\n/**\n * Removes anchor `index` without opening the path: its neighbours keep their handle directions\n * and their facing handles are refitted so one cubic follows the two segments that met there\n * as closely as possible (least maximum error over where the new curve passes the removed\n * point). Two straight segments become one; removing an end of an open subpath drops its\n * segment. Returns the subpath unchanged (a copy) when `index` is out of range.\n */\nexport function removeAnchorKeepingShape(sp: VectorSubpath, index: number): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tif (index < 0 || index >= n) return { anchors, closed: sp.closed };\n\tif ((sp.closed || (index > 0 && index < n - 1)) && n >= 3) {\n\t\tconst pi = (index + n - 1) % n;\n\t\tconst ni = (index + 1) % n;\n\t\tif (!(isLine(sp, pi) && isLine(sp, index))) {\n\t\t\tconst left = cubicOf(sp, pi);\n\t\t\tconst right = cubicOf(sp, index);\n\t\t\tconst N = 16;\n\t\t\tconst pts: Point[] = [];\n\t\t\tsample(left, N, pts, true);\n\t\t\tsample(right, N, pts, false);\n\t\t\tconst t0 = startTangent(left);\n\t\t\tconst t1 = endTangent(right);\n\t\t\tconst { curve } = fitAcross(pts, N, t0, t1);\n\t\t\tif ([curve.p1, curve.p2].every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) {\n\t\t\t\tanchors[pi] = tidy({ ...anchors[pi], out: { x: curve.p1[0], y: curve.p1[1] } });\n\t\t\t\tanchors[ni] = tidy({ ...anchors[ni], in: { x: curve.p2[0], y: curve.p2[1] } });\n\t\t\t}\n\t\t}\n\t}\n\tanchors.splice(index, 1);\n\tlet closed = sp.closed;\n\tif (!closed && anchors.length) {\n\t\t// A new end has nothing beyond it.\n\t\tanchors[0] = tidy({ ...anchors[0], in: null });\n\t\tconst last = anchors.length - 1;\n\t\tanchors[last] = tidy({ ...anchors[last], out: null });\n\t}\n\tif (anchors.length < 3) closed = closed && anchors.length === 2 && anchors.some((a) => a.in || a.out);\n\treturn { anchors, closed };\n}\n\n/** Removes several anchors of a subpath, keeping the shape (see `removeAnchorKeepingShape`). */\nexport function removeAnchorsKeepingShape(sp: VectorSubpath, indices: readonly number[]): VectorSubpath {\n\tconst order = [...new Set(indices)].filter((i) => i >= 0 && i < sp.anchors.length).sort((a, b) => b - a);\n\treturn order.reduce((acc, i) => removeAnchorKeepingShape(acc, i), { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed });\n}\n\n// ---------------------------------------------------------------------------\n// Bending a segment\n// ---------------------------------------------------------------------------\n\n/**\n * Bends segment `segment` so the curve passes through `p` at parameter `t` (clamped to\n * 0.05–0.95): its handles go to the thirds of the chord plus one shared offset, so\n * `B(t) = L(t) + 3t(1 − t)·offset` exactly. The end anchors keep their types (a smooth or\n * symmetric end turns its other handle to stay in line).\n */\nexport function bendSegment(sp: VectorSubpath, segment: number, t: number, p: Vec2): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tif (segment < 0 || segment >= subpathSegmentCount(sp) || !Number.isFinite(t) || !Number.isFinite(p.x) || !Number.isFinite(p.y)) return { anchors, closed: sp.closed };\n\tconst tc = Math.min(0.95, Math.max(0.05, t));\n\tconst ia = segment;\n\tconst ib = (segment + 1) % n;\n\tconst a = anchors[ia];\n\tconst b = anchors[ib];\n\tconst k = 3 * tc * (1 - tc);\n\tconst ox = (p.x - (a.x + (b.x - a.x) * tc)) / k;\n\tconst oy = (p.y - (a.y + (b.y - a.y) * tc)) / k;\n\tconst c1 = { x: a.x + (b.x - a.x) / 3 + ox, y: a.y + (b.y - a.y) / 3 + oy };\n\tconst c2 = { x: b.x + (a.x - b.x) / 3 + ox, y: b.y + (a.y - b.y) / 3 + oy };\n\tanchors[ia] = moveAnchorHandle(a, 'out', c1);\n\tanchors[ib] = moveAnchorHandle(b, 'in', c2);\n\treturn { anchors, closed: sp.closed };\n}\n\n/** The point at parameter `t` of segment `segment` (for tests and previews). */\nexport function subpathPointAt(sp: VectorSubpath, segment: number, t: number): Vec2 {\n\tconst [x, y] = segmentPoint(subpathSegment(sp, segment), t);\n\treturn { x, y };\n}\n\n// ---------------------------------------------------------------------------\n// Curvature-tool anchor move\n// ---------------------------------------------------------------------------\n\n/**\n * Moves anchor `index` to `q` the way the Curvature tool drags a point: only the two segments\n * at it change. A smooth or symmetric anchor turns its handles along the line through its\n * neighbours; the neighbours' handles on those segments, and a corner's own handles, keep\n * their directions while their lengths scale with their segment's chord, so the segments\n * beyond don't move and a corner without handles keeps none.\n */\nexport function curvatureMoveAnchor(sp: VectorSubpath, index: number, q: Vec2): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst a = sp.anchors[index];\n\tif (!a) return { anchors, closed: sp.closed };\n\tconst own: [Vec2 | null, Vec2 | null] = [\n\t\ta.in && !onAnchor(a, a.in) ? { x: a.in.x - a.x, y: a.in.y - a.y } : null,\n\t\ta.out && !onAnchor(a, a.out) ? { x: a.out.x - a.x, y: a.out.y - a.y } : null\n\t];\n\tconst ends: [Vec2 | null, Vec2 | null] = [null, null];\n\tneighbours(sp, index).forEach((j, side) => {\n\t\tif (j < 0 || j === index) return;\n\t\tconst b = anchors[j];\n\t\tconst old = Math.hypot(a.x - b.x, a.y - b.y);\n\t\tconst s = old > 1e-9 ? Math.hypot(q.x - b.x, q.y - b.y) / old : 1;\n\t\tconst key = side === 0 ? 'out' : 'in';\n\t\tconst h = b[key];\n\t\tif (h) b[key] = { x: b.x + (h.x - b.x) * s, y: b.y + (h.y - b.y) * s };\n\t\tconst o = own[side];\n\t\tif (o) own[side] = { x: o.x * s, y: o.y * s };\n\t\tends[side] = { x: b.x, y: b.y };\n\t});\n\tconst moved: VectorAnchor = { x: q.x, y: q.y };\n\tif (own[0]) moved.in = { x: q.x + own[0].x, y: q.y + own[0].y };\n\tif (own[1]) moved.out = { x: q.x + own[1].x, y: q.y + own[1].y };\n\tif (a.type) moved.type = a.type;\n\tif (a.corner) moved.corner = { ...a.corner };\n\tconst [prev, next] = ends;\n\tif (a.type && a.type !== 'corner' && prev && next) {\n\t\tconst dx = next.x - prev.x;\n\t\tconst dy = next.y - prev.y;\n\t\tconst l = Math.hypot(dx, dy);\n\t\tif (l > 1e-9) {\n\t\t\t// A handle it lacks comes out a third of the way to that side's neighbour.\n\t\t\tconst len = (h: Vec2 | null, to: Vec2) => (h ? Math.hypot(h.x, h.y) : Math.hypot(q.x - to.x, q.y - to.y) / 3);\n\t\t\tlet li = len(own[0], prev);\n\t\t\tlet lo = len(own[1], next);\n\t\t\tif (a.type === 'symmetric') li = lo = (li + lo) / 2;\n\t\t\tmoved.in = { x: q.x - (dx * li) / l, y: q.y - (dy * li) / l };\n\t\t\tmoved.out = { x: q.x + (dx * lo) / l, y: q.y + (dy * lo) / l };\n\t\t}\n\t}\n\tanchors[index] = moved;\n\treturn { anchors, closed: sp.closed };\n}\n\n// ---------------------------------------------------------------------------\n// Scissors\n// ---------------------------------------------------------------------------\n\n/**\n * Cuts a subpath at the anchors `at`: each becomes the end of one open piece and the start of\n * the next, its handle off each piece dropped (the shape doesn't change). A closed subpath\n * opens at its first cut, so one cut leaves one piece whose ends coincide. The ends of an open\n * subpath and indices out of range don't cut; with no cut left the subpath comes back as it is.\n */\nexport function cutSubpathAt(sp: VectorSubpath, at: readonly number[]): VectorSubpath[] {\n\tconst n = sp.anchors.length;\n\tconst cuts = [...new Set(at)].filter((i) => Number.isInteger(i) && i >= 0 && i < n && (sp.closed || (i > 0 && i < n - 1))).sort((a, b) => a - b);\n\tif (!cuts.length || n < 2) return [{ anchors: sp.anchors.map(cloneAnchor), closed: sp.closed }];\n\tconst first = cuts[0];\n\t// A closed subpath's anchors from the first cut round to it again; an open one's as they are.\n\tconst run = sp.closed ? Array.from({ length: n + 1 }, (_, i) => sp.anchors[(first + i) % n]) : sp.anchors;\n\tconst cutSet = new Set(sp.closed ? [...cuts.map((c) => (c - first + n) % n), n] : cuts);\n\tconst pieces: VectorSubpath[] = [];\n\tlet cur: VectorAnchor[] = [];\n\trun.forEach((a, i) => {\n\t\tif (!cutSet.has(i)) {\n\t\t\tcur.push(cloneAnchor(a));\n\t\t\treturn;\n\t\t}\n\t\tif (cur.length) {\n\t\t\tcur.push(tidy({ ...a, out: null }, false));\n\t\t\tpieces.push({ anchors: cur, closed: false });\n\t\t\tcur = [];\n\t\t}\n\t\tif (i < n) cur.push(tidy({ ...a, in: null }, false));\n\t});\n\tif (cur.length > 1) pieces.push({ anchors: cur, closed: false });\n\treturn pieces;\n}\n\n/**\n * Cuts a subpath at parameter `t` of segment `segment` (Scissors on a segment): an anchor is\n * inserted there without changing the shape, then cut. Within `endTolerance` of the segment's\n * ends (in parameter) the existing anchor is cut instead.\n */\nexport function splitSubpathAt(sp: VectorSubpath, segment: number, t: number, endTolerance = 1e-6): VectorSubpath[] {\n\tconst n = sp.anchors.length;\n\tif (segment < 0 || segment >= subpathSegmentCount(sp)) return [{ anchors: sp.anchors.map(cloneAnchor), closed: sp.closed }];\n\tif (t <= endTolerance) return cutSubpathAt(sp, [segment]);\n\tif (t >= 1 - endTolerance) return cutSubpathAt(sp, [(segment + 1) % n]);\n\tconst { subpath, index } = insertAnchor(sp, segment, t);\n\treturn cutSubpathAt(subpath, [index]);\n}\n\n// ---------------------------------------------------------------------------\n// Join\n// ---------------------------------------------------------------------------\n\nconst endOf = (sp: VectorSubpath, last: boolean): VectorAnchor => sp.anchors[last ? sp.anchors.length - 1 : 0];\nconst dist = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\n\nfunction reverse(sp: VectorSubpath): VectorSubpath {\n\treturn {\n\t\tclosed: sp.closed,\n\t\tanchors: sp.anchors\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.map((a) => {\n\t\t\t\tconst next: VectorAnchor = { x: a.x, y: a.y };\n\t\t\t\tif (a.out) next.in = { ...a.out };\n\t\t\t\tif (a.in) next.out = { ...a.in };\n\t\t\t\tif (a.type) next.type = a.type;\n\t\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\t\treturn next;\n\t\t\t})\n\t};\n}\n\n/**\n * Join: open subpaths are joined nearest-endpoints-first into one open subpath (endpoints\n * within `tolerance` merge into one anchor, otherwise a straight segment connects them). A\n * single open subpath is closed instead (its ends merged when they meet). Closed subpaths and\n * lone anchors pass through unchanged, before the joined one.\n */\nexport function joinSubpaths(subpaths: readonly VectorSubpath[], tolerance: number): VectorSubpath[] {\n\tconst closed: VectorSubpath[] = [];\n\tlet open: VectorSubpath[] = [];\n\tfor (const sp of subpaths) {\n\t\tconst copy = { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n\t\tif (sp.closed || sp.anchors.length < 2) {\n\t\t\tif (sp.anchors.length) closed.push(copy);\n\t\t} else open.push(copy);\n\t}\n\tif (open.length === 1) {\n\t\tconst sp = open[0];\n\t\tconst first = sp.anchors[0];\n\t\tconst last = sp.anchors[sp.anchors.length - 1];\n\t\tif (sp.anchors.length > 2 && dist(first, last) <= tolerance) {\n\t\t\tsp.anchors.pop();\n\t\t\tsp.anchors[0] = tidy({ ...first, in: last.in ?? null }, false);\n\t\t} else {\n\t\t\tsp.anchors[0] = tidy({ ...first, in: null }, false);\n\t\t\tsp.anchors[sp.anchors.length - 1] = tidy({ ...sp.anchors[sp.anchors.length - 1], out: null }, false);\n\t\t}\n\t\tsp.closed = true;\n\t\treturn [...closed, sp];\n\t}\n\twhile (open.length > 1) {\n\t\t// The closest pair of endpoints on different subpaths.\n\t\tlet best = { d: Infinity, i: 0, j: 1, ei: true, ej: false };\n\t\tfor (let i = 0; i < open.length; i++) {\n\t\t\tfor (let j = i + 1; j < open.length; j++) {\n\t\t\t\tfor (const ei of [false, true]) {\n\t\t\t\t\tfor (const ej of [false, true]) {\n\t\t\t\t\t\tconst d = dist(endOf(open[i], ei), endOf(open[j], ej));\n\t\t\t\t\t\tif (d < best.d) best = { d, i, j, ei, ej };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet a = open[best.i];\n\t\tlet b = open[best.j];\n\t\topen = open.filter((_, k) => k !== best.j);\n\t\t// `a` ends at the meeting point, `b` starts there.\n\t\tif (!best.ei) a = reverse(a);\n\t\tif (best.ej) b = reverse(b);\n\t\tconst anchors = a.anchors;\n\t\tif (best.d <= tolerance) {\n\t\t\tconst [head, ...rest] = b.anchors;\n\t\t\tconst l = anchors[anchors.length - 1];\n\t\t\tanchors[anchors.length - 1] = tidy({ ...l, out: head.out ?? null }, false);\n\t\t\tanchors.push(...rest);\n\t\t} else {\n\t\t\tconst l = anchors[anchors.length - 1];\n\t\t\tanchors[anchors.length - 1] = tidy({ ...l, out: null }, false);\n\t\t\tanchors.push(tidy({ ...b.anchors[0], in: null }, false), ...b.anchors.slice(1));\n\t\t}\n\t\topen[best.i > best.j ? best.i - 1 : best.i] = { anchors, closed: false };\n\t}\n\treturn [...closed, ...open];\n}\n\n// ---------------------------------------------------------------------------\n// Smooth and Remove Redundant Points\n// ---------------------------------------------------------------------------\n\n/**\n * Smooth: pulls handles towards Catmull-Rom-like tangents (a third of the way to each\n * neighbour along the line through both). `amount` 0–1 (0 = unchanged, 1 = fully smooth).\n * Only the anchors in `only` change when it is given; endpoints of open subpaths keep their\n * handles. Subpaths of fewer than three anchors are unchanged.\n */\nexport function smoothSubpath(sp: VectorSubpath, amount = 1, only?: ReadonlySet<number>): VectorSubpath {\n\tconst t = Math.min(1, Math.max(0, amount));\n\tconst orig = sp.anchors;\n\tconst n = orig.length;\n\tconst anchors = orig.map(cloneAnchor);\n\tif (n < 3 || t === 0) return { anchors, closed: sp.closed };\n\tfor (let i = 0; i < n; i++) {\n\t\tif (!sp.closed && (i === 0 || i === n - 1)) continue;\n\t\tif (only && !only.has(i)) continue;\n\t\tconst prev = orig[(i + n - 1) % n];\n\t\tconst next = orig[(i + 1) % n];\n\t\tconst p = orig[i];\n\t\tconst dir = unit(next.x - prev.x, next.y - prev.y);\n\t\tif (!dir) continue;\n\t\tconst li = dist(p, prev) / 3;\n\t\tconst lo = dist(p, next) / 3;\n\t\tconst hin = p.in ?? p;\n\t\tconst hout = p.out ?? p;\n\t\tconst target = (h: Vec2, x: number, y: number) => ({ x: h.x + (x - h.x) * t, y: h.y + (y - h.y) * t });\n\t\tanchors[i] = tidy(\n\t\t\t{\n\t\t\t\tx: p.x,\n\t\t\t\ty: p.y,\n\t\t\t\tin: target(hin, p.x - dir[0] * li, p.y - dir[1] * li),\n\t\t\t\tout: target(hout, p.x + dir[0] * lo, p.y + dir[1] * lo)\n\t\t\t},\n\t\t\tfalse\n\t\t);\n\t}\n\treturn { anchors, closed: sp.closed };\n}\n\ninterface Seg {\n\tc: Point[];\n\tline: boolean;\n}\n\nfunction segsOf(sp: VectorSubpath): Seg[] {\n\tconst out: Seg[] = [];\n\tfor (let i = 0; i < subpathSegmentCount(sp); i++) {\n\t\tconst s = subpathSegment(sp, i);\n\t\tout.push(s.length === 2 ? { c: s, line: true } : { c: s, line: false });\n\t}\n\treturn out;\n}\n\n/** A subpath from consecutive segments (anchor types inferred; original types kept where they still hold). */\nfunction segsToSubpath(segs: readonly Seg[], closed: boolean, types: Map<string, VectorAnchor['type']>): VectorSubpath | null {\n\tif (!segs.length) return null;\n\tconst anchors: VectorAnchor[] = [];\n\tconst at = (p: Point): VectorAnchor => ({ x: p[0], y: p[1] });\n\tanchors.push(at(segs[0].c[0]));\n\tfor (const s of segs) {\n\t\tconst end = s.c[s.c.length - 1];\n\t\tif (!s.line) anchors[anchors.length - 1].out = { x: s.c[1][0], y: s.c[1][1] };\n\t\tconst next = at(end);\n\t\tif (!s.line) next.in = { x: s.c[2][0], y: s.c[2][1] };\n\t\tanchors.push(next);\n\t}\n\tif (closed) {\n\t\tconst last = anchors.pop()!;\n\t\tif (last.in) anchors[0].in = last.in;\n\t}\n\tconst typed = anchors.map((a) => {\n\t\tconst type = types.get(`${a.x},${a.y}`);\n\t\treturn tidy(type ? { ...a, type } : a, !!type);\n\t});\n\treturn { anchors: typed, closed };\n}\n\nconst isZeroSeg = (s: Seg) => s.c.every((p) => Math.abs(p[0] - s.c[0][0]) < 1e-9 && Math.abs(p[1] - s.c[0][1]) < 1e-9);\n\n/** One segment replacing `a` then `b` within `tol`, or null. */\nfunction mergePair(a: Seg, b: Seg, tol: number): Seg | null {\n\tconst a0 = a.c[0];\n\tconst a3 = a.c[a.c.length - 1];\n\tconst b3 = b.c[b.c.length - 1];\n\tif (a.line && b.line) {\n\t\tconst cx = b3[0] - a0[0];\n\t\tconst cy = b3[1] - a0[1];\n\t\tconst len = Math.hypot(cx, cy);\n\t\tif (len < 1e-12) return null;\n\t\tconst mx = a3[0] - a0[0];\n\t\tconst my = a3[1] - a0[1];\n\t\tconst along = (mx * cx + my * cy) / len;\n\t\treturn Math.abs((mx * cy - my * cx) / len) <= tol && along >= 0 && along <= len ? { c: [a0, b3], line: true } : null;\n\t}\n\tconst ca = a.line ? [a0, a0, a3, a3] : a.c;\n\tconst cb = b.line ? [a3, a3, b3, b3] : b.c;\n\tconst ta = endTangent(ca);\n\tconst tb = startTangent(cb);\n\t// Only merge across (near-)smooth joints.\n\tif (ta[0] * tb[0] + ta[1] * tb[1] < 0.99) return null;\n\tconst pts: Point[] = [];\n\tsample(ca, 16, pts, true);\n\tsample(cb, 16, pts, false);\n\tconst { curve, error } = fitAcross(pts, 16, startTangent(ca), endTangent(cb));\n\treturn error <= tol ? { c: [curve.p0, curve.p1, curve.p2, curve.p3], line: false } : null;\n}\n\n/**\n * Remove Redundant Points: drops anchors that can go without changing the shape by more than\n * `tolerance` (collinear corners, duplicate points, and smooth joints that one cubic can\n * replace).\n */\nexport function removeRedundantPoints(sp: VectorSubpath, tolerance: number): VectorSubpath {\n\tconst tol = Math.max(tolerance, 1e-9);\n\tconst types = new Map(sp.anchors.filter((a) => a.type).map((a) => [`${a.x},${a.y}`, a.type] as const));\n\tconst segs = segsOf(sp).filter((s) => !isZeroSeg(s));\n\tif (!segs.length) return { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n\tconst minSegs = sp.closed ? 2 : 1;\n\tlet changed = true;\n\twhile (changed && segs.length > minSegs) {\n\t\tchanged = false;\n\t\tconst n = segs.length;\n\t\tconst joints = sp.closed ? n : n - 1;\n\t\tfor (let j = 0; j < joints; j++) {\n\t\t\tconst [i0, i1] = sp.closed ? [(j + n - 1) % n, j] : [j, j + 1];\n\t\t\tconst m = mergePair(segs[i0], segs[i1], tol);\n\t\t\tif (!m) continue;\n\t\t\tsegs[i0] = m;\n\t\t\tsegs.splice(i1, 1);\n\t\t\t// The merged segment now starts the loop.\n\t\t\tif (sp.closed && i1 === 0) segs.unshift(segs.pop()!);\n\t\t\tchanged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn segsToSubpath(segs, sp.closed, types) ?? { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n}\n","/**\n * Knife and eraser on Bézier paths, built on the curve booleans and `outlineStroke`.\n *\n * The knife cuts filled regions along a polyline with no gap: each stretch of the polyline\n * that crosses a region from boundary to boundary (a chord) splits the boundary loop it starts\n * and ends on into two loops sharing that chord, or, when it joins two loops (an outline and a\n * hole), merges them into one. Crossings are exact (line–cubic roots), and the pieces share\n * the cut edge exactly.\n *\n * The eraser removes the area of a round-capped stroke along a polyline: filled shapes lose it\n * by a boolean difference; outlines are cut where they cross the stroke's outline (exact\n * curve–curve intersections) and keep the parts outside it.\n *\n * Modelled on vectorcraft-main/crates/engine/src/cmd/draw2.rs (`knife`, `erase_region`,\n * `erase_outline`, `cut_subpath`; MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md), without its fixed knife slit and its sampled crossing search.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcloseContour,\n\tcontourSignedArea,\n\tcontoursToPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentBounds,\n\tsegmentPoint,\n\tsubSegment,\n\twindingNumber,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport { normalizeBezierPath, pathBoolean, segmentIntersections } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport { inferAnchorType, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath } from './types.js';\n\ntype FillRule = 'nonzero' | 'evenodd';\n\n// ---------------------------------------------------------------------------\n// Faces: an outer loop with its holes\n// ---------------------------------------------------------------------------\n\ninterface Loop {\n\tsegs: Point[][];\n\t/** Which segments came from a knife chord (not sampled for containment). */\n\tchord: boolean[];\n}\n\ninterface Face {\n\tloops: Loop[];\n}\n\nconst loopArea = (l: Loop) => contourSignedArea(l.segs);\n\n/** A point on the loop that is not on a chord (chords are shared with a neighbouring piece). */\nfunction loopSample(l: Loop): Point {\n\tconst k = l.chord.findIndex((c) => !c);\n\treturn segmentPoint(l.segs[k >= 0 ? k : 0], 0.5);\n}\n\nconst contains = (l: Loop, p: Point) => windingNumber([l.segs], p) !== 0;\n\n/**\n * Groups non-crossing loops into faces: loops turning like the largest one are outlines, the\n * others holes of the smallest outline around them.\n */\nfunction groupFaces(loops: Loop[]): Face[] {\n\tconst usable = loops.filter((l) => l.segs.length && Math.abs(loopArea(l)) > 1e-12);\n\tif (!usable.length) return [];\n\tconst largest = usable.reduce((a, b) => (Math.abs(loopArea(b)) > Math.abs(loopArea(a)) ? b : a));\n\tconst sign = Math.sign(loopArea(largest));\n\tconst outers = usable.filter((l) => Math.sign(loopArea(l)) === sign).sort((a, b) => Math.abs(loopArea(a)) - Math.abs(loopArea(b)));\n\tconst faces = new Map<Loop, Face>(outers.map((o) => [o, { loops: [o] }]));\n\tfor (const hole of usable.filter((l) => Math.sign(loopArea(l)) !== sign)) {\n\t\tconst p = loopSample(hole);\n\t\tconst parent = outers.find((o) => Math.abs(loopArea(o)) > Math.abs(loopArea(hole)) && contains(o, p));\n\t\tif (parent) faces.get(parent)!.loops.push(hole);\n\t}\n\treturn outers.reverse().map((o) => faces.get(o)!);\n}\n\nfunction faceToPath(face: Face): BezierPath {\n\treturn contoursToPath(face.loops.map((l) => ({ segments: l.segs, closed: true })));\n}\n\n/** Simple, consistently oriented faces of a filled path. */\nfunction facesOf(path: BezierPathInput, fillRule: FillRule): Face[] {\n\tconst normalized = normalizeBezierPath(path, fillRule);\n\tconst loops = pathToContours(normalized).map((c) => {\n\t\tconst segs = closeContour(c, true).map((s) => s.slice());\n\t\treturn { segs, chord: segs.map(() => false) };\n\t});\n\treturn groupFaces(loops);\n}\n\n/** One path per face (an outline with its holes) of a filled path, largest first. */\nexport function splitIntoFaces(path: BezierPathInput, fillRule: FillRule = 'nonzero'): BezierPath[] {\n\treturn facesOf(path, fillRule).map(faceToPath);\n}\n\n// ---------------------------------------------------------------------------\n// Line × segment crossings\n// ---------------------------------------------------------------------------\n\n/** Real roots in [0, 1] of `a·t³ + b·t² + c·t + d` (monotone pieces, bisection). */\nfunction rootsInUnit(a: number, b: number, c: number, d: number, scale: number): number[] {\n\tconst f = (t: number) => ((a * t + b) * t + c) * t + d;\n\tconst tol = 1e-12 * Math.max(1, scale);\n\t// Critical points split [0, 1] into monotone pieces.\n\tconst cuts = [0];\n\tconst qa = 3 * a;\n\tconst qb = 2 * b;\n\tif (Math.abs(qa) > 1e-18) {\n\t\tconst disc = qb * qb - 4 * qa * c;\n\t\tif (disc >= 0) {\n\t\t\tconst r = Math.sqrt(disc);\n\t\t\tfor (const t of [(-qb - r) / (2 * qa), (-qb + r) / (2 * qa)].sort((x, y) => x - y)) if (t > 0 && t < 1) cuts.push(t);\n\t\t}\n\t} else if (Math.abs(qb) > 1e-18) {\n\t\tconst t = -c / qb;\n\t\tif (t > 0 && t < 1) cuts.push(t);\n\t}\n\tcuts.push(1);\n\tconst roots: number[] = [];\n\tconst push = (t: number) => {\n\t\tif (!roots.some((r) => Math.abs(r - t) < 1e-9)) roots.push(t);\n\t};\n\tfor (let i = 0; i < cuts.length - 1; i++) {\n\t\tlet lo = cuts[i];\n\t\tlet hi = cuts[i + 1];\n\t\tlet flo = f(lo);\n\t\tconst fhi = f(hi);\n\t\tif (Math.abs(flo) <= tol) push(lo);\n\t\tif (Math.abs(fhi) <= tol) push(hi);\n\t\tif (flo * fhi >= 0) continue;\n\t\tfor (let k = 0; k < 80; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = f(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm * flo < 0) hi = m;\n\t\t\telse {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t}\n\t\t}\n\t\tpush((lo + hi) / 2);\n\t}\n\treturn roots.sort((x, y) => x - y);\n}\n\n/** Where the line `p → q` crosses a segment: `s` on the line (0–1), `t` on the segment. Parallel overlaps are not crossings. */\nfunction lineHits(p: Point, q: Point, seg: readonly Point[]): { s: number; t: number; point: Point }[] {\n\tconst dx = q[0] - p[0];\n\tconst dy = q[1] - p[1];\n\tconst len2 = dx * dx + dy * dy;\n\tif (len2 < 1e-24) return [];\n\t// Signed distance (times |d|) of the segment from the line, as a polynomial in t.\n\tconst h = (pt: Point) => (pt[0] - p[0]) * -dy + (pt[1] - p[1]) * dx;\n\tlet coeffs: [number, number, number, number];\n\tif (seg.length === 2) coeffs = [0, 0, h(seg[1]) - h(seg[0]), h(seg[0])];\n\telse {\n\t\tconst [h0, h1, h2, h3] = seg.map(h);\n\t\tcoeffs = [-h0 + 3 * h1 - 3 * h2 + h3, 3 * h0 - 6 * h1 + 3 * h2, -3 * h0 + 3 * h1, h0];\n\t}\n\tif (coeffs.every((c) => Math.abs(c) < 1e-12 * Math.max(1, len2))) return [];\n\tconst scale = Math.sqrt(len2) * Math.max(1, ...seg.map((pt) => Math.abs(pt[0]) + Math.abs(pt[1])));\n\tconst out: { s: number; t: number; point: Point }[] = [];\n\tfor (const t of rootsInUnit(...coeffs, scale)) {\n\t\tconst point = segmentPoint(seg, t);\n\t\tconst s = ((point[0] - p[0]) * dx + (point[1] - p[1]) * dy) / len2;\n\t\tif (s >= -1e-9 && s <= 1 + 1e-9) out.push({ s: Math.min(1, Math.max(0, s)), t, point });\n\t}\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Knife\n// ---------------------------------------------------------------------------\n\ninterface Hit {\n\t/** Knife position: segment index + parameter. */\n\ts: number;\n\tloop: number;\n\tseg: number;\n\tt: number;\n\tpoint: Point;\n}\n\nconst near = (a: Point, b: Point, eps: number) => Math.abs(a[0] - b[0]) <= eps && Math.abs(a[1] - b[1]) <= eps;\nconst degenerate = (seg: readonly Point[], eps: number) => seg.every((p) => near(p, seg[0], eps));\n\n/** The loop's pieces from (seg a, t a) forward to (seg b, t b); `full` goes all the way round when they coincide. */\nfunction arc(l: Loop, a: { seg: number; t: number }, b: { seg: number; t: number }, eps: number): { segs: Point[][]; chord: boolean[] } {\n\tconst n = l.segs.length;\n\tconst segs: Point[][] = [];\n\tconst chord: boolean[] = [];\n\tconst push = (k: number, t0: number, t1: number) => {\n\t\tconst piece = t0 <= 0 && t1 >= 1 ? l.segs[k].slice() : subSegment(l.segs[k], t0, t1);\n\t\tif (!degenerate(piece, eps)) {\n\t\t\tsegs.push(piece);\n\t\t\tchord.push(l.chord[k]);\n\t\t}\n\t};\n\tif (a.seg === b.seg && b.t >= a.t + 1e-12) {\n\t\tpush(a.seg, a.t, b.t);\n\t\treturn { segs, chord };\n\t}\n\tpush(a.seg, a.t, 1);\n\tfor (let k = (a.seg + 1) % n; k !== b.seg; k = (k + 1) % n) push(k, 0, 1);\n\tpush(b.seg, 0, b.t);\n\treturn { segs, chord };\n}\n\n/** Line segments through `points`. */\nfunction polySegs(points: readonly Point[], eps: number): Point[][] {\n\tconst out: Point[][] = [];\n\tfor (let i = 1; i < points.length; i++) if (!near(points[i - 1], points[i], eps)) out.push([points[i - 1], points[i]]);\n\treturn out;\n}\n\n/**\n * Cuts the filled path along the open polyline `knife`. Returns one path per resulting face\n * (an outline with its holes), or null when the knife crossed nothing from edge to edge. A\n * stretch of the knife that starts or ends inside the shape does not cut.\n */\nexport function knifePath(path: BezierPathInput, fillRule: FillRule, knife: readonly Point[]): BezierPath[] | null {\n\tconst pts = knife.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tif (pts.length < 2) return null;\n\tlet faces = facesOf(path, fillRule);\n\tif (!faces.length) return null;\n\tconst b = bezierPathBounds(path);\n\tconst size = b ? Math.max(b.maxX - b.minX, b.maxY - b.minY, 1) : 1;\n\tconst eps = size * 1e-9;\n\tlet cursor = -Infinity;\n\tlet cuts = 0;\n\tfor (let guard = 0; guard < 512; guard++) {\n\t\tlet best: { face: number; from: Hit; to: Hit } | null = null;\n\t\tfaces.forEach((face, fi) => {\n\t\t\tconst hits: Hit[] = [];\n\t\t\tfor (let m = 0; m < pts.length - 1; m++) {\n\t\t\t\tif (m + 1 < cursor - 1e-9) continue;\n\t\t\t\tconst kb = { minX: Math.min(pts[m][0], pts[m + 1][0]), maxX: Math.max(pts[m][0], pts[m + 1][0]), minY: Math.min(pts[m][1], pts[m + 1][1]), maxY: Math.max(pts[m][1], pts[m + 1][1]) };\n\t\t\t\tface.loops.forEach((l, li) =>\n\t\t\t\t\tl.segs.forEach((seg, si) => {\n\t\t\t\t\t\tconst sb = segmentBounds(seg);\n\t\t\t\t\t\tif (sb.maxX < kb.minX - eps || sb.minX > kb.maxX + eps || sb.maxY < kb.minY - eps || sb.minY > kb.maxY + eps) return;\n\t\t\t\t\t\tfor (const h of lineHits(pts[m], pts[m + 1], seg)) {\n\t\t\t\t\t\t\tconst s = m + h.s;\n\t\t\t\t\t\t\tif (s >= cursor - 1e-9) hits.push({ s, loop: li, seg: si, t: h.t, point: h.point });\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\thits.sort((x, y) => x.s - y.s);\n\t\t\tconst unique = hits.filter((h, i) => i === 0 || h.s - hits[i - 1].s > 1e-9 || !near(h.point, hits[i - 1].point, eps * 10));\n\t\t\tconst inside = (s: number) => {\n\t\t\t\tconst m = Math.min(pts.length - 2, Math.floor(s));\n\t\t\t\tconst u = s - m;\n\t\t\t\tconst q: Point = [pts[m][0] + (pts[m + 1][0] - pts[m][0]) * u, pts[m][1] + (pts[m + 1][1] - pts[m][1]) * u];\n\t\t\t\treturn windingNumber(face.loops.map((l) => l.segs), q) !== 0;\n\t\t\t};\n\t\t\tfor (let i = 0; i < unique.length - 1; i++) {\n\t\t\t\tconst from = unique[i];\n\t\t\t\tconst to = unique[i + 1];\n\t\t\t\tif (near(from.point, to.point, eps * 10) || !inside((from.s + to.s) / 2)) continue;\n\t\t\t\tif (!best || from.s < best.from.s) best = { face: fi, from, to };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tif (!best) break;\n\t\tconst { face: fi, from, to } = best as { face: number; from: Hit; to: Hit };\n\t\tconst face = faces[fi];\n\t\t// The chord: the crossing points with the knife's corners between them.\n\t\tconst corners: Point[] = [from.point];\n\t\tfor (let m = Math.floor(from.s) + 1; m <= to.s - 1e-12 && m < pts.length; m++) if (m > from.s) corners.push(pts[m]);\n\t\tcorners.push(to.point);\n\t\tconst forward = polySegs(corners, eps);\n\t\tconst back = polySegs(corners.slice().reverse(), eps);\n\t\tconst la = face.loops[from.loop];\n\t\tconst loops = face.loops.filter((_, i) => i !== from.loop && i !== to.loop);\n\t\tif (from.loop === to.loop) {\n\t\t\tconst ab = arc(la, from, to, eps);\n\t\t\tconst ba = arc(la, to, from, eps);\n\t\t\tloops.push(\n\t\t\t\t{ segs: [...ab.segs, ...back], chord: [...ab.chord, ...back.map(() => true)] },\n\t\t\t\t{ segs: [...ba.segs, ...forward], chord: [...ba.chord, ...forward.map(() => true)] }\n\t\t\t);\n\t\t} else {\n\t\t\t// The chord joins two loops into one, with the chord on both sides of a zero-width slit.\n\t\t\tconst lb = face.loops[to.loop];\n\t\t\tconst roundA = arc(la, from, from, eps);\n\t\t\tconst roundB = arc(lb, to, to, eps);\n\t\t\tloops.push({\n\t\t\t\tsegs: [...roundA.segs, ...forward, ...roundB.segs, ...back],\n\t\t\t\tchord: [...roundA.chord, ...forward.map(() => true), ...roundB.chord, ...back.map(() => true)]\n\t\t\t});\n\t\t}\n\t\tfaces = [...faces.slice(0, fi), ...groupFaces(loops), ...faces.slice(fi + 1)];\n\t\tcursor = to.s;\n\t\tcuts++;\n\t}\n\treturn cuts ? faces.map(faceToPath) : null;\n}\n\n// ---------------------------------------------------------------------------\n// Eraser\n// ---------------------------------------------------------------------------\n\n/** The area a round eraser of diameter `width` covers along `points` (a disc for one point). */\nexport function eraserRegion(points: readonly Point[], width: number): BezierPath {\n\tconst pts = points.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tconst r = width / 2;\n\tif (!pts.length || !(r > 0)) return [];\n\tconst moved = pts.some((p) => !near(p, pts[0], 1e-9));\n\tif (!moved) {\n\t\tconst [cx, cy] = pts[0];\n\t\tconst k = r * 0.5522847498307936;\n\t\treturn [\n\t\t\t{ type: 'M', x: cx, y: cy - r },\n\t\t\t{ type: 'C', x1: cx + k, y1: cy - r, x2: cx + r, y2: cy - k, x: cx + r, y: cy },\n\t\t\t{ type: 'C', x1: cx + r, y1: cy + k, x2: cx + k, y2: cy + r, x: cx, y: cy + r },\n\t\t\t{ type: 'C', x1: cx - k, y1: cy + r, x2: cx - r, y2: cy + k, x: cx - r, y: cy },\n\t\t\t{ type: 'C', x1: cx - r, y1: cy - k, x2: cx - k, y2: cy - r, x: cx, y: cy - r },\n\t\t\t{ type: 'Z' }\n\t\t];\n\t}\n\tconst line: BezierPath = [{ type: 'M', x: pts[0][0], y: pts[0][1] }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p[0], y: p[1] }))];\n\treturn outlineStroke(line, { width, cap: 'round', join: 'round' });\n}\n\n/**\n * A filled path with `region` removed: one path per remaining face, or null when the region\n * does not overlap the fill.\n */\nexport function eraseFromFill(path: BezierPathInput, fillRule: FillRule, region: BezierPathInput): BezierPath[] | null {\n\tconst overlap = pathBoolean('intersection', [{ path, fillRule }, { path: region }]).path;\n\tif (!pathToContours(overlap).some((c) => Math.abs(contourSignedArea(closeContour(c, true))) > 1e-9)) return null;\n\tconst rest = pathBoolean('difference', [{ path, fillRule }, { path: region }]).path;\n\treturn splitIntoFaces(rest);\n}\n\n/**\n * The parts of a subpath's outline outside `region`, as open subpaths that keep the original\n * curves exactly; null when the outline does not enter the region. A closed subpath's last\n * and first parts join at its first anchor.\n */\nexport function eraseFromOutline(sp: VectorSubpath, region: BezierPathInput): VectorSubpath[] | null {\n\tconst regionSegs = pathToContours(region).flatMap((c) => closeContour(c, true));\n\tif (!regionSegs.length) return null;\n\tconst rb = bezierPathBounds(region);\n\tconst count = subpathSegmentCount(sp);\n\tif (!rb || count === 0) return null;\n\tconst removed = (p: Point) => pointInBezierPath(region, p, 'nonzero');\n\ttype Piece = { seg: number; t0: number; t1: number };\n\tconst runs: Piece[][] = [];\n\tlet cur: Piece[] = [];\n\tlet any = false;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst seg = subpathSegment(sp, i);\n\t\tconst sb = segmentBounds(seg);\n\t\tconst ts = [0, 1];\n\t\tif (!(sb.maxX < rb.minX || sb.minX > rb.maxX || sb.maxY < rb.minY || sb.minY > rb.maxY)) {\n\t\t\tfor (const r of regionSegs) {\n\t\t\t\tconst b = segmentBounds(r);\n\t\t\t\tif (b.maxX < sb.minX || b.minX > sb.maxX || b.maxY < sb.minY || b.minY > sb.maxY) continue;\n\t\t\t\tfor (const hit of segmentIntersections(seg, r)) if (hit.ta > 1e-9 && hit.ta < 1 - 1e-9) ts.push(hit.ta);\n\t\t\t}\n\t\t}\n\t\tts.sort((a, b) => a - b);\n\t\tfor (let k = 0; k < ts.length - 1; k++) {\n\t\t\tconst t0 = ts[k];\n\t\t\tconst t1 = ts[k + 1];\n\t\t\tif (t1 - t0 < 1e-9) continue;\n\t\t\tif (removed(segmentPoint(seg, (t0 + t1) / 2))) {\n\t\t\t\tany = true;\n\t\t\t\tif (cur.length) runs.push(cur);\n\t\t\t\tcur = [];\n\t\t\t} else cur.push({ seg: i, t0, t1 });\n\t\t}\n\t}\n\tif (cur.length) runs.push(cur);\n\tif (!any) return null;\n\t// A closed path's last and first runs meet at anchor 0.\n\tif (sp.closed && runs.length >= 2) {\n\t\tconst first = runs[0][0];\n\t\tconst lastRun = runs[runs.length - 1];\n\t\tconst last = lastRun[lastRun.length - 1];\n\t\tif (first.seg === 0 && first.t0 === 0 && last.seg === count - 1 && last.t1 === 1) lastRun.push(...runs.shift()!);\n\t}\n\tconst out: VectorSubpath[] = [];\n\tfor (const run of runs) {\n\t\tconst anchors: VectorAnchor[] = [];\n\t\tfor (const { seg, t0, t1 } of run) {\n\t\t\tconst c = subSegment(subpathSegment(sp, seg), t0, t1);\n\t\t\tconst line = c.length === 2;\n\t\t\tconst start = c[0];\n\t\t\tconst end = c[c.length - 1];\n\t\t\tif (!anchors.length) anchors.push({ x: start[0], y: start[1] });\n\t\t\tif (!line) anchors[anchors.length - 1].out = { x: c[1][0], y: c[1][1] };\n\t\t\tconst next: VectorAnchor = { x: end[0], y: end[1] };\n\t\t\tif (!line) next.in = { x: c[2][0], y: c[2][1] };\n\t\t\tanchors.push(next);\n\t\t}\n\t\tif (anchors.length < 2) continue;\n\t\tfor (const a of anchors) {\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t\tout.push({ anchors, closed: false });\n\t}\n\treturn out;\n}\n\n/** Bounds of a point list (for picking the paths a knife or eraser stroke can reach). */\nexport function polylineBounds(points: readonly Point[], pad = 0): { x: number; y: number; width: number; height: number } | null {\n\tif (!points.length) return null;\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const [x, y] of points) {\n\t\tminX = Math.min(minX, x);\n\t\tminY = Math.min(minY, y);\n\t\tmaxX = Math.max(maxX, x);\n\t\tmaxY = Math.max(maxY, y);\n\t}\n\treturn { x: minX - pad, y: minY - pad, width: maxX - minX + 2 * pad, height: maxY - minY + 2 * pad };\n}\n\n/** Ramer–Douglas–Peucker reduction of a polyline (keeps both ends). */\nexport function simplifyPolyline(points: readonly Point[], tolerance: number): Point[] {\n\tconst n = points.length;\n\tif (n < 3) return points.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ax, ay] = points[a];\n\t\tconst dx = points[b][0] - ax;\n\t\tconst dy = points[b][1] - ay;\n\t\tconst len = Math.hypot(dx, dy);\n\t\tlet far = -1;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [px, py] = points[i];\n\t\t\tconst d = len < 1e-12 ? Math.hypot(px - ax, py - ay) : Math.abs((px - ax) * dy - (py - ay) * dx) / len;\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (far >= 0 && farD > tolerance) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn points.filter((_, i) => keep[i]);\n}\n\n","/**\n * Pencil helpers: lazy-mouse smoothing (a pulled string between the pointer and the pen) and\n * ink-to-shape recognition (a hand-drawn stroke that is a line, rectangle, ellipse or polygon).\n *\n * Portions ported from (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md):\n * - photocraft-main/crates/paint/src/dynamics.rs (`Smoother`: pulled-string mode, `string`,\n * `finish` with catch-up on stroke end)\n * - wordcraft-main/crates/engine/src/cmd/ink_shape.rs (`recognise`, `ellipse_rms`,\n * `snap_square`, `corners`, `turning`, `rdp`, `upright`)\n */\nimport type { Point } from '../canvas/types.js';\n\n// ---------------------------------------------------------------------------\n// Lazy mouse\n// ---------------------------------------------------------------------------\n\n/**\n * Pulled-string smoothing: the pen stays put until the pointer is more than `length` away,\n * then follows it at that distance, so small wobbles never reach the stroke. Feed pointer\n * positions to `push`; it returns the pen positions to draw through (possibly none).\n */\nexport class LazyMouse {\n\tprivate pos: Point | null = null;\n\tprivate last: Point | null = null;\n\n\t/** `length` is the string length in the units of the points (0 turns smoothing off). */\n\tconstructor(readonly length: number) {}\n\n\tpush(p: Point): Point[] {\n\t\tthis.last = p;\n\t\tif (!(this.length > 0)) return [p];\n\t\tconst pos = this.pos;\n\t\tif (!pos) {\n\t\t\tthis.pos = p;\n\t\t\treturn [p];\n\t\t}\n\t\tconst dx = p[0] - pos[0];\n\t\tconst dy = p[1] - pos[1];\n\t\tconst d = Math.hypot(dx, dy);\n\t\tif (d <= this.length) return [];\n\t\tconst k = (d - this.length) / d;\n\t\tconst next: Point = [pos[0] + dx * k, pos[1] + dy * k];\n\t\tthis.pos = next;\n\t\treturn [next];\n\t}\n\n\t/** The string from the pen to the pointer while they are apart, else null. */\n\tstring(): [Point, Point] | null {\n\t\tconst { pos, last } = this;\n\t\tif (!(this.length > 0) || !pos || !last || (pos[0] === last[0] && pos[1] === last[1])) return null;\n\t\treturn [pos, last];\n\t}\n\n\t/** End of stroke: the pen catches up with the pointer (the point to add, if it lagged). */\n\tfinish(): Point[] {\n\t\tconst { pos, last } = this;\n\t\tif (!(this.length > 0) || !pos || !last || (pos[0] === last[0] && pos[1] === last[1])) return [];\n\t\tthis.pos = last;\n\t\treturn [last];\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Ink to shape\n// ---------------------------------------------------------------------------\n\n/** A shape recognised in a stroke, in the stroke's coordinates. */\nexport type VectorInkShape =\n\t| { kind: 'line'; a: Point; b: Point }\n\t| { kind: 'rect'; x: number; y: number; width: number; height: number }\n\t| { kind: 'ellipse'; x: number; y: number; width: number; height: number }\n\t| { kind: 'polygon'; points: Point[] };\n\nexport interface RecognizeInkOptions {\n\t/** Strokes whose longer side is smaller than this stay ink (default 6). */\n\tminSize?: number;\n}\n\n/** Most corners a recognised polygon may have. */\nexport const VECTOR_INK_MAX_CORNERS = 8;\nconst MAX_POINTS = 100_000;\n\n/** \"line\", \"square\", \"rectangle\", \"circle\", \"ellipse\", \"triangle\" or \"polygon\". */\nexport function vectorInkShapeName(shape: VectorInkShape): string {\n\tswitch (shape.kind) {\n\t\tcase 'line':\n\t\t\treturn 'line';\n\t\tcase 'rect':\n\t\t\treturn shape.width === shape.height ? 'square' : 'rectangle';\n\t\tcase 'ellipse':\n\t\t\treturn shape.width === shape.height ? 'circle' : 'ellipse';\n\t\tcase 'polygon':\n\t\t\treturn shape.points.length === 3 ? 'triangle' : 'polygon';\n\t}\n}\n\nconst dist = (a: Point, b: Point) => Math.hypot(b[0] - a[0], b[1] - a[1]);\n\nfunction bbox(pts: readonly Point[]): [number, number, number, number] {\n\tif (!pts.length) return [0, 0, 0, 0];\n\tlet [x0, y0] = pts[0];\n\tlet [x1, y1] = pts[0];\n\tfor (const [x, y] of pts) {\n\t\tx0 = Math.min(x0, x);\n\t\ty0 = Math.min(y0, y);\n\t\tx1 = Math.max(x1, x);\n\t\ty1 = Math.max(y1, y);\n\t}\n\treturn [x0, y0, x1 - x0, y1 - y0];\n}\n\nfunction segDistance(a: Point, b: Point, p: Point): number {\n\tconst dx = b[0] - a[0];\n\tconst dy = b[1] - a[1];\n\tconst len2 = dx * dx + dy * dy;\n\tconst t = len2 > 0 ? Math.min(1, Math.max(0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len2)) : 0;\n\treturn dist([a[0] + t * dx, a[1] + t * dy], p);\n}\n\nfunction polygonDistance(c: readonly Point[], p: Point): number {\n\tlet best = Infinity;\n\tfor (let i = 0; i < c.length; i++) best = Math.min(best, segDistance(c[i], c[(i + 1) % c.length], p));\n\treturn best;\n}\n\n/** RMS of each point's normalised radius minus one on the ellipse inscribed in the box (0 on it). */\nfunction ellipseRms(p: readonly Point[], x0: number, y0: number, w: number, h: number): number {\n\tconst rx = w / 2;\n\tconst ry = h / 2;\n\tif (rx <= 0 || ry <= 0 || !p.length) return Infinity;\n\tconst cx = x0 + rx;\n\tconst cy = y0 + ry;\n\tlet sum = 0;\n\tfor (const [x, y] of p) sum += (Math.hypot((x - cx) / rx, (y - cy) / ry) - 1) ** 2;\n\treturn Math.sqrt(sum / p.length);\n}\n\n/** A box drawn nearly square made square (same centre). */\nfunction snapSquare(x: number, y: number, w: number, h: number): [number, number, number, number] {\n\tif (Math.abs(w - h) <= 0.12 * Math.max(w, h)) {\n\t\tconst s = (w + h) / 2;\n\t\treturn [x + (w - s) / 2, y + (h - s) / 2, s, s];\n\t}\n\treturn [x, y, w, h];\n}\n\n/** How far the path turns at `b` coming from `a` towards `c`, in degrees (0 = straight on). */\nfunction turning(a: Point, b: Point, c: Point): number {\n\tconst u = [b[0] - a[0], b[1] - a[1]];\n\tconst v = [c[0] - b[0], c[1] - b[1]];\n\tconst lu = Math.hypot(u[0], u[1]);\n\tconst lv = Math.hypot(v[0], v[1]);\n\tif (lu <= 0 || lv <= 0) return 0;\n\treturn (Math.acos(Math.min(1, Math.max(-1, (u[0] * v[0] + u[1] * v[1]) / (lu * lv)))) * 180) / Math.PI;\n}\n\n/** Ramer–Douglas–Peucker reduction of an open polyline (iterative), keeping both ends. */\nfunction rdp(p: readonly Point[], eps: number): Point[] {\n\tconst n = p.length;\n\tif (n < 3) return p.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tlet far = a;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst d = segDistance(p[a], p[b], p[i]);\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (farD > eps) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn p.filter((_, i) => keep[i]);\n}\n\n/** Corners of the closed path through `p`: RDP split at the point farthest from the start, then flat and crowded corners merged away. */\nfunction corners(p: readonly Point[], diag: number): Point[] {\n\tconst eps = 0.05 * diag;\n\tconst start = p[0];\n\tlet far = 0;\n\tlet farD = 0;\n\tp.forEach((q, i) => {\n\t\tconst d = dist(start, q);\n\t\tif (d > farD) {\n\t\t\tfarD = d;\n\t\t\tfar = i;\n\t\t}\n\t});\n\tconst a = p.slice(0, far);\n\tconst b = p.slice(far);\n\tconst ring = rdp([...a, ...b.slice(0, 1)], eps);\n\tconst back = rdp([...b, start], eps);\n\t// The halves share the far point and the start.\n\tring.pop();\n\tback.pop();\n\tring.push(...back);\n\twhile (ring.length > 3) {\n\t\tconst n = ring.length;\n\t\tconst turn = (i: number) => turning(ring[(i + n - 1) % n], ring[i], ring[(i + 1) % n]);\n\t\tlet flat = 0;\n\t\tlet flatT = Infinity;\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst t = turn(i);\n\t\t\tif (t < flatT) {\n\t\t\t\tflatT = t;\n\t\t\t\tflat = i;\n\t\t\t}\n\t\t}\n\t\tlet short = -1;\n\t\tfor (let j = 0; j < n; j++) {\n\t\t\tif (dist(ring[j], ring[(j + 1) % n]) < 0.1 * diag) {\n\t\t\t\tshort = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (flatT < 30) ring.splice(flat, 1);\n\t\telse if (short >= 0) {\n\t\t\t// Of the two crowded corners keep the sharper.\n\t\t\tconst k = turn(short) < turn((short + 1) % n) ? short : (short + 1) % n;\n\t\t\tring.splice(k, 1);\n\t\t} else break;\n\t}\n\treturn ring;\n}\n\n/** A quadrilateral whose sides run (nearly) across and down, alternately. */\nfunction upright(c: readonly Point[]): boolean {\n\tconst n = c.length;\n\tconst dirs = c.map((a, i) => {\n\t\tconst b = c[(i + 1) % n];\n\t\tconst deg = ((((Math.atan2(b[1] - a[1], b[0] - a[0]) * 180) / Math.PI) % 180) + 180) % 180;\n\t\tif (deg <= 15 || deg >= 165) return 'across';\n\t\tif (deg >= 75 && deg <= 105) return 'down';\n\t\treturn null;\n\t});\n\treturn dirs.every((d) => d !== null) && dirs.every((d, i) => d !== dirs[(i + 1) % n]);\n}\n\n/**\n * The shape a hand-drawn stroke draws, if it is one: an open stroke is a line when it stays\n * close to the chord between its ends; a closed one is an ellipse when its points sit on the\n * ellipse inscribed in their bounds, else a polygon of 3–8 corners when that polygon stays\n * close to every point (an upright four-cornered one is a rectangle). Nearly square boxes\n * become squares and circles. Anything else (scribbles, curves, letters) is null.\n */\nexport function recognizeInkShape(points: readonly Point[], options: RecognizeInkOptions = {}): VectorInkShape | null {\n\tconst minSize = options.minSize ?? 6;\n\tconst p: Point[] = [];\n\tfor (const q of points.slice(0, MAX_POINTS)) {\n\t\tif (!Number.isFinite(q[0]) || !Number.isFinite(q[1]) || Math.abs(q[0]) >= 1e9 || Math.abs(q[1]) >= 1e9) continue;\n\t\tconst last = p[p.length - 1];\n\t\tif (!last || last[0] !== q[0] || last[1] !== q[1]) p.push([q[0], q[1]]);\n\t}\n\tif (p.length < 2) return null;\n\tconst first = p[0];\n\tconst last = p[p.length - 1];\n\tconst [x0, y0, w, h] = bbox(p);\n\tconst size = Math.max(w, h);\n\tconst diag = Math.hypot(w, h);\n\tif (size < minSize) return null;\n\tlet length = 0;\n\tfor (let i = 1; i < p.length; i++) length += dist(p[i - 1], p[i]);\n\tconst gap = dist(first, last);\n\t// A line: the stroke barely leaves the chord between its ends and doesn't double back.\n\tif (gap > 0.85 * length && gap >= minSize) {\n\t\tconst off = Math.max(...p.map((q) => segDistance(first, last, q)));\n\t\tif (off <= Math.max(0.06 * gap, (1.5 * minSize) / 6)) return { kind: 'line', a: first, b: last };\n\t}\n\t// Other shapes are closed: the stroke ends near where it began and goes around.\n\tif (gap > 0.2 * size || length < 2 * size) return null;\n\tconst rms = ellipseRms(p, x0, y0, w, h);\n\tconst roundish = w > 0.2 * size && h > 0.2 * size;\n\tconst ellipse = (): VectorInkShape => {\n\t\tconst [x, y, sw, sh] = snapSquare(x0, y0, w, h);\n\t\treturn { kind: 'ellipse', x, y, width: sw, height: sh };\n\t};\n\tif (roundish && rms < 0.06) return ellipse();\n\tconst c = corners(p, diag);\n\tconst fits = c.length >= 3 && p.every((q) => polygonDistance(c, q) <= 0.08 * diag);\n\tif (fits && c.length === 4 && upright(c)) {\n\t\tconst [bx, by, bw, bh] = bbox(c);\n\t\tconst [x, y, sw, sh] = snapSquare(bx, by, bw, bh);\n\t\treturn { kind: 'rect', x, y, width: sw, height: sh };\n\t}\n\tif (fits && c.length <= VECTOR_INK_MAX_CORNERS) return { kind: 'polygon', points: c };\n\t// A wobbly round stroke is still an ellipse.\n\treturn roundish && rms < 0.1 ? ellipse() : null;\n}\n","/**\n * Pathfinder operands, the Shape Builder and fill regions over a vector document.\n *\n * Everything works in document space: each path is mapped through its own transform and its\n * parents', with live corners cut (`subpathsToBezier`), so rotated nodes and nodes inside\n * rotated groups take part as drawn. The controller maps results back into the space of the node\n * that receives them.\n *\n * - **Pathfinder operands**: a filled path is its fill area (every subpath closed); an unfilled\n * path with a stroke is the area its stroke paints (alignment, caps, joins and arrowheads\n * included) and results from it are filled with the stroke's paint; for Divide an unfilled open\n * path is a cutting line instead.\n * - **Shape Builder**: the planar map of the selected paths (`PlanarMap`). Closed subpaths bound\n * faces whatever their paint (a stroke-only shape's inside is a face), filled open subpaths that\n * enclose an area are closed by an invisible edge, and unfilled open paths cut the faces they\n * cross; their pieces between junctions can be erased. Merging faces unites them along the\n * map's own edges and takes the area away from every shape covering them. Erasing (Alt) also\n * takes the edges of the other outlines, cut where paths meet: a closed subpath opens there,\n * an open one splits, and an edge bounding a face deleted in the same gesture goes with it.\n * - **Fill regions** (paint bucket): the planar map of every visible outline; the region around a\n * point is traced from a ray (`PlanarMap.regionAt`).\n *\n * The Shape Builder follows vectorcraft-main/crates/tools/src/builder.rs (`BuilderMap`, `hit`,\n * `sides`, `line_between`, `erased_edges`, `Hit::Edge`, `shape_builder_shapes`, `sample_polyline`)\n * and crates/engine/src/cmd/buildcmds.rs (`sb_merge`), with figcraft-main/crates/engine/src/shapebuilder.rs\n * (strokes as their outlined area). MIT OR Apache-2.0, © ArtCraft Team and contributors. See\n * THIRD_PARTY_NOTICES.md.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcontourSignedArea,\n\tcloseContour,\n\tdistanceToBezierPath,\n\tpathToContours,\n\tsegmentPoint,\n\tsegmentTangent,\n\tcontoursToPath,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport { PlanarMap, cutOutPiece, type PlanarChain } from '../canvas/pathops/planar.js';\nimport type { PathfinderOperation, PathfinderShape } from '../canvas/pathops/pathfinder.js';\nimport { hasPaint, multiplyMatrices, nodeMatrix, subpathsToBezier, vectorPathWorldBezier, vectorStrokeOutline, IDENTITY_MATRIX, type AffineMatrix } from './geometry.js';\nimport { expandVectorAppearance } from './appearance.js';\nimport type { Vec2, VectorDocument, VectorNode, VectorPaint, VectorPathNode, VectorSubpath } from './types.js';\n\n/** A path node with the matrix of its parent space (parent → document). */\nexport interface VectorPathEntry {\n\tnode: VectorPathNode;\n\tparent: AffineMatrix;\n}\n\n/**\n * The path nodes inside `roots` (or every node when `roots` is null), bottom to top, with their\n * parent matrices. Hidden nodes are skipped, and locked ones unless `locked` is true. Live nodes\n * (path effects, live booleans) take part as drawn (`expandVectorAppearance`: their entries are\n * the expanded paths, whose ids may not be in the document) unless `expand` is false.\n */\nexport function vectorPathEntries(doc: VectorDocument, roots: readonly string[] | null, options: { locked?: boolean; expand?: boolean } = {}): VectorPathEntry[] {\n\tconst out: VectorPathEntry[] = [];\n\tconst visit = (stored: VectorNode, parent: AffineMatrix, inside: boolean) => {\n\t\tif (stored.visible === false || (stored.locked && !options.locked)) return;\n\t\tconst node = options.expand === false ? stored : expandVectorAppearance(stored);\n\t\tconst picked = inside || roots === null || roots.includes(node.id);\n\t\tif (node.type === 'group') {\n\t\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\t\tfor (const c of node.children) visit(c, m, picked);\n\t\t} else if (picked) out.push({ node, parent });\n\t};\n\tfor (const n of doc.nodes) visit(n, IDENTITY_MATRIX, false);\n\treturn out;\n}\n\nconst usable = (sp: VectorSubpath) => sp.anchors.length > 1;\n\n/** The entry's outline in document space with the given subpaths. */\nfunction worldOf(entry: VectorPathEntry, subpaths: VectorSubpath[]): BezierPath {\n\treturn vectorPathWorldBezier({ ...entry.node, subpaths }, entry.parent);\n}\n\n/** Whether a subpath, closed, encloses an area (rather than retracing itself). */\nexport function subpathEnclosesArea(sp: VectorSubpath): boolean {\n\tconst contour = pathToContours(subpathsToBezier([{ ...sp, closed: true }]))[0];\n\tif (!contour) return false;\n\tconst segs = closeContour(contour, true);\n\tconst b = bezierPathBounds(contoursToPath([{ segments: segs, closed: true }]));\n\tif (!b) return false;\n\tconst w = b.maxX - b.minX;\n\tconst h = b.maxY - b.minY;\n\treturn Math.abs(contourSignedArea(segs)) > 1e-9 * (w * w + h * h);\n}\n\n/** How an operand takes part in a Pathfinder operation: its fill, its stroke's area, a cutting line or its bare outline. */\nexport type VectorPathfinderPaint = 'fill' | 'stroke' | 'line' | 'outline';\n\nconst paintKey = (paint: VectorPaint | undefined) => (typeof paint === 'string' ? paint.trim().toLowerCase() : JSON.stringify(paint ?? null));\n\n/** The Pathfinder shape of a path (document space), and what it stands for. */\nexport function vectorPathfinderShape(entry: VectorPathEntry, op: PathfinderOperation): PathfinderShape & { paint: VectorPathfinderPaint } {\n\tconst { node } = entry;\n\tconst subpaths = node.subpaths.filter(usable);\n\tconst closed = subpaths.map((s) => ({ ...s, closed: true }));\n\tconst fillRule = node.fillRule ?? 'nonzero';\n\tif (hasPaint(node.fill)) return { path: worldOf(entry, closed), fillRule, key: `fill:${paintKey(node.fill)}`, paint: 'fill' };\n\tconst open = subpaths.length > 0 && subpaths.every((s) => !s.closed);\n\tif (op === 'divide' && open) return { path: worldOf(entry, subpaths), line: true, paint: 'line' };\n\tif (hasPaint(node.stroke) && (node.strokeWidth ?? 1) > 0) {\n\t\t// Node transforms are rigid, so the stroke laid out in document space keeps its width.\n\t\tconst path = vectorStrokeOutline({ ...node, subpaths }, entry.parent);\n\t\treturn { path, fillRule: 'nonzero', key: `fill:${paintKey(node.stroke)}`, paint: 'stroke' };\n\t}\n\treturn { path: worldOf(entry, closed), fillRule, key: 'none', paint: 'outline' };\n}\n\nconst STROKE_KEYS = [\n\t'stroke',\n\t'strokeWidth',\n\t'strokeLinecap',\n\t'strokeLinejoin',\n\t'strokeDasharray',\n\t'strokeAlign',\n\t'startArrow',\n\t'endArrow',\n\t'arrowAlign',\n\t'startArrowScale',\n\t'endArrowScale',\n\t'strokeWidthProfile'\n] as const;\n\n/**\n * Style of a Pathfinder or Shape Builder result taken from `node`: the node's own style for a\n * filled area, the stroke's paint as a fill for a stroke's area, or (for Outline edges) a stroke\n * in the paint of the area the edge bounds. Never carries the node's id, transform or geometry.\n */\nexport function vectorResultStyle(node: VectorPathNode, paint: VectorPathfinderPaint, edge = false): Omit<VectorPathNode, 'id' | 'subpaths'> {\n\tconst { id: _id, subpaths: _s, transform: _t, effects: _e, booleanOperation: _b, ...rest } = node;\n\tconst base: Omit<VectorPathNode, 'id' | 'subpaths'> = { ...rest, fillRule: 'nonzero' };\n\tif (edge) {\n\t\tfor (const k of STROKE_KEYS) delete (base as Record<string, unknown>)[k];\n\t\tconst stroke = paint === 'stroke' || !hasPaint(node.fill) ? node.stroke : node.fill;\n\t\treturn { ...base, fill: null, stroke: stroke ?? '#000000', strokeWidth: node.strokeWidth ?? 1 };\n\t}\n\tif (paint === 'stroke') {\n\t\tfor (const k of STROKE_KEYS) delete (base as Record<string, unknown>)[k];\n\t\treturn { ...base, fill: node.stroke ?? null, stroke: null };\n\t}\n\treturn base;\n}\n\n// ---------------------------------------------------------------------------\n// Shape Builder\n// ---------------------------------------------------------------------------\n\n/**\n * A run of a path between the points where other paths meet it (or it ends): a piece of an\n * unfilled open path, or an edge of another path's outline.\n */\nexport interface VectorBuilderLinePiece {\n\tpath: BezierPath;\n\tsegments: BezierSegment[];\n\t/** A loop with no junction on it (the whole subpath). */\n\tclosed: boolean;\n\t/** Index of the entry it belongs to (the front-most where outlines coincide). */\n\tsource: number;\n\tbounds: { minX: number; minY: number; maxX: number; maxY: number };\n}\n\n/** The Shape Builder's planar map of a set of paths. */\nexport interface VectorShapeBuilderMap {\n\tentries: VectorPathEntry[];\n\tmap: PlanarMap;\n\t/** Entries with no closed subpath (cutting lines; their pieces can be erased). */\n\tlines: boolean[];\n\tpieces: VectorBuilderLinePiece[];\n\t/** The edges of the other entries' outlines, cut where paths meet (built on first use: erasing). */\n\treadonly edges: VectorBuilderLinePiece[];\n\t/** How far an edge may lie from the outline it came from (document units). */\n\ttolerance: number;\n}\n\n/** What a Shape Builder gesture touches at a point. */\nexport type VectorBuilderHit = { face: number } | { line: number } | { edge: number };\n\n/** The faces, line pieces and edges a gesture touched, in the order touched. */\nexport interface VectorBuilderTouched {\n\tfaces: number[];\n\tlines: number[];\n\tedges: number[];\n}\n\n/**\n * The Shape Builder map of `entries` (bottom to top). Filled open subpaths that enclose an area\n * are closed. Null when nothing can be mapped.\n */\nexport function vectorShapeBuilderMap(entries: readonly VectorPathEntry[]): VectorShapeBuilderMap | null {\n\tconst lines: boolean[] = [];\n\tconst inputs = entries.map((entry) => {\n\t\tconst filled = hasPaint(entry.node.fill);\n\t\tconst subpaths = entry.node.subpaths.filter(usable).map((sp) => (!sp.closed && filled && subpathEnclosesArea(sp) ? { ...sp, closed: true } : sp));\n\t\tlines.push(!subpaths.some((s) => s.closed));\n\t\treturn { path: worldOf(entry, subpaths), fillRule: entry.node.fillRule ?? 'nonzero' };\n\t});\n\tconst map = PlanarMap.build(inputs);\n\tif (!map) return null;\n\tlet chains: PlanarChain[] | null = null;\n\tconst runs = (line: boolean) =>\n\t\t(chains ??= map.chains())\n\t\t\t.filter((c) => lines[c.source] === line && !(line && c.closed))\n\t\t\t.map((c) => {\n\t\t\t\tconst path = contoursToPath([{ segments: c.segments, closed: c.closed }]);\n\t\t\t\treturn { path, segments: c.segments, closed: c.closed, source: c.source, bounds: bezierPathBounds(path)! };\n\t\t\t});\n\tconst pieces = lines.some(Boolean) ? runs(true) : [];\n\tlet edges: VectorBuilderLinePiece[] | null = null;\n\tlet size = 0;\n\tfor (const input of inputs) {\n\t\tconst b = bezierPathBounds(input.path);\n\t\tif (b) size = Math.max(size, b.maxX - b.minX, b.maxY - b.minY);\n\t}\n\treturn {\n\t\tentries: [...entries],\n\t\tmap,\n\t\tlines,\n\t\tpieces,\n\t\tget edges() {\n\t\t\treturn (edges ??= runs(false));\n\t\t},\n\t\ttolerance: 0.2 * Math.max(size / 2000, 0.25)\n\t};\n}\n\n/** The run of `pieces` nearest `p` within `tol`, with its distance. */\nfunction pieceNear(pieces: readonly VectorBuilderLinePiece[], p: Vec2, tol: number): { index: number; d: number } | null {\n\tconst point: Point = [p.x, p.y];\n\tlet best: { index: number; d: number } | null = null;\n\tpieces.forEach((piece, index) => {\n\t\tconst b = piece.bounds;\n\t\tif (p.x < b.minX - tol || p.x > b.maxX + tol || p.y < b.minY - tol || p.y > b.maxY + tol) return;\n\t\tconst d = distanceToBezierPath(piece.path, point);\n\t\tif (d <= tol && (!best || d < best.d)) best = { index, d };\n\t});\n\treturn best;\n}\n\n/**\n * The face under `p`, or with `lineTolerance` (erasing) first the nearer of the line piece and\n * the outline edge that close.\n */\nexport function vectorShapeBuilderHit(m: VectorShapeBuilderMap, p: Vec2, lineTolerance: number | null = null): VectorBuilderHit | null {\n\tif (lineTolerance !== null && lineTolerance > 0) {\n\t\tconst line = pieceNear(m.pieces, p, lineTolerance);\n\t\tconst edge = pieceNear(m.edges, p, lineTolerance);\n\t\tif (edge && (!line || edge.d < line.d)) return { edge: edge.index };\n\t\tif (line) return { line: line.index };\n\t}\n\tconst face = m.map.faceAt([p.x, p.y]);\n\treturn face >= 0 ? { face } : null;\n}\n\n/** Points along a polyline no more than `step` apart (the pointer's path through faces). */\nexport function samplePolyline(points: readonly Vec2[], step: number): Vec2[] {\n\tconst out: Vec2[] = [];\n\tconst s = Math.max(step, 1e-3);\n\tpoints.forEach((p, i) => {\n\t\tif (i > 0) {\n\t\t\tconst a = points[i - 1];\n\t\t\tconst n = Math.min(4000, Math.ceil(Math.hypot(p.x - a.x, p.y - a.y) / s));\n\t\t\tfor (let k = 1; k < n; k++) out.push({ x: a.x + ((p.x - a.x) * k) / n, y: a.y + ((p.y - a.y) * k) / n });\n\t\t}\n\t\tout.push(p);\n\t});\n\treturn out;\n}\n\n/** Adds what a point hits to `touched` (each face or piece once). */\nexport function addBuilderHit(touched: VectorBuilderTouched, hit: VectorBuilderHit | null): boolean {\n\tif (!hit) return false;\n\tconst [list, i] = 'face' in hit ? [touched.faces, hit.face] : 'line' in hit ? [touched.lines, hit.line] : [touched.edges, hit.edge];\n\tif (list.includes(i)) return false;\n\tlist.push(i);\n\treturn true;\n}\n\n/** The faces just either side of the middle of a line piece (-1 outside every face). */\nfunction sides(m: VectorShapeBuilderMap, piece: VectorBuilderLinePiece): [number, number] {\n\tconst seg = piece.segments[Math.floor(piece.segments.length / 2)];\n\tconst mid = segmentPoint(seg, 0.5);\n\tconst t = segmentTangent(seg, 0.5);\n\tconst chord = Math.hypot(seg[seg.length - 1][0] - seg[0][0], seg[seg.length - 1][1] - seg[0][1]);\n\tconst off = Math.max(1e-6, Math.min(0.05, 0.05 * chord));\n\treturn [m.map.faceAt([mid[0] - t[1] * off, mid[1] + t[0] * off]), m.map.faceAt([mid[0] + t[1] * off, mid[1] - t[0] * off])];\n}\n\n/**\n * The edges a gesture deletes: those it touched that bound none of the faces it touched (an edge\n * of a deleted or merged face goes with the face, so an erase drag that crosses an edge into a\n * face deletes the face).\n */\nexport function vectorBuilderErasedEdges(m: VectorShapeBuilderMap, touched: VectorBuilderTouched): number[] {\n\tif (!touched.edges.length) return [];\n\tconst faces = new Set(touched.faces);\n\treturn touched.edges.filter((k) => m.edges[k] && !sides(m, m.edges[k]).some((f) => f >= 0 && faces.has(f)));\n}\n\n/**\n * What becomes of one entry: unchanged (absent), removed (`null`), or new outlines (document\n * space). `fill`: what is left of its area, filled non-zero (subpaths an erased edge opened stay\n * open); `outline`: its own outline with erased edges cut out, its fill rule kept; `pieces`: the\n * pieces of a cutting line that stay, each its own path.\n */\nexport type VectorBuilderReplacement = { kind: 'fill'; path: BezierPath } | { kind: 'outline'; path: BezierPath } | { kind: 'pieces'; paths: BezierPath[] } | null;\n\nexport interface VectorShapeBuilderPlan {\n\treplace: Map<number, VectorBuilderReplacement>;\n\t/** The merged shape (document space), styled like entry `style`; `currentFill` when only outlines enclosed it. */\n\tmerged: { path: BezierPath; style: number; currentFill: boolean } | null;\n}\n\n/**\n * What a gesture does: merging (or with `erase`, deleting) the touched faces takes them away\n * from every shape covering them; line pieces touched (erasing) or lying between touched faces\n * go; erased edges (`vectorBuilderErasedEdges`) are cut out of every outline they lie on;\n * merging adds the union of the faces as a new shape styled like the top-most shape over the\n * first face touched (or, for a face only outlines enclose, the top-most shape with the current\n * fill).\n */\nexport function planShapeBuilder(m: VectorShapeBuilderMap, touched: VectorBuilderTouched, erase: boolean): VectorShapeBuilderPlan {\n\tconst replace = new Map<number, VectorBuilderReplacement>();\n\tconst picked = new Set(touched.faces);\n\tconst faces = m.map.faces;\n\tconst sourcesOf = faces.map((_, i) => m.map.faceSources(i));\n\tconst cuts = erase ? vectorBuilderErasedEdges(m, touched).map((k) => m.edges[k]) : [];\n\tm.entries.forEach((entry, i) => {\n\t\tif (m.lines[i]) {\n\t\t\tconst own = m.pieces.flatMap((piece, k) => (piece.source === i ? [k] : []));\n\t\t\tconst keep = own.filter((k) => !touched.lines.includes(k) && !sides(m, m.pieces[k]).every((f) => f >= 0 && picked.has(f)));\n\t\t\tif (keep.length === own.length) return;\n\t\t\treplace.set(i, keep.length ? { kind: 'pieces', paths: keep.map((k) => m.pieces[k].path) } : null);\n\t\t\treturn;\n\t\t}\n\t\tconst inUnion = touched.faces.some((f) => sourcesOf[f].includes(i));\n\t\tif (!inUnion && !cuts.length) return;\n\t\tlet rest: BezierPath;\n\t\tif (inUnion) {\n\t\t\tconst kept = faces.flatMap((_, f) => (sourcesOf[f].includes(i) && !picked.has(f) ? [f] : []));\n\t\t\trest = kept.length ? m.map.merge(kept) : [];\n\t\t} else rest = worldOf(entry, entry.node.subpaths.filter(usable));\n\t\t// Each erased edge comes off every outline it lies on (shared edges from each shape).\n\t\tconst fillCloses = hasPaint(entry.node.fill);\n\t\tlet cut = false;\n\t\tfor (const piece of cuts) {\n\t\t\tconst r = rest.length ? cutOutPiece(rest, piece, fillCloses, m.tolerance) : null;\n\t\t\tif (r) {\n\t\t\t\trest = r;\n\t\t\t\tcut = true;\n\t\t\t}\n\t\t}\n\t\tif (!inUnion && !cut) return;\n\t\treplace.set(i, rest.length ? { kind: inUnion ? 'fill' : 'outline', path: rest } : null);\n\t});\n\tlet merged: VectorShapeBuilderPlan['merged'] = null;\n\tif (!erase && touched.faces.length) {\n\t\tconst path = m.map.merge(touched.faces);\n\t\tconst covered = touched.faces.map((f) => sourcesOf[f]).find((s) => s.length);\n\t\tconst lastShape = m.lines.lastIndexOf(false);\n\t\tconst style = covered ? covered[covered.length - 1] : lastShape >= 0 ? lastShape : m.entries.length - 1;\n\t\tif (path.length) merged = { path, style, currentFill: !covered };\n\t}\n\treturn { replace, merged };\n}\n\n// ---------------------------------------------------------------------------\n// Fill regions\n// ---------------------------------------------------------------------------\n\n/**\n * The planar map of every visible path's outline as drawn (locked ones included), for the paint\n * bucket. `gap` closes gaps up to that distance between loose ends.\n */\nexport function vectorFillMap(doc: VectorDocument, gap = 0): PlanarMap | null {\n\tconst entries = vectorPathEntries(doc, null, { locked: true });\n\treturn PlanarMap.build(\n\t\tentries.map((e) => ({ path: worldOf(e, e.node.subpaths.filter(usable)), fills: false })),\n\t\t{ gap, maxSegments: 20000 }\n\t);\n}\n","import { HistoryManager } from '../history/HistoryManager.js';\nimport type { Command } from '../history/types.js';\nimport { fitCubics } from '../canvas/curveFit.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { pathfinder as runPathfinder } from '../canvas/pathops/pathfinder.js';\nimport type { PlanarMap } from '../canvas/pathops/planar.js';\nimport { bezierPathBounds, bezierPathToSvg, transformBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierToSubpaths,\n\tboundsFromPoints,\n\tboundsIntersect,\n\tcloneVectorDocument,\n\tcloneVectorNode,\n\tcollectPathNodes,\n\tconvertAnchor,\n\tellipseSubpath,\n\tfindVectorNode,\n\thitTestVectorNode,\n\thitTestVectorNodes,\n\tinsertAnchor,\n\tlineSubpath,\n\tlocateVectorNode,\n\tmoveAnchorHandle,\n\tnearestSegment,\n\thasPaint,\n\tnodeMatrix,\n\tinvertMatrix,\n\tapplyMatrix,\n\tapplyMatrixLinear,\n\tmultiplyMatrices,\n\tmatrixRotation,\n\tvectorWorldMatrix,\n\tvectorParentMatrix,\n\tvectorPathWorldBezier,\n\tIDENTITY_MATRIX,\n\tpolygonSubpath,\n\trectSubpath,\n\tremoveAnchors,\n\treverseSubpath,\n\trotateMatrix,\n\tscaleMatrix,\n\tstarSubpath,\n\tsubpathsToBezier,\n\ttransformVectorNode,\n\ttranslateAnchor,\n\ttranslateMatrix,\n\tunionBounds,\n\tvectorNodeBounds,\n\twalkVectorNodes,\n\ttype AffineMatrix\n} from './geometry.js';\nimport {\n\tcornerBisectorPoint,\n\tcornerRadiusChange,\n\tfitCornerRadius,\n\tnextVectorCornerKind,\n\tsetAnchorCorner,\n\tsetSubpathCorners,\n\tvectorCorners,\n\ttype VectorCornerInfo\n} from './corners.js';\nimport { strokeWidthProfileOf, vectorStrokeOutlinePath, vectorStrokeParts } from './stroke.js';\nimport { nearestStrokePosition, strokePositionPoint } from './varstroke.js';\nimport {\n\tgenerateWidthProfile,\n\tinsertWidthPoint,\n\tpressureWidthProfile,\n\tremoveWidthPoints,\n\treverseWidthProfile,\n\tsanitizeWidthProfile,\n\tsetWidthPoint,\n\twidthProfileAt,\n\twidthProfileMaxScale,\n\twidthProfilePreset,\n\ttype VectorTaperOptions,\n\ttype VectorWaveOptions,\n\ttype VectorWidthPreset,\n\tVECTOR_WIDTH_PROFILE_MAX_POINTS,\n\tVECTOR_WIDTH_SAME_T\n} from './width.js';\nimport { parseVectorSvg, vectorDocumentToSvg, vectorPathLocalBounds, type VectorSvgExportOptions } from './svg.js';\nimport {\n\tapplyVectorGradientPatch,\n\tdefaultVectorGradient,\n\tinsertVectorGradientStop,\n\tisVectorGradient,\n\tmoveVectorGradientHandle,\n\tmoveVectorGradientStop,\n\tremoveVectorGradientStop,\n\tsetVectorGradientVector,\n\tsortedVectorGradientStops,\n\tvectorGradientMidpointFromPosition,\n\ttype VectorGradientHandle,\n\ttype VectorGradientPatch\n} from './gradient.js';\nimport {\n\tgetVectorGradientAnnotator,\n\thitVectorGradientAnnotator,\n\tvectorGradientBarPosition,\n\tVECTOR_GRADIENT_OFF_BAR,\n\tVECTOR_GRADIENT_STOP_GAP,\n\ttype VectorGradientAnnotator,\n\ttype VectorGradientPart,\n\ttype VectorGradientTarget\n} from './gradientTool.js';\nimport {\n\texpandVectorBlend,\n\tisVectorBlendGroup,\n\trefreshVectorBlends,\n\treleaseVectorBlend,\n\tvectorBlendKeyTargets\n} from './blendGroup.js';\nimport {\n\tcreateVectorEffect,\n\texpandVectorAppearance,\n\thasOwnVectorAppearance,\n\thasVectorAppearance,\n\tisVectorLiveBoolean,\n\tnormalizeVectorEffectParams,\n\tvectorAppearanceOutline,\n\tvectorEnteredGroups,\n\tvectorEnvelopeFrame,\n\tvectorNodeEnvelope,\n\ttype VectorEnvelopeParams,\n\tVECTOR_EFFECT_LABELS\n} from './appearance.js';\nimport { applyVectorHomography, vectorHomography, vectorHomographyKeepsQuad } from './perspective.js';\nimport { distortVectorNode, vectorBoxCorners, vectorDistortQuad, vectorShearForSide, vectorSkewMatrix, VECTOR_DISTORT_TOLERANCE, type VectorDistortMode } from './distort.js';\nimport {\n\tdragVectorMeshPoint,\n\tpullVectorMesh,\n\tresizeVectorMesh,\n\tvectorMeshEditPoints,\n\tvectorMeshFromOutline,\n\tvectorMeshOutline,\n\tvectorMeshParamAt\n} from './warp.js';\nimport { constrainToLeave, VECTOR_CONSTRUCTION_ANGLES, VectorSnapTargets, type VectorSnapGuides, type VectorSnapLeave } from './snap.js';\nimport {\n\tbendSegment as bendSubpathSegment,\n\tcurvatureMoveAnchor,\n\tcutSubpathAt,\n\tjoinSubpaths,\n\tremoveAnchorsKeepingShape,\n\tremoveRedundantPoints as removeRedundantSubpathPoints,\n\tsmoothSubpath,\n\tsplitSubpathAt\n} from './pathEdit.js';\nimport { eraseFromFill, eraseFromOutline, eraserRegion, knifePath, polylineBounds, simplifyPolyline } from './pathCut.js';\nimport { LazyMouse, recognizeInkShape, vectorInkShapeName, type VectorInkShape } from './ink.js';\nimport {\n\taddBuilderHit,\n\tplanShapeBuilder,\n\tsamplePolyline,\n\tvectorFillMap,\n\tvectorPathEntries,\n\tvectorPathfinderShape,\n\tvectorResultStyle,\n\tvectorBuilderErasedEdges,\n\tvectorShapeBuilderHit,\n\tvectorShapeBuilderMap,\n\ttype VectorBuilderTouched,\n\ttype VectorShapeBuilderMap\n} from './builder.js';\nimport type { VectorGradient, VectorWarpMesh } from './types.js';\nimport type {\n\tVec2,\n\tVectorEffect,\n\tVectorEffectType,\n\tVectorAlign,\n\tVectorAnchor,\n\tVectorAnchorRef,\n\tVectorAnchorType,\n\tVectorArrange,\n\tVectorAverageAxis,\n\tVectorBlend,\n\tVectorBlendOptions,\n\tVectorBooleanOperation,\n\tVectorBounds,\n\tVectorCornerKind,\n\tVectorDefaults,\n\tVectorDistribute,\n\tVectorDocument,\n\tVectorGroupNode,\n\tVectorHandleRef,\n\tVectorModifiers,\n\tVectorNode,\n\tVectorPathfinderOperation,\n\tVectorPathNode,\n\tVectorSegmentRef,\n\tVectorStyle,\n\tVectorSubpath,\n\tVectorTool,\n\tVectorTransformHandle,\n\tVectorViewport,\n\tVectorWidthPoint\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface VectorSnapOptions {\n\t/** Grid size in document units (0 = off, default 0). Points and boxes that snap to no object snap to it. */\n\tgrid: number;\n\t/**\n\t * Snap to other objects (default true): anchors, paths and their intersections, bounding-box\n\t * edges and centres, the artboard, construction angles, equal spacing and matching sizes.\n\t */\n\tobjects: boolean;\n\t/** Show smart guide lines and labels while snapping (default true). */\n\tguides: boolean;\n\t/** How near a target pulls, in screen pixels (default 5). */\n\tthreshold: number;\n\t/** Construction guide angles through the point a drawn point leaves from, in degrees (default 0, 45, 90, 135). */\n\tangles: readonly number[];\n}\n\n/** Snap options new editors start with. Hold Cmd / Ctrl (`mod`) during a drag to bypass snapping. */\nexport const DEFAULT_VECTOR_SNAP: Readonly<VectorSnapOptions> = { grid: 0, objects: true, guides: true, threshold: 5, angles: VECTOR_CONSTRUCTION_ANGLES };\n\n/** How path-editing gestures and the pencil, knife and eraser behave. */\nexport interface VectorPathEditOptions {\n\t/**\n\t * Deleting anchors refits the neighbouring handles so the shape stays (default true). Off,\n\t * the neighbours are joined with their handles as they are.\n\t */\n\tkeepShapeOnDelete: boolean;\n\t/**\n\t * Dragging one anchor with the direct tool bends its two segments like the Curvature tool,\n\t * keeping the segments beyond still (default false). Alt held during the drag flips it.\n\t */\n\tcurvatureMoves: boolean;\n\t/** Pencil lazy-mouse smoothing, 0–1: the pulled string is up to 100 screen pixels long (default 0, off). */\n\tpencilSmoothing: number;\n\t/** Pencil strokes that look like a line, rectangle, ellipse or polygon become that shape (default false). */\n\trecognizeShapes: boolean;\n\t/** Eraser diameter in document units (default 10). */\n\teraserSize: number;\n\t/**\n\t * Record pointer pressure on pencil strokes as a width profile: `pen` (default) for pen input\n\t * only, `all` for any pointer that reports pressure, `off` never.\n\t */\n\tpencilPressure: 'pen' | 'all' | 'off';\n\t/**\n\t * Paint bucket: gaps up to this distance (document units) between loose ends of outlines are\n\t * closed when finding the region to fill (default 0, off).\n\t */\n\tfillGap: number;\n}\n\n/** The gap the toolbars' \"Close gaps\" toggle sets (document units). */\nexport const VECTOR_FILL_GAP = 6;\n\n/** Path-editing options new editors start with. */\nexport const DEFAULT_VECTOR_PATH_EDIT: Readonly<VectorPathEditOptions> = {\n\tkeepShapeOnDelete: true,\n\tcurvatureMoves: false,\n\tpencilSmoothing: 0,\n\trecognizeShapes: false,\n\teraserSize: 10,\n\tpencilPressure: 'pen',\n\tfillGap: 0\n};\n\n/** Longest pencil lazy-mouse string (at smoothing 1), in screen pixels. */\nexport const VECTOR_PENCIL_STRING_PX = 100;\n\nexport interface VectorEditorOptions {\n\tdocument?: VectorDocument;\n\t/** History to record into, e.g. one shared with the rest of the app (default: a new one). */\n\thistory?: HistoryManager;\n\t/** Starting tool (default `select`). */\n\ttool?: VectorTool;\n\t/** Style and settings for new shapes and paths. */\n\tdefaults?: VectorDefaults;\n\tviewport?: Partial<VectorViewport>;\n\tsnap?: Partial<VectorSnapOptions>;\n\tediting?: Partial<VectorPathEditOptions>;\n\t/** Pick distance for anchors, handles and outlines in screen pixels (default 6). */\n\thitRadius?: number;\n\t/** Id factory for new nodes. */\n\tcreateId?: () => string;\n\t/** Called after the document changes (edits, undo, redo, load). */\n\tonChange?: (document: VectorDocument) => void;\n\t/** Start in Free Distort mode (see `setFreeDistort`). */\n\tfreeDistort?: boolean;\n}\n\n/** A pointer event as the controller needs it. Positions are in screen pixels relative to the canvas. */\nexport interface VectorPointerInput extends VectorModifiers {\n\t/** 0 = primary, 1 = middle (pans), 2 = secondary. Default 0. */\n\tbutton?: number;\n\t/** `PointerEvent.pressure` (0–1), recorded on pencil strokes. */\n\tpressure?: number;\n\t/** `PointerEvent.pointerType` (`mouse`, `pen`, `touch`). */\n\tpointerType?: string;\n}\n\n/** One width point of a path's stroke profile; `subpath` is the subpath it is shown on. */\nexport interface VectorWidthPointRef {\n\tnodeId: string;\n\tindex: number;\n\tsubpath: number;\n}\n\n/** A spot on a stroke (width tool): where a drag would add a width point. Positions in document units. */\nexport interface VectorStrokeSpot {\n\tnodeId: string;\n\tsubpath: number;\n\t/** Position along the subpath by length, 0–1. */\n\tt: number;\n\tpoint: Vec2;\n\t/** Ends of the stroke's width across the path there. */\n\tleft: Vec2;\n\tright: Vec2;\n}\n\n/**\n * The width point being edited numerically (double-click with the width tool): `index` is the\n * point's, or null for a new point at `t` (a double-click on a stroke away from its points).\n * `left` / `right` are side widths in document units (how far the stroke reaches on each side),\n * `point` is where it sits on the path, in document space.\n */\nexport interface VectorWidthPointEdit {\n\tnodeId: string;\n\tsubpath: number;\n\tindex: number | null;\n\tt: number;\n\tleft: number;\n\tright: number;\n\tpoint: Vec2;\n}\n\n/** A key press as the controller needs it. */\nexport interface VectorKeyInput extends VectorModifiers {\n\t/** `KeyboardEvent.key`. */\n\tkey: string;\n}\n\n/** What the pointer is over. */\nexport interface VectorHover {\n\tnodeId: string | null;\n\tanchor?: VectorAnchorRef;\n\thandle?: VectorHandleRef;\n\t/** A segment under the pointer (direct tool and scissors); `point` is in document space. */\n\tsegment?: { nodeId: string; subpath: number; segment: number; t: number; point: Vec2 };\n\ttransformHandle?: VectorTransformHandle;\n\t/** A live corner widget (direct tool): the corner's anchor. */\n\tcorner?: VectorAnchorRef;\n\t/** A width point (width tool): its centre or the end of its left / right side. */\n\twidthPoint?: VectorWidthPointRef & { part: 'center' | 'left' | 'right' };\n\t/** A spot on a stroke away from its width points (width tool). */\n\tstrokeSpot?: VectorStrokeSpot;\n\t/** A part of the gradient annotator (gradient tool). */\n\tgradient?: VectorGradientPart;\n\t/** A control point of the selected envelope's mesh (`index`), or a spot inside it (`index` null): Envelope tool. */\n\tenvelope?: { nodeId: string; index: number | null };\n}\n\n/** The drag in progress, for overlays and status text. */\nexport type VectorInteraction =\n\t| { type: 'marquee'; bounds: VectorBounds }\n\t| { type: 'move'; dx: number; dy: number }\n\t| { type: 'scale'; handle: VectorTransformHandle; sx: number; sy: number }\n\t| { type: 'rotate'; angle: number }\n\t| { type: 'anchors'; dx: number; dy: number }\n\t| { type: 'handle'; ref: VectorHandleRef }\n\t| { type: 'bend'; ref: VectorSegmentRef }\n\t| { type: 'corner'; ref: VectorAnchorRef; radius: number }\n\t| { type: 'draw'; tool: VectorTool; nodeId: string; bounds: VectorBounds; string?: [Vec2, Vec2] }\n\t| { type: 'stroke'; tool: 'knife' | 'eraser'; points: Vec2[]; width: number }\n\t| { type: 'builder'; mode: 'merge' | 'erase'; points: Vec2[] }\n\t| { type: 'width'; ref: VectorWidthPointRef; mode: 'width' | 'move' | 'copy'; width: number }\n\t| { type: 'pen'; nodeId: string }\n\t/** A gradient tool drag: drawing a new vector, or a handle, stop, midpoint or the bar (`removing`: a stop dragged off the bar). */\n\t| { type: 'gradient'; part: 'create' | VectorGradientPart['kind']; handle?: VectorGradientHandle; removing?: boolean }\n\t/** Free Distort: the selection box's corners as dragged so far (document space, clockwise from the top left). */\n\t| { type: 'distort'; mode: VectorDistortMode | 'skew'; corners: Vec2[] }\n\t/** Envelope tool: a mesh point (`index`) or the surface (`index` null) being dragged. */\n\t| { type: 'envelope'; nodeId: string; index: number | null }\n\t| { type: 'pan' };\n\n/** A snapshot of the editor. The same object is returned until something changes. */\nexport interface VectorEditorState {\n\tdocument: VectorDocument;\n\ttool: VectorTool;\n\t/** Selected node ids (top-level nodes or group members picked with the direct tool). */\n\tselection: readonly string[];\n\t/** Selected anchors (direct tool). */\n\tselectedAnchors: readonly VectorAnchorRef[];\n\t/** The selected width points (width tool, all on one path); Delete removes them. */\n\tselectedWidthPoints: readonly VectorWidthPointRef[];\n\t/** The width point open for numeric editing (double-click with the width tool), if any. */\n\twidthPointEdit: VectorWidthPointEdit | null;\n\t/** The path whose anchors are being edited, if any. */\n\teditingId: string | null;\n\t/** Axis-aligned bounds of the selected nodes in document units. */\n\tselectionBounds: VectorBounds | null;\n\t/** The selection box, rotated with the selection when its nodes share a rotation. */\n\tselectionFrame: VectorSelectionFrame | null;\n\tviewport: VectorViewport;\n\tdefaults: Readonly<Required<Pick<VectorDefaults, 'polygonSides' | 'starPoints' | 'starInnerRatio' | 'cornerRadius'>> & Pick<VectorDefaults, 'cornerKind'> & VectorStyle>;\n\tsnap: VectorSnapOptions;\n\tediting: VectorPathEditOptions;\n\t/** Smart guides of the snap in progress, in document units (null when there are none). */\n\tguides: VectorSnapGuides | null;\n\thitRadius: number;\n\thover: VectorHover | null;\n\t/** A CSS cursor for the canvas. */\n\tcursor: string;\n\tinteraction: VectorInteraction | null;\n\t/** The path the pen tool is adding to. */\n\tpen: { nodeId: string; subpath: number } | null;\n\t/** Last pointer position in document units (for the pen preview), or null when outside. */\n\tpointer: Vec2 | null;\n\t/** Shape Builder and paint bucket highlight: faces, line pieces and the gesture's trail. */\n\tbuilder: VectorBuilderPreview | null;\n\t/** The Blend tool's first click: the shape (and anchor of its first subpath) the next click blends from. */\n\tblendStart: VectorBlendStart | null;\n\t/** Options new blends get. */\n\tblendDefaults: VectorBlendOptions;\n\t/** The paint the gradient tool and gradient editor work on, and the selected stop (index into the sorted stops). */\n\tgradientEdit: { target: VectorGradientTarget; stop: number | null };\n\t/**\n\t * Free Distort mode of the selection box: dragging a corner distorts in perspective (each corner\n\t * on its own; Shift+Alt+Mod: symmetric perspective), a side moves its two corners, and Mod-dragging\n\t * a side skews along it (Alt: about the centre).\n\t */\n\tfreeDistort: boolean;\n\tcanUndo: boolean;\n\tcanRedo: boolean;\n\tundoLabel: string;\n\tredoLabel: string;\n\t/** Bumped on every change. */\n\trevision: number;\n}\n\nexport type VectorActionResult = { ok: true } | { ok: false; message: string };\n\n/** The shape the Blend tool blends from (its first click). */\nexport interface VectorBlendStart {\n\tnodeId: string;\n\t/** The clicked anchor of its first subpath, or null for the shape as a whole. */\n\tanchor: number | null;\n}\n\n/** Blend settings and options of `VectorEditorController.blend`. */\nexport interface VectorBlendInput extends VectorBlendOptions {\n\t/** Nodes to blend (default: the selection), in stacking order unless `keepOrder`. */\n\tids?: readonly string[];\n\t/** Blend in the order given instead of stacking order. */\n\tkeepOrder?: boolean;\n\t/** Start anchor of each key's first subpath, by key id. */\n\tstarts?: Record<string, number>;\n\tname?: string;\n}\n\nconst BLEND_OPTION_KEYS = ['spacing', 'steps', 'distance', 'orientToSpine', 'linear'] as const;\n\n/** The blend options in `input`, valid ones only. */\nfunction blendOptionsOf(input: Partial<VectorBlendOptions>): VectorBlendOptions {\n\tconst out: VectorBlendOptions = {};\n\tif (input.spacing === 'steps' || input.spacing === 'distance' || input.spacing === 'smoothColor') out.spacing = input.spacing;\n\tif (typeof input.steps === 'number' && Number.isFinite(input.steps)) out.steps = Math.min(1000, Math.max(1, Math.round(input.steps)));\n\tif (typeof input.distance === 'number' && Number.isFinite(input.distance) && input.distance > 0) out.distance = input.distance;\n\tif (typeof input.orientToSpine === 'boolean') out.orientToSpine = input.orientToSpine;\n\tif (typeof input.linear === 'boolean') out.linear = input.linear;\n\treturn out;\n}\n\n/**\n * What the Shape Builder or paint bucket highlights, in document units: the faces (filled paths\n * as SVG path data) under the pointer or touched by the drag, the line pieces an erase would\n * delete, and the drag's trail. `mode` is `merge`, `erase` (Alt) or `fill` (paint bucket).\n */\nexport interface VectorBuilderPreview {\n\tmode: 'merge' | 'erase' | 'fill';\n\tfaces: BezierPath[];\n\tlines: BezierPath[];\n\ttrail: Vec2[] | null;\n}\n\n/** Result of a Shape Builder gesture. */\nexport interface VectorShapeBuilderResult {\n\tok: boolean;\n\tmessage?: string;\n\t/** Id of the merged shape (none when erasing). */\n\tmerged: string | null;\n\tfaces: number;\n\tlines: number;\n\t/** Outline edges erased (cut out of the paths they lie on). */\n\tedges: number;\n}\n\n/** A face of the Shape Builder map (document units). */\nexport interface VectorShapeBuilderFace {\n\tindex: number;\n\t/** SVG path data. */\n\td: string;\n\tarea: number;\n\t/** Ids of the paths whose fill covers it, bottom to top (empty for an area only outlines enclose). */\n\tsources: string[];\n\t/** A point inside it. */\n\tpoint: Vec2 | null;\n}\n\nexport interface AddVectorNodeOptions {\n\t/** Group to add into (default: the root). */\n\tparentId?: string;\n\t/** Position in the parent's list (default: on top). */\n\tindex?: number;\n\t/** Select the new node (default true). */\n\tselect?: boolean;\n\t/** Undo step label. */\n\tlabel?: string;\n}\n\n/** A shape description for `addShape` (and the agent command of the same name). */\nexport interface VectorShapeInput extends VectorStyle {\n\tkind: 'rect' | 'ellipse' | 'polygon' | 'star' | 'line';\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\t/** Live corner radius of a rectangle, polygon or star (default: the editor default). */\n\tcornerRadius?: number;\n\tcornerKind?: VectorCornerKind;\n\tsides?: number;\n\tpoints?: number;\n\tinnerRatio?: number;\n\tname?: string;\n}\n\n/** Every field of `VectorStyle`, in the order style panels and commands list them. */\nexport const VECTOR_STYLE_KEYS = [\n\t'fill',\n\t'stroke',\n\t'strokeWidth',\n\t'strokeLinecap',\n\t'strokeLinejoin',\n\t'strokeDasharray',\n\t'fillRule',\n\t'strokeAlign',\n\t'startArrow',\n\t'endArrow',\n\t'arrowAlign',\n\t'startArrowScale',\n\t'endArrowScale',\n\t'strokeWidthProfile'\n] as const satisfies readonly (keyof VectorStyle)[];\n\n/** Clipboard payload type written by `copy()`. */\nexport const VECTOR_CLIPBOARD_TYPE = 'pixerate/vector';\n\nconst DEFAULT_DEFAULTS = {\n\tfill: '#d4d4d8',\n\tstroke: '#18181b',\n\tstrokeWidth: 2,\n\tpolygonSides: 6,\n\tstarPoints: 5,\n\tstarInnerRatio: 0.5,\n\tcornerRadius: 0\n};\n\nconst MIN_ZOOM = 0.05;\nconst MAX_ZOOM = 64;\n/** Screen distance of the rotation handle above the selection box. */\nexport const VECTOR_ROTATE_HANDLE_OFFSET = 24;\n\n// ---------------------------------------------------------------------------\n// Helpers shared with the render module\n// ---------------------------------------------------------------------------\n\nconst sameRef = (a: VectorAnchorRef, b: VectorAnchorRef) => a.nodeId === b.nodeId && a.subpath === b.subpath && a.index === b.index;\n\n/** Ids of the path nodes whose anchors are shown (the edited path plus selected paths). */\nexport function getEditablePathIds(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen'>): string[] {\n\tif (state.tool !== 'direct' && state.tool !== 'pen') return [];\n\tconst ids = new Set<string>();\n\tif (state.pen) ids.add(state.pen.nodeId);\n\tif (state.tool === 'direct') {\n\t\tif (state.editingId) ids.add(state.editingId);\n\t\tfor (const id of state.selection) {\n\t\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) ids.add(p.id);\n\t\t}\n\t}\n\treturn [...ids].filter((id) => findVectorNode(state.document.nodes, id)?.type === 'path');\n}\n\n/** Every anchor drawn on the canvas. */\nexport function getVisibleAnchors(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen'>): VectorAnchorRef[] {\n\tconst out: VectorAnchorRef[] = [];\n\tfor (const id of getEditablePathIds(state)) {\n\t\tconst node = findVectorNode(state.document.nodes, id) as VectorPathNode;\n\t\tnode.subpaths.forEach((sp, s) => sp.anchors.forEach((_, i) => out.push({ nodeId: id, subpath: s, index: i })));\n\t}\n\treturn out;\n}\n\n/**\n * Handles drawn on the canvas: those of selected anchors and of the segments next to them\n * (direct tool), or of the last anchor of the pen path.\n */\nexport function getVisibleHandles(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen' | 'selectedAnchors'>\n): VectorHandleRef[] {\n\tconst out: VectorHandleRef[] = [];\n\tconst seen = new Set<string>();\n\tconst push = (node: VectorPathNode, s: number, i: number, handle: 'in' | 'out') => {\n\t\tconst sp = node.subpaths[s];\n\t\tconst a = sp?.anchors[i];\n\t\tif (!a || !a[handle]) return;\n\t\tconst key = `${node.id}:${s}:${i}:${handle}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tout.push({ nodeId: node.id, subpath: s, index: i, handle });\n\t};\n\tif (state.tool === 'pen' && state.pen) {\n\t\tconst node = findVectorNode(state.document.nodes, state.pen.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[state.pen.subpath] : undefined;\n\t\tif (node?.type === 'path' && sp) {\n\t\t\tconst last = sp.anchors.length - 1;\n\t\t\tpush(node, state.pen.subpath, last, 'in');\n\t\t\tpush(node, state.pen.subpath, last, 'out');\n\t\t}\n\t\treturn out;\n\t}\n\tif (state.tool !== 'direct') return out;\n\tconst editable = new Set(getEditablePathIds(state));\n\tfor (const ref of state.selectedAnchors) {\n\t\tif (!editable.has(ref.nodeId)) continue;\n\t\tconst node = findVectorNode(state.document.nodes, ref.nodeId) as VectorPathNode;\n\t\tconst sp = node.subpaths[ref.subpath];\n\t\tif (!sp) continue;\n\t\tconst n = sp.anchors.length;\n\t\tpush(node, ref.subpath, ref.index, 'in');\n\t\tpush(node, ref.subpath, ref.index, 'out');\n\t\tconst prev = ref.index > 0 ? ref.index - 1 : sp.closed ? n - 1 : -1;\n\t\tconst next = ref.index < n - 1 ? ref.index + 1 : sp.closed ? 0 : -1;\n\t\tif (prev >= 0) push(node, ref.subpath, prev, 'out');\n\t\tif (next >= 0) push(node, ref.subpath, next, 'in');\n\t}\n\treturn out;\n}\n\n/** Live corner widgets sit at least this far inside their corner (screen px along each side of a right angle). */\nexport const VECTOR_CORNER_WIDGET_INSET = 10;\n\n/** A live corner widget of the direct tool: drag it to round the corners, Alt-click to change their kind. */\nexport interface VectorCornerWidget {\n\tref: VectorAnchorRef;\n\t/** Document position of the widget. */\n\tx: number;\n\ty: number;\n\t/** The radius stored on the anchor and the radius drawn (no larger than fits). */\n\tradius: number;\n\tdrawnRadius: number;\n\tkind: VectorCornerKind;\n\t/** The corner in its node's own space. */\n\tcorner: VectorCornerInfo;\n}\n\n/**\n * The live corner widgets the direct tool shows: on each editable path, at its selected corner\n * anchors (or at every corner when none of its anchors is selected). Corners whose sides are\n * shorter than three insets on screen hide theirs. Dragging one sets the radius of all of them.\n * Ported from ArtCraft vectorcraft `crates/tools/src/corners.rs` (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md), as is the `corner` drag below.\n */\nexport function getVectorCornerWidgets(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen' | 'selectedAnchors' | 'viewport'>\n): VectorCornerWidget[] {\n\tif (state.tool !== 'direct' || state.pen) return [];\n\tconst zoom = state.viewport.zoom;\n\tconst out: VectorCornerWidget[] = [];\n\tfor (const id of getEditablePathIds(state)) {\n\t\tconst node = findVectorNode(state.document.nodes, id) as VectorPathNode;\n\t\tconst picked = state.selectedAnchors.filter((r) => r.nodeId === id);\n\t\tconst m = vectorWorldMatrix(state.document.nodes, id) ?? IDENTITY_MATRIX;\n\t\tfor (const c of vectorCorners(node.subpaths)) {\n\t\t\tif (picked.length && !picked.some((r) => r.subpath === c.subpath && r.index === c.index)) continue;\n\t\t\tconst side = Math.min(c.lu, c.lv);\n\t\t\tif (side * zoom < 3 * VECTOR_CORNER_WIDGET_INSET) continue;\n\t\t\tconst a = node.subpaths[c.subpath].anchors[c.index];\n\t\t\tconst radius = a.corner?.radius ?? 0;\n\t\t\tconst drawn = fitCornerRadius(c, radius);\n\t\t\t// On the bisector at the centre of the arc as drawn, at least the inset in and at most half the shorter side.\n\t\t\tconst k = Math.min(Math.max(drawn / c.sin, VECTOR_CORNER_WIDGET_INSET / (zoom * Math.sqrt(1 + c.cos))), side / 2);\n\t\t\tconst p = applyMatrix(m, cornerBisectorPoint(c, k));\n\t\t\tout.push({ ref: { nodeId: id, subpath: c.subpath, index: c.index }, x: p.x, y: p.y, radius, drawnRadius: drawn, kind: a.corner?.kind ?? 'round', corner: c });\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * The line a path's stroke follows (node space; shortened under `tip` arrowheads) and the\n * distance a side scale of 1 reaches from it (half the drawn width: twice the stroke width for\n * inside / outside strokes). Null for paths without a visible stroke.\n */\nexport function vectorStrokeWidthGeometry(node: VectorPathNode): { line: BezierPath; unit: number } | null {\n\tif (!hasPaint(node.stroke) || !((node.strokeWidth ?? 1) > 0)) return null;\n\tconst parts = vectorStrokeParts(subpathsToBezier(node.subpaths), node);\n\treturn parts.line.length ? { line: parts.line, unit: parts.drawWidth / 2 } : null;\n}\n\n/** A width point of the width tool, in document units. */\nexport interface VectorWidthHandle {\n\tref: VectorWidthPointRef;\n\t/** The point on the path. */\n\tx: number;\n\ty: number;\n\t/** Ends of its left and right sides. */\n\tleft: Vec2;\n\tright: Vec2;\n\tt: number;\n\t/** Side scales (multiples of half the stroke width). */\n\tleftScale: number;\n\trightScale: number;\n\tselected: boolean;\n}\n\n/**\n * Moves the points at `indices` of `profile` by `dt` along the path (kept in 0–1) and re-sorts\n * it (stably, so steps keep their order); `renumber` maps each old index to its new one.\n */\nfunction shiftWidthPoints(profile: readonly VectorWidthPoint[], indices: readonly number[], dt: number): { points: VectorWidthPoint[]; renumber: Map<number, number> } {\n\tconst moving = new Set(indices);\n\tconst tagged = profile.map((p, i) => ({ p: moving.has(i) ? { ...p, t: Math.min(Math.max(p.t + dt, 0), 1) } : { ...p }, i }));\n\ttagged.sort((a, b) => a.p.t - b.p.t || a.i - b.i);\n\treturn { points: tagged.map((x) => x.p), renumber: new Map(tagged.map((x, k) => [x.i, k])) };\n}\n\n/**\n * The width points the width tool shows: every profile point on every subpath of the stroke\n * under the pointer, the selected paths and the stroke being edited. Ported from ArtCraft\n * vectorcraft `crates/tools/src/distort/width.rs` (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md), as are the `width` drag and hover below.\n */\nexport function getVectorWidthHandles(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'tool' | 'hover' | 'interaction' | 'selectedWidthPoints'>\n): VectorWidthHandle[] {\n\tif (state.tool !== 'width') return [];\n\tconst ids = new Set<string>();\n\tfor (const id of state.selection) {\n\t\tconst n = findVectorNode(state.document.nodes, id);\n\t\tif (n) for (const p of collectPathNodes(n)) ids.add(p.id);\n\t}\n\tif (state.hover?.nodeId) ids.add(state.hover.nodeId);\n\tif (state.interaction?.type === 'width') ids.add(state.interaction.ref.nodeId);\n\tfor (const r of state.selectedWidthPoints) ids.add(r.nodeId);\n\tconst out: VectorWidthHandle[] = [];\n\tfor (const id of ids) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node?.type !== 'path' || node.visible === false || !node.strokeWidthProfile?.length) continue;\n\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\tif (!g) continue;\n\t\tconst profile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\tconst m = vectorWorldMatrix(state.document.nodes, id) ?? IDENTITY_MATRIX;\n\t\tconst contours = node.subpaths.length;\n\t\tfor (let sp = 0; sp < contours; sp++) {\n\t\t\tprofile.forEach((w, index) => {\n\t\t\t\tconst at = strokePositionPoint(g.line, sp, w.t);\n\t\t\t\tif (!at) return;\n\t\t\t\tconst n = { x: at.tangent[1], y: -at.tangent[0] };\n\t\t\t\tconst c = { x: at.point[0], y: at.point[1] };\n\t\t\t\tconst p = applyMatrix(m, c);\n\t\t\t\tconst l = applyMatrix(m, { x: c.x + n.x * w.left * g.unit, y: c.y + n.y * w.left * g.unit });\n\t\t\t\tconst r = applyMatrix(m, { x: c.x - n.x * w.right * g.unit, y: c.y - n.y * w.right * g.unit });\n\t\t\t\tout.push({\n\t\t\t\t\tref: { nodeId: id, index, subpath: sp },\n\t\t\t\t\tx: p.x,\n\t\t\t\t\ty: p.y,\n\t\t\t\t\tleft: l,\n\t\t\t\t\tright: r,\n\t\t\t\t\tt: w.t,\n\t\t\t\t\tleftScale: w.left,\n\t\t\t\t\trightScale: w.right,\n\t\t\t\t\tselected: state.selectedWidthPoints.some((r) => r.nodeId === id && r.index === index)\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Looks up an anchor (positions in its node's own space). */\nexport function getAnchor(doc: VectorDocument, ref: VectorAnchorRef): VectorAnchor | undefined {\n\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\treturn node?.type === 'path' ? node.subpaths[ref.subpath]?.anchors[ref.index] : undefined;\n}\n\n/** An anchor with its position and handles in document space (its node's transforms applied). */\nexport function getAnchorWorld(doc: VectorDocument, ref: VectorAnchorRef): { x: number; y: number; in?: Vec2; out?: Vec2; type?: VectorAnchorType } | undefined {\n\tconst a = getAnchor(doc, ref);\n\tif (!a) return undefined;\n\tconst m = vectorWorldMatrix(doc.nodes, ref.nodeId) ?? IDENTITY_MATRIX;\n\tconst p = applyMatrix(m, a);\n\treturn { x: p.x, y: p.y, ...(a.in ? { in: applyMatrix(m, a.in) } : {}), ...(a.out ? { out: applyMatrix(m, a.out) } : {}), ...(a.type ? { type: a.type } : {}) };\n}\n\n/**\n * The selection box: `angle` is the shared rotation of the selected nodes (0 when they\n * differ), `x / y / width / height` the bounds in the box's own frame (document space\n * rotated by −angle). A frame point `q` is at `rotateMatrix(angle)` applied to `q`.\n */\nexport interface VectorSelectionFrame {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\tangle: number;\n}\n\n/** The selection frame of nodes `ids` (see `VectorSelectionFrame`), or null when they have no points. */\nexport function getVectorSelectionFrame(doc: VectorDocument, ids: readonly string[]): VectorSelectionFrame | null {\n\tconst nodes = ids.map((id) => ({ node: findVectorNode(doc.nodes, id), parent: vectorParentMatrix(doc.nodes, id) ?? IDENTITY_MATRIX })).filter((n) => n.node);\n\tif (!nodes.length) return null;\n\tconst angles = nodes.map((n) => matrixRotation(multiplyMatrices(nodeMatrix(n.node!), n.parent)));\n\tconst same = angles.every((a) => Math.abs(normalizeAngle(a - angles[0])) < 1e-6);\n\tconst angle = same ? angles[0] : 0;\n\tconst unrotate = rotateMatrix(-angle);\n\tconst b = unionBounds(nodes.map((n) => vectorNodeBounds(n.node!, multiplyMatrices(n.parent, unrotate))));\n\treturn b ? { ...b, angle } : null;\n}\n\nconst normalizeAngle = (a: number) => ((((a + 180) % 360) + 360) % 360) - 180;\n\n/** Screen positions of the selection box handles for a box given in screen pixels. */\nexport function getTransformHandlePositions(box: VectorBounds): { handle: VectorTransformHandle; x: number; y: number }[] {\n\tconst { x, y, width: w, height: h } = box;\n\treturn [\n\t\t{ handle: 'nw', x, y },\n\t\t{ handle: 'n', x: x + w / 2, y },\n\t\t{ handle: 'ne', x: x + w, y },\n\t\t{ handle: 'e', x: x + w, y: y + h / 2 },\n\t\t{ handle: 'se', x: x + w, y: y + h },\n\t\t{ handle: 's', x: x + w / 2, y: y + h },\n\t\t{ handle: 'sw', x, y: y + h },\n\t\t{ handle: 'w', x, y: y + h / 2 },\n\t\t{ handle: 'rotate', x: x + w / 2, y: y - VECTOR_ROTATE_HANDLE_OFFSET }\n\t];\n}\n\n/**\n * Screen geometry of a selection box. `box` and each handle's `x / y` are the unrotated box\n * in screen pixels; draw them inside a group with `transform` (a `rotate(angle cx cy)`),\n * or use `screen` for the true on-screen positions (hit-testing).\n */\nexport interface VectorSelectionBoxGeometry {\n\tbox: VectorBounds;\n\tangle: number;\n\ttransform: string;\n\thandles: { handle: VectorTransformHandle; x: number; y: number; screen: Vec2 }[];\n\t/** The four corners on screen, clockwise from the top left. */\n\tcorners: Vec2[];\n}\n\nexport function getVectorSelectionBoxGeometry(frame: VectorSelectionFrame, viewport: VectorViewport): VectorSelectionBoxGeometry {\n\tconst z = viewport.zoom;\n\tconst box = { x: frame.x * z + viewport.x, y: frame.y * z + viewport.y, width: frame.width * z, height: frame.height * z };\n\tconst rot = rotateMatrix(frame.angle, { x: viewport.x, y: viewport.y });\n\tconst toScreen = (p: Vec2): Vec2 => (frame.angle ? applyMatrix(rot, p) : { x: p.x, y: p.y });\n\tconst handles = getTransformHandlePositions(box).map((h) => ({ ...h, screen: toScreen(h) }));\n\tconst corners = [\n\t\t{ x: box.x, y: box.y },\n\t\t{ x: box.x + box.width, y: box.y },\n\t\t{ x: box.x + box.width, y: box.y + box.height },\n\t\t{ x: box.x, y: box.y + box.height }\n\t].map(toScreen);\n\tconst r = (n: number) => Math.round(n * 1000) / 1000;\n\treturn { box, angle: frame.angle, transform: frame.angle ? `rotate(${r(frame.angle)} ${r(viewport.x)} ${r(viewport.y)})` : '', handles, corners };\n}\n\n/**\n * The node the Envelope tool edits: the one selected node with an enabled envelope, with the\n * envelope's mesh and box (node space) and the node → document matrix. Null otherwise.\n */\nexport function getVectorEnvelopeTarget(\n\tdoc: VectorDocument,\n\tselection: readonly string[]\n): { node: VectorNode; frame: { effectId: string; bounds: VectorBounds; mesh: VectorWarpMesh }; world: AffineMatrix } | null {\n\tif (selection.length !== 1) return null;\n\tconst node = findVectorNode(doc.nodes, selection[0]);\n\tif (!node || !vectorNodeEnvelope(node)) return null;\n\tconst frame = vectorEnvelopeFrame(node);\n\treturn frame ? { node, frame, world: vectorWorldMatrix(doc.nodes, node.id) ?? IDENTITY_MATRIX } : null;\n}\n\nconst RESIZE_CURSOR_ORDER = ['ew-resize', 'nwse-resize', 'ns-resize', 'nesw-resize'];\nconst HANDLE_ANGLES: Partial<Record<VectorTransformHandle, number>> = { e: 0, se: 45, s: 90, sw: 135, w: 180, nw: 225, n: 270, ne: 315 };\n\n/** The resize cursor for a handle of a box rotated by `angle` degrees. */\nexport function vectorResizeCursor(handle: VectorTransformHandle, angle = 0): string {\n\tif (handle === 'rotate') return 'grab';\n\tconst a = (((HANDLE_ANGLES[handle]! + angle) % 180) + 180) % 180;\n\treturn RESIZE_CURSOR_ORDER[Math.round(a / 45) % 4];\n}\n\n\nconst TOOL_LABELS: Record<VectorTool, string> = {\n\tselect: 'Select',\n\tdirect: 'Direct Select',\n\tpen: 'Pen',\n\tpencil: 'Pencil',\n\trect: 'Rectangle',\n\tellipse: 'Ellipse',\n\tpolygon: 'Polygon',\n\tstar: 'Star',\n\tline: 'Line',\n\tscissors: 'Scissors',\n\tknife: 'Knife',\n\teraser: 'Eraser',\n\twidth: 'Width',\n\tshapeBuilder: 'Shape Builder',\n\tpaintBucket: 'Paint Bucket',\n\tblend: 'Blend',\n\tgradient: 'Gradient',\n\tenvelope: 'Envelope Mesh'\n};\n\nconst TOOL_KEYS: Record<string, VectorTool> = {\n\tv: 'select',\n\ta: 'direct',\n\tp: 'pen',\n\tn: 'pencil',\n\tr: 'rect',\n\to: 'ellipse',\n\ty: 'polygon',\n\ts: 'star',\n\tl: 'line',\n\tc: 'scissors',\n\tk: 'knife',\n\te: 'eraser',\n\tw: 'width',\n\tm: 'shapeBuilder',\n\tb: 'paintBucket',\n\tj: 'blend',\n\tg: 'gradient',\n\tu: 'envelope'\n};\n\nexport function vectorToolLabel(tool: VectorTool): string {\n\treturn TOOL_LABELS[tool];\n}\n\n/** Keyboard shortcut of each tool (single letters, no modifiers). */\nexport const VECTOR_TOOL_SHORTCUTS: Readonly<Record<VectorTool, string>> = {\n\tselect: 'V',\n\tdirect: 'A',\n\tpen: 'P',\n\tpencil: 'N',\n\trect: 'R',\n\tellipse: 'O',\n\tpolygon: 'Y',\n\tstar: 'S',\n\tline: 'L',\n\tscissors: 'C',\n\tknife: 'K',\n\teraser: 'E',\n\twidth: 'W',\n\tshapeBuilder: 'M',\n\tpaintBucket: 'B',\n\tblend: 'J',\n\tgradient: 'G',\n\tenvelope: 'U'\n};\n\n/** Short glyphs for tool buttons (pair them with `vectorToolLabel` for the accessible name). */\nexport const VECTOR_TOOL_GLYPHS: Readonly<Record<VectorTool, string>> = {\n\tselect: '↖',\n\tdirect: '⌖',\n\tpen: '✒',\n\tpencil: '✎',\n\trect: '▭',\n\tellipse: '◯',\n\tpolygon: '⬡',\n\tstar: '☆',\n\tline: '╱',\n\tscissors: '✂',\n\tknife: '⟋',\n\teraser: '⌫',\n\twidth: '⇹',\n\tshapeBuilder: '⊕',\n\tpaintBucket: '◍',\n\tblend: '⧓',\n\tgradient: '◐',\n\tenvelope: '⌗'\n};\n\n/** Tools that drag out a shape (they snap while hovering). */\nconst SHAPE_TOOLS: ReadonlySet<VectorTool> = new Set(['rect', 'ellipse', 'polygon', 'star', 'line']);\n\nconst BOOLEAN_OPS: Record<VectorBooleanOperation, 'union' | 'difference' | 'intersection' | 'xor'> = {\n\tunion: 'union',\n\tsubtract: 'difference',\n\tintersect: 'intersection',\n\texclude: 'xor'\n};\n\nconst BOOLEAN_LABELS: Record<VectorBooleanOperation, string> = { union: 'Union', subtract: 'Subtract', intersect: 'Intersect', exclude: 'Exclude' };\n\n/** Names of the Pathfinder operations (undo steps, groups and buttons). */\nexport const VECTOR_PATHFINDER_LABELS: Readonly<Record<VectorPathfinderOperation, string>> = {\n\tdivide: 'Divide',\n\ttrim: 'Trim',\n\tmerge: 'Merge',\n\tcrop: 'Crop',\n\toutline: 'Outline',\n\tminusBack: 'Minus Back'\n};\n\n/** Replaces nodes by id anywhere in the tree (structural sharing for untouched branches). */\nfunction mapTree(nodes: readonly VectorNode[], fn: (node: VectorNode) => VectorNode | null): VectorNode[] {\n\tlet changed = false;\n\tconst out: VectorNode[] = [];\n\tfor (const node of nodes) {\n\t\tlet next = fn(node);\n\t\tif (next && next.type === 'group') {\n\t\t\tconst children = mapTree(next.children, fn);\n\t\t\tif (children !== next.children) next = { ...next, children };\n\t\t}\n\t\tif (next !== node) changed = true;\n\t\tif (next) out.push(next);\n\t}\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\n/** Replaces node `id` anywhere in the tree with `replacements` (none removes it). */\nfunction spliceTree(nodes: readonly VectorNode[], id: string, replacements: readonly VectorNode[]): VectorNode[] {\n\tlet changed = false;\n\tconst out: VectorNode[] = [];\n\tfor (const node of nodes) {\n\t\tif (node.id === id) {\n\t\t\tchanged = true;\n\t\t\tout.push(...replacements);\n\t\t\tcontinue;\n\t\t}\n\t\tif (node.type === 'group') {\n\t\t\tconst children = spliceTree(node.children, id, replacements);\n\t\t\tif (children !== node.children) {\n\t\t\t\tchanged = true;\n\t\t\t\tout.push({ ...node, children });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tout.push(node);\n\t}\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\nconst toPoint = (p: Vec2): Point => [p.x, p.y];\n\n/** A node's place and state (transform, visibility, lock, operand operation), for a node taking its place. */\nconst placementOf = (n: VectorNode) => ({\n\t...(n.transform ? { transform: n.transform } : {}),\n\t...(n.visible === false ? { visible: false } : {}),\n\t...(n.locked ? { locked: true } : {}),\n\t...(n.booleanOperation ? { booleanOperation: n.booleanOperation } : {})\n});\n\nconst isRoot = (m: AffineMatrix) => m === IDENTITY_MATRIX || (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0);\n\nlet idCounter = 0;\nconst defaultCreateId = () => `vn-${Date.now().toString(36)}${(++idCounter).toString(36)}`;\n\n// ---------------------------------------------------------------------------\n// Controller\n// ---------------------------------------------------------------------------\n\ninterface Snapshot {\n\tdoc: VectorDocument;\n\tselection: string[];\n\tanchors: VectorAnchorRef[];\n\teditingId: string | null;\n\tpen: { nodeId: string; subpath: number } | null;\n}\n\n/** Snap targets of a drag, gathered on its first move that needs them. */\ntype DragTargets = { targets?: VectorSnapTargets };\n\ntype Drag =\n\t| ({ kind: 'move'; start: Vec2; origin: VectorBounds | null; before: Snapshot; base: VectorDocument; moved: boolean; duplicated: boolean; clickId: string | null } & DragTargets)\n\t| ({ kind: 'scale'; handle: VectorTransformHandle; start: Vec2; frame: VectorSelectionFrame; before: Snapshot; base: VectorDocument; op?: string } & DragTargets)\n\t| {\n\t\t\tkind: 'envelope';\n\t\t\tnodeId: string;\n\t\t\teffectId: string;\n\t\t\t/** The mesh at the start (node space) and the document it belongs to. */\n\t\t\tbase: VectorWarpMesh;\n\t\t\tbaseDoc: VectorDocument;\n\t\t\tbefore: Snapshot;\n\t\t\tindex: number | null;\n\t\t\ts: number;\n\t\t\tt: number;\n\t\t\tstart: Vec2;\n\t\t\tmoved: boolean;\n\t }\n\t| { kind: 'rotate'; start: Vec2; center: Vec2; before: Snapshot; base: VectorDocument }\n\t| { kind: 'marquee'; start: Vec2; base: string[]; baseAnchors: VectorAnchorRef[]; anchorsMode: boolean }\n\t| ({ kind: 'anchors'; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean; clickRef: VectorAnchorRef | null; lead: VectorAnchorRef | null } & DragTargets)\n\t| ({ kind: 'handle'; ref: VectorHandleRef; before: Snapshot; base: VectorDocument } & DragTargets)\n\t| { kind: 'bend'; ref: VectorSegmentRef; t: number; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean }\n\t| { kind: 'corner'; widget: VectorCornerWidget; refs: VectorAnchorRef[]; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean; alt: boolean; shift: boolean }\n\t| { kind: 'stroke'; tool: 'knife' | 'eraser'; points: Vec2[]; before: Snapshot }\n\t| { kind: 'builder'; erase: boolean; points: Vec2[]; touched: VectorBuilderTouched; map: VectorShapeBuilderMap }\n\t| { kind: 'pull'; ref: VectorAnchorRef; before: Snapshot; base: VectorDocument; label: string; outOnly: boolean; closing: boolean; altBreaks: boolean }\n\t| ({ kind: 'shape'; tool: VectorTool; start: Vec2; nodeId: string; before: Snapshot } & DragTargets)\n\t| { kind: 'pencil'; nodeId: string; points: Point[]; before: Snapshot; lazy: LazyMouse; pressures: number[] | null; pressure: number }\n\t| {\n\t\t\tkind: 'width';\n\t\t\tref: VectorWidthPointRef;\n\t\t\t/** `copy`: Alt-drag a centre to slide a copy of the point. */\n\t\t\tmode: 'width' | 'move' | 'copy';\n\t\t\tside: 'both' | 'left' | 'right';\n\t\t\t/** The index the drag started on (the source of a copy). */\n\t\t\tsource: number;\n\t\t\t/** Other selected points of the path that move or widen with it (indices into `profile`). */\n\t\t\tgroup: number[];\n\t\t\t/** Shift-click (adding the point): a click without a move keeps the other selected points. */\n\t\t\tshift: boolean;\n\t\t\t/** Old index → new index after a group move re-sorted the profile. */\n\t\t\trenumber: Map<number, number> | null;\n\t\t\t/** The stroke line's point and left normal where the drag started (node space). */\n\t\t\torigin: Vec2;\n\t\t\tnormal: Vec2;\n\t\t\t/** Half the drawn stroke width: side scale 1 reaches this far. */\n\t\t\tunit: number;\n\t\t\tprofile: VectorWidthPoint[];\n\t\t\tbefore: Snapshot;\n\t\t\tbase: VectorDocument;\n\t\t\tstart: Vec2;\n\t\t\tmoved: boolean;\n\t\t\tcreated: boolean;\n\t }\n\t| {\n\t\t\tkind: 'gradient';\n\t\t\t/** What was grabbed: null draws a new vector over `targets`. */\n\t\t\tpart: VectorGradientPart | null;\n\t\t\tnodeId: string | null;\n\t\t\ttargets: string[];\n\t\t\tannotator: VectorGradientAnnotator | null;\n\t\t\tstart: Vec2;\n\t\t\tstartDoc: Vec2;\n\t\t\tbefore: Snapshot;\n\t\t\tbase: VectorDocument;\n\t\t\tmoved: boolean;\n\t\t\t/** The dragged stop's index now (null once dragged off the bar). */\n\t\t\tstop: number | null;\n\t }\n\t| { kind: 'pan'; start: Vec2; viewport: VectorViewport };\n\n/**\n * Headless state for a vector editor: a document of paths and groups, select / direct /\n * pen / pencil / shape tools driven by pointer and key events, undo, transforms, boolean\n * operations, alignment, grouping, SVG import / export and a viewport. Any UI forwards\n * pointer events (in canvas pixels) and renders `getState()`; `getState()` returns the same\n * object until something changes, so it works with `useSyncExternalStore` and Svelte runes.\n */\nexport class VectorEditorController {\n\treadonly history: HistoryManager;\n\tprivate doc: VectorDocument;\n\tprivate selection: string[] = [];\n\tprivate anchors: VectorAnchorRef[] = [];\n\tprivate widthPoints: VectorWidthPointRef[] = [];\n\tprivate widthEdit: VectorWidthPointEdit | null = null;\n\tprivate editingId: string | null = null;\n\tprivate pen: { nodeId: string; subpath: number } | null = null;\n\tprivate tool: VectorTool;\n\tprivate defaults: VectorEditorState['defaults'];\n\tprivate viewport: VectorViewport;\n\tprivate snap: VectorSnapOptions;\n\tprivate editing: VectorPathEditOptions;\n\tprivate hitRadius: number;\n\tprivate hover: VectorHover | null = null;\n\tprivate pointer: Vec2 | null = null;\n\tprivate drag: Drag | null = null;\n\tprivate interaction: VectorInteraction | null = null;\n\tprivate guides: VectorSnapGuides | null = null;\n\t/** Whether the last `snapDrawn` landed on an object (guides may be hidden). */\n\tprivate snappedToObject = false;\n\t/** Drawing targets for hovering the pen and shape tools, kept while the document and the excluded path stay the same. */\n\tprivate hoverTargets: { doc: VectorDocument; exclude: string; targets: VectorSnapTargets } | null = null;\n\tprivate spaceHeld = false;\n\tprivate clipboard: VectorNode[] | null = null;\n\t/** Shape Builder map of the selection, kept while the document and the selection stay the same. */\n\tprivate builderCache: { doc: VectorDocument; key: string; map: VectorShapeBuilderMap | null } | null = null;\n\t/** Paint bucket map of the visible outlines. */\n\tprivate fillCache: { doc: VectorDocument; gap: number; map: PlanarMap | null } | null = null;\n\tprivate builderPreview: VectorBuilderPreview | null = null;\n\tprivate blendStart: VectorBlendStart | null = null;\n\t/** Options new blends get (the toolbars edit them along with the selected blend's). */\n\tprivate blendDefaults: VectorBlendOptions = {};\n\tprivate gradientEdit: VectorEditorState['gradientEdit'] = { target: 'fill', stop: null };\n\tprivate freeDistort = false;\n\t/** What the highlight shows, to skip notifying when the pointer stays over the same face. */\n\tprivate builderHoverKey: string | null = null;\n\tprivate readonly createId: () => string;\n\tprivate readonly onChange?: (document: VectorDocument) => void;\n\tprivate readonly listeners = new Set<(state: VectorEditorState) => void>();\n\tprivate readonly cleanups: Array<() => void> = [];\n\tprivate applying = false;\n\t/** Set while a commit records a change that was already applied, so `restore` still reports it. */\n\tprivate committing = false;\n\tprivate revision = 0;\n\tprivate state!: VectorEditorState;\n\n\tconstructor(options: VectorEditorOptions = {}) {\n\t\tthis.history = options.history ?? new HistoryManager();\n\t\tthis.doc = options.document ? cloneVectorDocument(options.document) : { width: 800, height: 600, nodes: [] };\n\t\tthis.doc = this.refreshed(this.doc);\n\t\tthis.tool = options.tool ?? 'select';\n\t\tthis.defaults = { ...DEFAULT_DEFAULTS, ...(options.defaults ?? {}) } as VectorEditorState['defaults'];\n\t\tthis.viewport = { x: 0, y: 0, zoom: 1, ...(options.viewport ?? {}) };\n\t\tthis.snap = { ...DEFAULT_VECTOR_SNAP, ...(options.snap ?? {}) };\n\t\tthis.editing = { ...DEFAULT_VECTOR_PATH_EDIT, ...(options.editing ?? {}) };\n\t\tthis.hitRadius = options.hitRadius ?? 6;\n\t\tthis.createId = options.createId ?? defaultCreateId;\n\t\tthis.onChange = options.onChange;\n\t\tthis.freeDistort = !!options.freeDistort;\n\t\tthis.state = this.computeState();\n\t\tthis.connect();\n\t}\n\n\t/** Listens to the history (once; again after `destroy`). */\n\tprivate connect(): void {\n\t\tif (this.cleanups.length) return;\n\t\tthis.cleanups.push(\n\t\t\tthis.history.subscribe((h) => {\n\t\t\t\tif (!this.applying && this.historyDiffers(h)) this.notify();\n\t\t\t})\n\t\t);\n\t\t// Catch up on history changes made while disconnected.\n\t\tif (this.historyDiffers(this.history.getState())) this.state = this.computeState();\n\t}\n\n\tprivate historyDiffers(h: ReturnType<HistoryManager['getState']>): boolean {\n\t\tconst s = this.state;\n\t\treturn s.canUndo !== h.canUndo || s.canRedo !== h.canRedo || s.undoLabel !== h.undoName || s.redoLabel !== h.redoName;\n\t}\n\n\t/**\n\t * Stops listening to the history and drops all listeners. A later `subscribe` reconnects, so a\n\t * controller torn down by React StrictMode's double effect keeps working when it is reused.\n\t */\n\tdestroy(): void {\n\t\tthis.cleanups.splice(0).forEach((fn) => fn());\n\t\tthis.listeners.clear();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// State\n\t// -------------------------------------------------------------------------\n\n\t/** The current snapshot (stable until the next change). */\n\tgetState = (): VectorEditorState => this.state;\n\n\t/** Calls `listener` after every change. Returns an unsubscribe function. */\n\tsubscribe = (listener: (state: VectorEditorState) => void): (() => void) => {\n\t\tthis.connect();\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t};\n\n\tgetDocument(): VectorDocument {\n\t\treturn this.doc;\n\t}\n\n\tgetNode(id: string): VectorNode | undefined {\n\t\treturn findVectorNode(this.doc.nodes, id);\n\t}\n\n\tprivate computeState(): VectorEditorState {\n\t\tconst h = this.history.getState();\n\t\treturn {\n\t\t\tdocument: this.doc,\n\t\t\ttool: this.tool,\n\t\t\tselection: this.selection,\n\t\t\tselectedAnchors: this.anchors,\n\t\t\tselectedWidthPoints: this.widthPoints,\n\t\t\twidthPointEdit: this.widthEdit,\n\t\t\teditingId: this.editingId,\n\t\t\tselectionBounds: this.boundsOf(this.selection),\n\t\t\tselectionFrame: this.frameOf(this.selectedRoots()),\n\t\t\tviewport: this.viewport,\n\t\t\tdefaults: this.defaults,\n\t\t\tsnap: this.snap,\n\t\t\tediting: this.editing,\n\t\t\tguides: this.guides,\n\t\t\thitRadius: this.hitRadius,\n\t\t\thover: this.hover,\n\t\t\tcursor: this.cursorFor(),\n\t\t\tinteraction: this.interaction,\n\t\t\tpen: this.pen,\n\t\t\tpointer: this.pointer,\n\t\t\tbuilder: this.builderPreview,\n\t\t\tblendStart: this.blendStart,\n\t\t\tblendDefaults: this.blendDefaults,\n\t\t\tgradientEdit: this.gradientEdit,\n\t\t\tfreeDistort: this.freeDistort,\n\t\t\tcanUndo: h.canUndo,\n\t\t\tcanRedo: h.canRedo,\n\t\t\tundoLabel: h.undoName,\n\t\t\tredoLabel: h.redoName,\n\t\t\trevision: this.revision\n\t\t};\n\t}\n\n\t/** `doc` with its blends' steps brought up to date (the same object when they already are). */\n\tprivate refreshed(doc: VectorDocument): VectorDocument {\n\t\tconst nodes = refreshVectorBlends(doc.nodes);\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\tprivate notify(docChanged = false) {\n\t\t// Blends regenerate their steps after every edit of a key (drags included).\n\t\tconst fresh = this.refreshed(this.doc);\n\t\tif (fresh !== this.doc) this.doc = fresh;\n\t\tif (this.blendStart && !this.getNode(this.blendStart.nodeId)) this.blendStart = null;\n\t\tthis.revision++;\n\t\tthis.state = this.computeState();\n\t\tif (docChanged) this.onChange?.(this.doc);\n\t\tconst state = this.state;\n\t\tthis.listeners.forEach((listener) => {\n\t\t\ttry {\n\t\t\t\tlistener(state);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[VectorEditorController] Error in state listener:', error);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate boundsOf(ids: readonly string[]): VectorBounds | null {\n\t\treturn unionBounds(\n\t\t\tids.map((id) => {\n\t\t\t\tconst n = this.getNode(id);\n\t\t\t\treturn n ? vectorNodeBounds(n, vectorParentMatrix(this.doc.nodes, id) ?? IDENTITY_MATRIX) : null;\n\t\t\t})\n\t\t);\n\t}\n\n\tprivate frameOf(ids: readonly string[]): VectorSelectionFrame | null {\n\t\treturn getVectorSelectionFrame(this.doc, ids);\n\t}\n\n\t/** Local → document matrix of a node in `doc` (default: the current document). */\n\tprivate worldOf(id: string, doc: VectorDocument = this.doc): AffineMatrix {\n\t\treturn vectorWorldMatrix(doc.nodes, id) ?? IDENTITY_MATRIX;\n\t}\n\n\t/** A document point in node `id`'s own space. */\n\tprivate toLocal(id: string, p: Vec2, doc: VectorDocument = this.doc): Vec2 {\n\t\treturn applyMatrix(invertMatrix(this.worldOf(id, doc)), p);\n\t}\n\n\tprivate cursorFor(): string {\n\t\tif (this.drag?.kind === 'pan' || this.spaceHeld) return this.drag ? 'grabbing' : 'grab';\n\t\tif (this.drag?.kind === 'rotate') return 'grabbing';\n\t\tif (this.drag?.kind === 'move') return 'move';\n\t\tconst h = this.hover;\n\t\tswitch (this.tool) {\n\t\t\tcase 'select':\n\t\t\t\tif (h?.transformHandle && this.freeDistort && h.transformHandle !== 'rotate') return 'crosshair';\n\t\t\t\tif (h?.transformHandle) return vectorResizeCursor(h.transformHandle, this.frameOf(this.selectedRoots())?.angle ?? 0);\n\t\t\t\treturn h?.nodeId ? 'move' : 'default';\n\t\t\tcase 'envelope':\n\t\t\t\tif (this.drag?.kind === 'envelope') return 'grabbing';\n\t\t\t\tif (h?.envelope) return h.envelope.index === null ? 'grab' : 'pointer';\n\t\t\t\treturn h?.nodeId ? 'pointer' : 'default';\n\t\t\tcase 'direct':\n\t\t\t\tif (h?.anchor || h?.handle || h?.corner) return 'pointer';\n\t\t\t\tif (h?.segment) return 'copy';\n\t\t\t\treturn h?.nodeId ? 'move' : 'default';\n\t\t\tcase 'pen':\n\t\t\t\treturn h?.anchor ? 'pointer' : 'crosshair';\n\t\t\tcase 'width':\n\t\t\t\tif (this.drag?.kind === 'width') return this.drag.mode === 'width' ? 'ew-resize' : 'grabbing';\n\t\t\t\tif (h?.widthPoint) return h.widthPoint.part === 'center' ? 'grab' : 'ew-resize';\n\t\t\t\treturn h?.strokeSpot ? 'copy' : 'default';\n\t\t\tcase 'shapeBuilder':\n\t\t\t\tif (!this.builderPreview?.faces.length && !this.builderPreview?.lines.length) return 'crosshair';\n\t\t\t\treturn this.builderPreview.mode === 'erase' ? 'not-allowed' : 'cell';\n\t\t\tcase 'paintBucket':\n\t\t\t\treturn this.builderPreview ? 'cell' : 'crosshair';\n\t\t\tcase 'blend':\n\t\t\t\treturn h?.nodeId ? (this.blendStart && this.blendStart.nodeId !== h.nodeId ? 'copy' : 'pointer') : 'crosshair';\n\t\t\tcase 'gradient': {\n\t\t\t\tconst part = this.drag?.kind === 'gradient' ? this.drag.part : h?.gradient;\n\t\t\t\tif (!part) return 'crosshair';\n\t\t\t\tif (part.kind === 'bar') return this.drag ? 'grabbing' : 'copy';\n\t\t\t\tif (part.kind === 'handle' && part.handle === 'start') return this.drag ? 'grabbing' : 'move';\n\t\t\t\treturn 'pointer';\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn 'crosshair';\n\t\t}\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Undoable changes\n\t// -------------------------------------------------------------------------\n\n\tprivate snapshot(): Snapshot {\n\t\treturn { doc: this.doc, selection: this.selection, anchors: this.anchors, editingId: this.editingId, pen: this.pen };\n\t}\n\n\tprivate restore(s: Snapshot) {\n\t\tconst docChanged = s.doc !== this.doc || this.committing;\n\t\t// Undo / redo can renumber width points: drop the ones that are gone and close the editor.\n\t\tif (!this.committing) this.widthEdit = null;\n\t\tthis.committing = false;\n\t\tthis.applying = true;\n\t\ttry {\n\t\t\tthis.doc = s.doc;\n\t\t\tthis.selection = s.selection.filter((id) => this.getNode(id));\n\t\t\tthis.anchors = s.anchors.filter((r) => getAnchor(this.doc, r));\n\t\t\tthis.editingId = s.editingId && this.getNode(s.editingId) ? s.editingId : null;\n\t\t\tthis.pen = s.pen && (this.getNode(s.pen.nodeId) as VectorPathNode | undefined)?.subpaths?.[s.pen.subpath] ? s.pen : null;\n\t\t\tif (this.widthPoints.length) {\n\t\t\t\tconst kept = this.widthPoints.filter((r) => {\n\t\t\t\t\tconst n = this.getNode(r.nodeId);\n\t\t\t\t\treturn n?.type === 'path' && !!n.strokeWidthProfile?.[r.index];\n\t\t\t\t});\n\t\t\t\tif (kept.length !== this.widthPoints.length) this.widthPoints = kept;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.applying = false;\n\t\t}\n\t\tthis.notify(docChanged);\n\t}\n\n\t/**\n\t * Records the change from `before` to the current state as one undo step. Consecutive\n\t * changes with the same `merge` key (a slider drag) fold into one step.\n\t */\n\tprivate commit(name: string, before: Snapshot, merge?: string) {\n\t\tthis.doc = this.refreshed(this.doc);\n\t\tconst after = this.snapshot();\n\t\tif (before.doc === after.doc) {\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst command: Command = {\n\t\t\tname,\n\t\t\texecute: () => this.restore(after),\n\t\t\tundo: () => this.restore(before),\n\t\t\tredo: () => this.restore(after),\n\t\t\t...(merge ? { tag: merge } : {})\n\t\t};\n\t\tthis.committing = true;\n\t\tif (merge) this.history.executeMerged(command, { key: merge });\n\t\telse this.history.execute(command);\n\t\tthis.committing = false;\n\t}\n\n\t/** Runs `fn` (which updates fields) and records it as one undo step (merged by `merge` key). */\n\tprivate change(name: string, fn: () => void, merge?: string): void {\n\t\tconst before = this.snapshot();\n\t\tfn();\n\t\tthis.commit(name, before, merge);\n\t}\n\n\t/** Ends a merged edit (a slider released): the next change starts a new undo step. */\n\tendMergedEdit(): void {\n\t\tthis.history.endGesture();\n\t}\n\n\tprivate setDoc(nodes: VectorNode[]) {\n\t\tif (nodes !== this.doc.nodes) this.doc = { ...this.doc, nodes };\n\t}\n\n\tprivate replaceNode(id: string, next: VectorNode | null) {\n\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === id ? next : n)));\n\t}\n\n\tprivate freshIds<T extends VectorNode>(node: T): T {\n\t\tconst copy = cloneVectorNode(node);\n\t\tconst used = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n) => used.add(n.id));\n\t\tconst next = () => {\n\t\t\tlet id = this.createId();\n\t\t\twhile (used.has(id)) id = this.createId();\n\t\t\tused.add(id);\n\t\t\treturn id;\n\t\t};\n\t\tconst assign = (n: VectorNode) => {\n\t\t\tn.id = next();\n\t\t\tif (n.type === 'group') n.children.forEach(assign);\n\t\t};\n\t\tassign(copy);\n\t\treturn copy;\n\t}\n\n\tprivate newId(): string {\n\t\tlet id = this.createId();\n\t\twhile (this.getNode(id)) id = this.createId();\n\t\treturn id;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Viewport\n\t// -------------------------------------------------------------------------\n\n\tscreenToDocument(p: Vec2): Vec2 {\n\t\tconst v = this.viewport;\n\t\treturn { x: (p.x - v.x) / v.zoom, y: (p.y - v.y) / v.zoom };\n\t}\n\n\tdocumentToScreen(p: Vec2): Vec2 {\n\t\tconst v = this.viewport;\n\t\treturn { x: p.x * v.zoom + v.x, y: p.y * v.zoom + v.y };\n\t}\n\n\tsetViewport(viewport: Partial<VectorViewport>): void {\n\t\tconst next = { ...this.viewport, ...viewport };\n\t\tnext.zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, next.zoom));\n\t\tif (next.x === this.viewport.x && next.y === this.viewport.y && next.zoom === this.viewport.zoom) return;\n\t\tthis.viewport = next;\n\t\tthis.notify();\n\t}\n\n\t/** Zooms by `factor` keeping the document point under `screen` in place. */\n\tzoomAt(screen: Vec2, factor: number): void {\n\t\tconst zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, this.viewport.zoom * factor));\n\t\tconst doc = this.screenToDocument(screen);\n\t\tthis.setViewport({ zoom, x: screen.x - doc.x * zoom, y: screen.y - doc.y * zoom });\n\t}\n\n\tpanBy(dx: number, dy: number): void {\n\t\tthis.setViewport({ x: this.viewport.x + dx, y: this.viewport.y + dy });\n\t}\n\n\t/** Fits the artboard (or `bounds`) into a canvas of `size` screen pixels. */\n\tzoomToFit(size: { width: number; height: number }, options: { padding?: number; bounds?: VectorBounds } = {}): void {\n\t\tconst padding = options.padding ?? 40;\n\t\tconst b = options.bounds ?? { x: 0, y: 0, width: this.doc.width, height: this.doc.height };\n\t\tconst zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min((size.width - padding * 2) / (b.width || 1), (size.height - padding * 2) / (b.height || 1))));\n\t\tthis.setViewport({ zoom, x: (size.width - b.width * zoom) / 2 - b.x * zoom, y: (size.height - b.height * zoom) / 2 - b.y * zoom });\n\t}\n\n\t/** Zoom at the canvas centre-ish: positive `delta` zooms out (wheel convention). Use with `wheel`. */\n\twheel(screen: Vec2, delta: { x: number; y: number }, mods: VectorModifiers = {}): void {\n\t\tif (mods.mod) this.zoomAt(screen, Math.exp(-delta.y * 0.01));\n\t\telse this.panBy(-(mods.shift ? delta.y : delta.x), -(mods.shift ? 0 : delta.y));\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Settings\n\t// -------------------------------------------------------------------------\n\n\tsetTool(tool: VectorTool): void {\n\t\tif (tool === this.tool) return;\n\t\tthis.finishPath();\n\t\tthis.cancelDrag();\n\t\tthis.tool = tool;\n\t\tthis.hover = null;\n\t\tthis.guides = null;\n\t\tthis.widthPoints = [];\n\t\tthis.widthEdit = null;\n\t\tthis.builderPreview = null;\n\t\tthis.builderHoverKey = null;\n\t\tthis.blendStart = null;\n\t\tif (tool !== 'direct') {\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t}\n\t\tthis.notify();\n\t}\n\n\tsetDefaults(defaults: Partial<VectorDefaults>): void {\n\t\tthis.defaults = { ...this.defaults, ...defaults };\n\t\tthis.notify();\n\t}\n\n\tsetSnap(snap: Partial<VectorSnapOptions>): void {\n\t\tthis.snap = { ...this.snap, ...snap };\n\t\tif (!this.snap.guides || !this.snap.objects) this.guides = null;\n\t\tthis.notify();\n\t}\n\n\t/** Changes how deleting, dragging anchors, the pencil and the eraser behave. */\n\tsetEditing(editing: Partial<VectorPathEditOptions>): void {\n\t\tconst next = { ...this.editing, ...editing };\n\t\tnext.pencilSmoothing = Math.min(1, Math.max(0, Number.isFinite(next.pencilSmoothing) ? next.pencilSmoothing : 0));\n\t\tif (!(next.eraserSize > 0)) next.eraserSize = this.editing.eraserSize;\n\t\tthis.editing = next;\n\t\tthis.notify();\n\t}\n\n\t/** Turns object snapping on or off (the toolbar's snapping toggle). */\n\ttoggleSnapping(on: boolean = !this.snap.objects): void {\n\t\tthis.setSnap({ objects: on });\n\t}\n\n\tprivate gridValue(v: number): number {\n\t\tconst g = this.snap.grid;\n\t\treturn g > 0 ? Math.round(v / g) * g : v;\n\t}\n\n\tprivate snapPoint(p: Vec2): Vec2 {\n\t\treturn { x: this.gridValue(p.x), y: this.gridValue(p.y) };\n\t}\n\n\t/** The pull distance in document units. */\n\tprivate snapTolerance(): number {\n\t\treturn this.snap.threshold / this.viewport.zoom;\n\t}\n\n\tprivate setGuides(guides: VectorSnapGuides | null) {\n\t\tthis.guides = guides && this.snap.guides && (guides.lines.length || guides.labels.length) ? guides : null;\n\t}\n\n\t/**\n\t * Where a drawn or dragged point `p` goes: onto the smart guide `targets` (gathered by\n\t * `gather` when missing), else onto the grid, kept to `leave`'s constraint. Cmd / Ctrl\n\t * bypasses snapping.\n\t */\n\tprivate snapDrawn(p: Vec2, leave: VectorSnapLeave | null, input: VectorModifiers, targets: () => VectorSnapTargets): Vec2 {\n\t\tthis.snappedToObject = false;\n\t\tif (input.mod) {\n\t\t\tthis.setGuides(null);\n\t\t\treturn constrainToLeave(leave, p);\n\t\t}\n\t\tif (this.snap.objects) {\n\t\t\tconst withAngles = leave ? { ...leave, angles: this.snap.angles } : null;\n\t\t\tconst res = targets().snapFrom(p, withAngles, this.snapTolerance());\n\t\t\tif (res.kind) {\n\t\t\t\tthis.snappedToObject = true;\n\t\t\t\tthis.setGuides(res);\n\t\t\t\t// An axis lined up with nothing still goes to the grid.\n\t\t\t\treturn leave?.constrain ? res.point : { x: res.x ? res.point.x : this.gridValue(res.point.x), y: res.y ? res.point.y : this.gridValue(res.point.y) };\n\t\t\t}\n\t\t}\n\t\tthis.setGuides(null);\n\t\treturn constrainToLeave(leave, this.snapPoint(p));\n\t}\n\n\t/** Drawing targets for the pen and shape tools, reused while the document stays the same. */\n\tprivate drawingTargets(exclude: string | null): VectorSnapTargets {\n\t\tconst key = exclude ?? '';\n\t\tconst cached = this.hoverTargets;\n\t\tif (cached && cached.doc === this.doc && cached.exclude === key) return cached.targets;\n\t\tconst targets = VectorSnapTargets.forDrawing(this.doc, exclude ? [exclude] : []);\n\t\tthis.hoverTargets = { doc: this.doc, exclude: key, targets };\n\t\treturn targets;\n\t}\n\n\t/** Where the pointer at `p` would place a point with the pen or a shape tool (and the guides showing why). */\n\tprivate hoverSnap(p: Vec2, input: VectorModifiers): Vec2 {\n\t\tif (this.tool === 'pen') {\n\t\t\tconst sp = this.pen ? (this.getNode(this.pen.nodeId) as VectorPathNode | undefined)?.subpaths[this.pen.subpath] : undefined;\n\t\t\tif (this.pen && sp && this.hover?.anchor) {\n\t\t\t\tthis.setGuides(null);\n\t\t\t\treturn p;\n\t\t\t}\n\t\t\tconst last = this.pen && sp ? getAnchorWorld(this.doc, { nodeId: this.pen.nodeId, subpath: this.pen.subpath, index: sp.anchors.length - 1 }) : undefined;\n\t\t\tconst leave = last ? { at: { x: last.x, y: last.y }, constrain: input.shift ? ('angle' as const) : null } : null;\n\t\t\treturn this.snapDrawn(p, leave, input, () => this.drawingTargets(this.pen?.nodeId ?? null));\n\t\t}\n\t\tif (SHAPE_TOOLS.has(this.tool)) return this.snapDrawn(p, null, input, () => this.drawingTargets(null));\n\t\tthis.setGuides(null);\n\t\treturn p;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Document\n\t// -------------------------------------------------------------------------\n\n\t/** Replaces the document. Undoable unless `{ history: false }` (then history is cleared). */\n\tsetDocument(doc: VectorDocument, options: { history?: boolean; label?: string } = {}): void {\n\t\tthis.cancelDrag();\n\t\tconst next = cloneVectorDocument(doc);\n\t\tif (options.history === false) {\n\t\t\tthis.doc = next;\n\t\t\tthis.selection = [];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t\tthis.pen = null;\n\t\t\tthis.history.clear();\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tthis.change(options.label ?? 'Replace Document', () => {\n\t\t\tthis.doc = next;\n\t\t\tthis.selection = [];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t\tthis.pen = null;\n\t\t});\n\t}\n\n\t/** Changes the artboard size or background. */\n\tsetArtboard(patch: Partial<Pick<VectorDocument, 'width' | 'height' | 'background'>>): void {\n\t\tthis.change('Change Artboard', () => {\n\t\t\tthis.doc = { ...this.doc, ...patch };\n\t\t});\n\t}\n\n\t/** Replaces the document with parsed SVG markup (one undo step). */\n\tloadSvg(svg: string, options: { history?: boolean } = {}): VectorActionResult {\n\t\ttry {\n\t\t\tconst doc = parseVectorSvg(svg, { createId: () => this.createId() });\n\t\t\tthis.setDocument(doc, { history: options.history, label: 'Import SVG' });\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\t/** Adds the nodes of SVG markup on top of the document, selected. */\n\timportSvg(svg: string): VectorActionResult {\n\t\ttry {\n\t\t\tconst parsed = parseVectorSvg(svg);\n\t\t\tconst nodes = parsed.nodes.map((n) => this.freshIds(n));\n\t\t\tif (!nodes.length) return { ok: false, message: 'The SVG has no shapes the editor can read.' };\n\t\t\tthis.change('Import SVG', () => {\n\t\t\t\tthis.setDoc([...this.doc.nodes, ...nodes]);\n\t\t\t\tthis.selection = nodes.map((n) => n.id);\n\t\t\t\tthis.anchors = [];\n\t\t\t});\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\ttoSvg(options?: VectorSvgExportOptions): string {\n\t\treturn vectorDocumentToSvg(this.doc, options);\n\t}\n\n\ttoJSON(): VectorDocument {\n\t\treturn cloneVectorDocument(this.doc);\n\t}\n\n\t/** Adds a node (ids are kept unless taken). Returns its id. */\n\taddNode(node: VectorNode, options: AddVectorNodeOptions = {}): string {\n\t\tconst taken = (() => {\n\t\t\tlet clash = false;\n\t\t\twalkVectorNodes([node], (n) => {\n\t\t\t\tif (this.getNode(n.id)) clash = true;\n\t\t\t});\n\t\t\treturn clash;\n\t\t})();\n\t\tconst next = taken ? this.freshIds(node) : cloneVectorNode(node);\n\t\tthis.change(options.label ?? `Add ${next.type === 'group' ? 'Group' : (next.name ?? 'Path')}`, () => {\n\t\t\tconst insert = (list: VectorNode[]) => {\n\t\t\t\tconst copy = list.slice();\n\t\t\t\tcopy.splice(options.index ?? copy.length, 0, next);\n\t\t\t\treturn copy;\n\t\t\t};\n\t\t\tif (options.parentId) {\n\t\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === options.parentId && n.type === 'group' ? { ...n, children: insert(n.children) } : n)));\n\t\t\t} else this.setDoc(insert(this.doc.nodes));\n\t\t\tif (options.select !== false) {\n\t\t\t\tthis.selection = [next.id];\n\t\t\t\tthis.anchors = [];\n\t\t\t}\n\t\t});\n\t\treturn next.id;\n\t}\n\n\t/** Builds a path node for a shape with the current defaults (not added). */\n\tcreateShapeNode(input: VectorShapeInput): VectorPathNode {\n\t\tconst b = { x: input.x, y: input.y, width: input.width, height: input.height };\n\t\tconst d = this.defaults;\n\t\tlet subpath: VectorSubpath;\n\t\tswitch (input.kind) {\n\t\t\tcase 'rect':\n\t\t\t\tsubpath = rectSubpath(b);\n\t\t\t\tbreak;\n\t\t\tcase 'ellipse':\n\t\t\t\tsubpath = ellipseSubpath(b);\n\t\t\t\tbreak;\n\t\t\tcase 'polygon':\n\t\t\t\tsubpath = polygonSubpath(b, input.sides ?? d.polygonSides);\n\t\t\t\tbreak;\n\t\t\tcase 'star':\n\t\t\t\tsubpath = starSubpath(b, input.points ?? d.starPoints, input.innerRatio ?? d.starInnerRatio);\n\t\t\t\tbreak;\n\t\t\tcase 'line':\n\t\t\t\tsubpath = lineSubpath({ x: b.x, y: b.y }, { x: b.x + b.width, y: b.y + b.height });\n\t\t\t\tbreak;\n\t\t}\n\t\tconst radius = input.cornerRadius ?? d.cornerRadius;\n\t\tconst kind = input.cornerKind ?? d.cornerKind;\n\t\t// Live corners: the shape keeps its sharp anchors, so the radius stays editable.\n\t\tif ((input.kind === 'rect' || input.kind === 'polygon' || input.kind === 'star') && radius > 0) subpath = setSubpathCorners(subpath, radius, kind);\n\t\tconst names = { rect: 'Rectangle', ellipse: 'Ellipse', polygon: 'Polygon', star: 'Star', line: 'Line' };\n\t\tconst style = this.styleFor(input.kind === 'line');\n\t\tconst own: VectorStyle = {};\n\t\tfor (const key of VECTOR_STYLE_KEYS) {\n\t\t\tif (input[key] !== undefined) (own as any)[key] = input[key];\n\t\t}\n\t\treturn { id: this.newId(), type: 'path', name: input.name ?? names[input.kind], ...style, ...own, subpaths: [subpath] };\n\t}\n\n\t/** Adds a shape drawn with the current defaults. Returns its id. */\n\taddShape(input: VectorShapeInput, options: AddVectorNodeOptions = {}): string {\n\t\tconst node = this.createShapeNode(input);\n\t\treturn this.addNode(node, { label: `Add ${node.name}`, ...options });\n\t}\n\n\t/** Adds a path from SVG path data. Returns its id. */\n\taddPath(d: string, style: VectorStyle & { name?: string } = {}, options: AddVectorNodeOptions = {}): string {\n\t\tconst subpaths = bezierToSubpaths(d);\n\t\tconst node: VectorPathNode = { id: this.newId(), type: 'path', name: style.name ?? 'Path', ...this.styleFor(false), ...style, subpaths };\n\t\treturn this.addNode(node, { label: 'Add Path', ...options });\n\t}\n\n\tprivate styleFor(open: boolean): VectorStyle {\n\t\tconst d = this.defaults;\n\t\tconst out: VectorStyle = { fill: open ? null : (d.fill ?? null), stroke: d.stroke ?? null, strokeWidth: d.strokeWidth ?? 1 };\n\t\tif (d.strokeLinecap) out.strokeLinecap = d.strokeLinecap;\n\t\tif (d.strokeLinejoin) out.strokeLinejoin = d.strokeLinejoin;\n\t\tif (d.strokeDasharray) out.strokeDasharray = d.strokeDasharray;\n\t\tif (d.fillRule) out.fillRule = d.fillRule;\n\t\tif (d.strokeAlign && d.strokeAlign !== 'center') out.strokeAlign = d.strokeAlign;\n\t\tfor (const key of ['startArrow', 'endArrow', 'arrowAlign', 'startArrowScale', 'endArrowScale'] as const) if (d[key]) (out as any)[key] = d[key];\n\t\tif (d.strokeWidthProfile?.length) out.strokeWidthProfile = d.strokeWidthProfile.map((p) => ({ ...p }));\n\t\treturn out;\n\t}\n\n\t/** Merges `patch` into a node (paths take style and geometry; groups name / visibility / opacity). */\n\tupdateNode(id: string, patch: Partial<VectorPathNode> | Partial<VectorGroupNode>, options: { label?: string } = {}): VectorActionResult {\n\t\tconst node = this.getNode(id);\n\t\tif (!node) return { ok: false, message: `There is no node \"${id}\".` };\n\t\tconst { id: _id, type: _type, ...rest } = patch as any;\n\t\tthis.change(options.label ?? 'Edit Node', () => this.replaceNode(id, { ...node, ...rest } as VectorNode));\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies style (and opacity) to the selected (or given) nodes; groups pass it to every path inside. */\n\tsetStyle(style: VectorStyle & { opacity?: number }, ids: readonly string[] = this.selection, options: { label?: string } = {}): VectorActionResult {\n\t\tconst targets = new Set<string>();\n\t\tfor (const id of ids) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (!node) return { ok: false, message: `There is no node \"${id}\".` };\n\t\t\tfor (const p of collectPathNodes(node)) targets.add(p.id);\n\t\t}\n\t\tif (!targets.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(options.label ?? 'Change Style', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (targets.has(n.id) ? withStyle(n as VectorPathNode, style) : n)));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Sets the variable-width profile of the selected (or given) paths: a preset id\n\t * (`uniform` removes the profile), points, or a parametric taper / wave. Returns an error for\n\t * an unknown preset.\n\t */\n\tsetWidthProfile(\n\t\tprofile: VectorWidthPreset | readonly VectorWidthPoint[] | { taper?: VectorTaperOptions; wave?: VectorWaveOptions } | null,\n\t\toptions: { ids?: readonly string[] } = {}\n\t): VectorActionResult {\n\t\tlet points: VectorWidthPoint[];\n\t\tif (profile === null) points = [];\n\t\telse if (typeof profile === 'string') {\n\t\t\tconst preset = widthProfilePreset(profile);\n\t\t\tif (!preset) return { ok: false, message: `There is no width profile \"${profile}\".` };\n\t\t\tpoints = preset;\n\t\t} else if (Array.isArray(profile)) points = sanitizeWidthProfile(profile);\n\t\telse {\n\t\t\tconst p = profile as { taper?: VectorTaperOptions; wave?: VectorWaveOptions };\n\t\t\tpoints = p.taper || p.wave ? generateWidthProfile(p) : [];\n\t\t}\n\t\tthis.widthPoints = [];\n\t\tthis.widthEdit = null;\n\t\treturn this.setStyle({ strokeWidthProfile: points.length ? points : null }, options.ids ?? this.selection, { label: points.length ? 'Width Profile' : 'Uniform Width' });\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Gradients\n\t// -------------------------------------------------------------------------\n\n\t/** Which paint (fill or stroke) the gradient tool and editor work on. */\n\tsetGradientTarget(target: VectorGradientTarget): void {\n\t\tif (target === this.gradientEdit.target) return;\n\t\tthis.gradientEdit = { target, stop: null };\n\t\tthis.notify();\n\t}\n\n\t/** Selects a stop of the gradient being edited (index into its sorted stops), or none. */\n\tselectGradientStop(index: number | null): void {\n\t\tif (index === this.gradientEdit.stop) return;\n\t\tthis.gradientEdit = { ...this.gradientEdit, stop: index };\n\t\tthis.notify();\n\t}\n\n\t/** The gradient tool's annotator for the selection (screen pixels), or null when its paint is not a gradient. */\n\tgetGradientAnnotator(): VectorGradientAnnotator | null {\n\t\treturn getVectorGradientAnnotator(this.doc, this.selection, this.viewport, this.gradientEdit.target);\n\t}\n\n\t/** Unlocked paths of `ids` (default: the selection). */\n\tprivate gradientPaths(ids: readonly string[] = this.selection): VectorPathNode[] {\n\t\tconst out = new Map<string, VectorPathNode>();\n\t\tfor (const id of ids) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) out.set(p.id, p);\n\t\t}\n\t\treturn [...out.values()];\n\t}\n\n\t/**\n\t * Edits the gradient of the `target` paint (default: the editor's) of the selected (or given)\n\t * paths with `patch`: a colour or no paint becomes a gradient (`patch.type`, default linear,\n\t * from the colour to white). Consecutive edits with the same `merge` key are one undo step.\n\t */\n\tsetGradient(patch: VectorGradientPatch, options: { ids?: readonly string[]; target?: VectorGradientTarget; label?: string; merge?: string } = {}): VectorActionResult {\n\t\tconst target = options.target ?? this.gradientEdit.target;\n\t\tconst paths = this.gradientPaths(options.ids ?? this.selection);\n\t\tif (!paths.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst next = new Map<string, VectorPathNode>();\n\t\tfor (const path of paths) {\n\t\t\tconst paint = path[target];\n\t\t\tconst base = isVectorGradient(paint) ? paint : defaultVectorGradient(patch.type ?? 'linear', paint);\n\t\t\tconst g = applyVectorGradientPatch(base, patch);\n\t\t\tif (!g) return { ok: false, message: 'That is not a valid gradient: it needs at least one stop with an offset and a colour.' };\n\t\t\tnext.set(path.id, { ...path, [target]: g });\n\t\t}\n\t\tthis.change(options.label ?? 'Gradient', () => this.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n)), options.merge);\n\t\tconst stops = (next.values().next().value?.[target] as { stops: unknown[] } | undefined)?.stops.length ?? 0;\n\t\tif (this.gradientEdit.stop !== null && this.gradientEdit.stop >= stops) this.gradientEdit = { ...this.gradientEdit, stop: null };\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies `fn` to every target gradient of the selection (paths whose paint is not a gradient are skipped). */\n\tprivate editGradients(label: string, fn: (stops: VectorGradient['stops']) => VectorGradient['stops'] | null, merge?: string): VectorActionResult {\n\t\tconst target = this.gradientEdit.target;\n\t\tconst paths = this.gradientPaths().filter((p) => isVectorGradient(p[target]));\n\t\tif (!paths.length) return { ok: false, message: 'The selection has no gradient.' };\n\t\tconst next = new Map<string, VectorPathNode>();\n\t\tfor (const path of paths) {\n\t\t\tconst g = path[target] as VectorGradient;\n\t\t\tconst stops = fn(sortedVectorGradientStops(g));\n\t\t\tif (!stops) return { ok: false, message: 'A gradient keeps at least two stops.' };\n\t\t\tnext.set(path.id, { ...path, [target]: { ...g, stops } });\n\t\t}\n\t\tthis.change(label, () => this.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n)), merge);\n\t\treturn { ok: true };\n\t}\n\n\t/** Changes stop `index` (colour, opacity, offset or midpoint) of the selection's gradients; selects it. */\n\tsetGradientStop(index: number, patch: { color?: string; opacity?: number; offset?: number; midpoint?: number }, options: { merge?: string } = {}): VectorActionResult {\n\t\tlet moved = index;\n\t\tconst result = this.editGradients(\n\t\t\t'Gradient Stop',\n\t\t\t(stops) => {\n\t\t\t\tif (!stops[index]) return stops;\n\t\t\t\tlet next = stops.map((s, i) => {\n\t\t\t\t\tif (i !== index) return s;\n\t\t\t\t\tconst out = { ...s };\n\t\t\t\t\tif (patch.color !== undefined) out.color = patch.color;\n\t\t\t\t\tif (patch.opacity !== undefined && Number.isFinite(patch.opacity)) {\n\t\t\t\t\t\tconst o = Math.min(1, Math.max(0, patch.opacity));\n\t\t\t\t\t\tif (o < 1) out.opacity = o;\n\t\t\t\t\t\telse delete out.opacity;\n\t\t\t\t\t}\n\t\t\t\t\tif (patch.midpoint !== undefined && Number.isFinite(patch.midpoint)) {\n\t\t\t\t\t\tconst m = Math.min(0.95, Math.max(0.05, patch.midpoint));\n\t\t\t\t\t\tif (Math.abs(m - 0.5) > 1e-3) out.midpoint = m;\n\t\t\t\t\t\telse delete out.midpoint;\n\t\t\t\t\t}\n\t\t\t\t\treturn out;\n\t\t\t\t});\n\t\t\t\tif (patch.offset !== undefined && Number.isFinite(patch.offset)) ({ stops: next, index: moved } = moveVectorGradientStop(next, index, patch.offset));\n\t\t\t\treturn next;\n\t\t\t},\n\t\t\toptions.merge\n\t\t);\n\t\tif (result.ok) this.selectGradientStop(moved);\n\t\treturn result;\n\t}\n\n\t/** Adds a stop at `offset` (painting what the gradient paints there) to the selection's gradients and selects it. */\n\taddGradientStop(offset: number): VectorActionResult {\n\t\tlet index = 0;\n\t\tconst target = this.gradientEdit.target;\n\t\tconst result = this.editGradients('Add Gradient Stop', (stops) => {\n\t\t\tconst path = this.gradientPaths().find((p) => isVectorGradient(p[target]));\n\t\t\tconst r = insertVectorGradientStop({ ...(path![target] as VectorGradient), stops }, offset);\n\t\t\tindex = r.index;\n\t\t\treturn r.stops;\n\t\t});\n\t\tif (result.ok) this.selectGradientStop(index);\n\t\treturn result;\n\t}\n\n\t/** Removes stop `index` of the selection's gradients (never below two stops). */\n\tremoveGradientStop(index: number): VectorActionResult {\n\t\tconst result = this.editGradients('Delete Gradient Stop', (stops) => removeVectorGradientStop(stops, index));\n\t\tif (result.ok) this.selectGradientStop(null);\n\t\treturn result;\n\t}\n\n\t/** Reverses the selection's gradients (stops and midpoints). */\n\treverseGradient(): VectorActionResult {\n\t\treturn this.setGradient({ reverse: true }, { label: 'Reverse Gradient' });\n\t}\n\n\t/** `doc` with path `id`'s `target` paint replaced. */\n\tprivate withGradient(doc: VectorDocument, id: string, target: VectorGradientTarget, g: VectorGradient): VectorDocument {\n\t\treturn { ...doc, nodes: mapTree(doc.nodes, (n) => (n.id === id ? ({ ...n, [target]: g } as VectorNode) : n)) };\n\t}\n\n\tprivate downGradient(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\tconst a = this.getGradientAnnotator();\n\t\tlet part = a ? hitVectorGradientAnnotator(a, screen) : null;\n\t\tif (a && part) {\n\t\t\t// Alt on a radial gradient's centre grabs its focal point (they sit together until moved).\n\t\t\tif (part.kind === 'handle' && part.handle === 'start' && input.alt && a.gradient.type === 'radial') part = { kind: 'handle', handle: 'focal' };\n\t\t\tif (part.kind === 'stop') this.gradientEdit = { ...this.gradientEdit, stop: part.index };\n\t\t\tthis.drag = { kind: 'gradient', part, nodeId: a.nodeId, targets: [a.nodeId], annotator: a, start: screen, startDoc: p, before, base: this.doc, moved: false, stop: part.kind === 'stop' ? part.index : null };\n\t\t\tthis.interaction = { type: 'gradient', part: part.kind, ...(part.kind === 'handle' ? { handle: part.handle } : {}) };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\t// Elsewhere a drag draws a new vector over the path under the pointer (selecting it) or the selection.\n\t\tconst hit = this.hitPath(p);\n\t\tif (hit && !this.gradientPaths().some((n) => n.id === hit.id)) {\n\t\t\tthis.selection = [hit.id];\n\t\t\tthis.gradientEdit = { ...this.gradientEdit, stop: null };\n\t\t}\n\t\tconst targets = this.gradientPaths().map((n) => n.id);\n\t\tif (!targets.length) {\n\t\t\tif (this.selection.length) this.clearSelection();\n\t\t\treturn;\n\t\t}\n\t\tthis.drag = { kind: 'gradient', part: null, nodeId: null, targets, annotator: null, start: screen, startDoc: p, before, base: this.doc, moved: false, stop: null };\n\t\tthis.interaction = { type: 'gradient', part: 'create' };\n\t\tthis.notify();\n\t}\n\n\tprivate moveGradient(drag: Extract<Drag, { kind: 'gradient' }>, screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tif (!drag.moved && Math.hypot(screen.x - drag.start.x, screen.y - drag.start.y) < 3) return;\n\t\tdrag.moved = true;\n\t\tconst target = this.gradientEdit.target;\n\t\tconst base = drag.base;\n\t\tconst constrained = (from: Vec2, to: Vec2) => {\n\t\t\tif (!input.shift) return to;\n\t\t\tconst ang = Math.round(Math.atan2(to.y - from.y, to.x - from.x) / (Math.PI / 4)) * (Math.PI / 4);\n\t\t\tconst len = Math.hypot(to.x - from.x, to.y - from.y);\n\t\t\treturn { x: from.x + Math.cos(ang) * len, y: from.y + Math.sin(ang) * len };\n\t\t};\n\t\tif (!drag.part) {\n\t\t\tconst end = constrained(drag.startDoc, p);\n\t\t\tlet doc = base;\n\t\t\tfor (const id of drag.targets) {\n\t\t\t\tconst node = findVectorNode(base.nodes, id) as VectorPathNode | undefined;\n\t\t\t\tif (!node) continue;\n\t\t\t\tconst paint = node[target];\n\t\t\t\tconst g = isVectorGradient(paint) ? paint : defaultVectorGradient('linear', paint);\n\t\t\t\tdoc = this.withGradient(doc, id, target, setVectorGradientVector(g, vectorPathLocalBounds(node), this.toLocal(id, drag.startDoc, base), this.toLocal(id, end, base)));\n\t\t\t}\n\t\t\tthis.doc = doc;\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tconst id = drag.nodeId!;\n\t\tconst node = findVectorNode(base.nodes, id) as VectorPathNode;\n\t\tconst g = node[target] as VectorGradient;\n\t\tconst bounds = vectorPathLocalBounds(node);\n\t\tconst local = (q: Vec2) => this.toLocal(id, q, base);\n\t\tconst part = drag.part;\n\t\tlet next: VectorGradient = g;\n\t\tif (part.kind === 'handle') {\n\t\t\tlet to = p;\n\t\t\t// Shift keeps the vector at 45° steps from the start.\n\t\t\tif (part.handle === 'end' || part.handle === 'radius') to = constrained(this.screenToDocument(drag.annotator!.start), p);\n\t\t\tnext = moveVectorGradientHandle(g, bounds, part.handle, local(to), local(drag.startDoc));\n\t\t} else if (part.kind === 'bar') {\n\t\t\tnext = moveVectorGradientHandle(g, bounds, 'start', local(p), local(drag.startDoc));\n\t\t} else {\n\t\t\tconst a = drag.annotator!;\n\t\t\tconst pos = vectorGradientBarPosition(a, screen);\n\t\t\tconst stops = sortedVectorGradientStops(g);\n\t\t\tif (part.kind === 'stop') {\n\t\t\t\tconst off = Math.abs(pos.across - VECTOR_GRADIENT_STOP_GAP) > VECTOR_GRADIENT_OFF_BAR;\n\t\t\t\tconst removed = off ? removeVectorGradientStop(stops, part.index) : null;\n\t\t\t\tif (removed) {\n\t\t\t\t\tnext = { ...g, stops: removed };\n\t\t\t\t\tdrag.stop = null;\n\t\t\t\t} else {\n\t\t\t\t\tconst r = moveVectorGradientStop(stops, part.index, Math.min(1, Math.max(0, pos.offset)));\n\t\t\t\t\tnext = { ...g, stops: r.stops };\n\t\t\t\t\tdrag.stop = r.index;\n\t\t\t\t}\n\t\t\t\tthis.interaction = { type: 'gradient', part: 'stop', ...(removed ? { removing: true } : {}) };\n\t\t\t\tthis.gradientEdit = { ...this.gradientEdit, stop: drag.stop };\n\t\t\t} else {\n\t\t\t\tconst m = vectorGradientMidpointFromPosition(stops, part.index, pos.offset);\n\t\t\t\tif (m !== null) next = { ...g, stops: stops.map((s, i) => (i !== part.index ? s : Math.abs(m - 0.5) < 1e-3 ? (({ midpoint: _m, ...rest }) => rest)(s) : { ...s, midpoint: m })) };\n\t\t\t}\n\t\t}\n\t\tthis.doc = this.withGradient(base, id, target, next);\n\t\tthis.notify(true);\n\t}\n\n\tprivate upGradient(drag: Extract<Drag, { kind: 'gradient' }>) {\n\t\tconst part = drag.part;\n\t\tif (!drag.moved) {\n\t\t\tif (part?.kind === 'bar') {\n\t\t\t\tthis.addGradientStop(part.offset);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst label = !part\n\t\t\t? 'Gradient'\n\t\t\t: part.kind === 'stop'\n\t\t\t\t? drag.stop === null\n\t\t\t\t\t? 'Delete Gradient Stop'\n\t\t\t\t\t: 'Move Gradient Stop'\n\t\t\t\t: part.kind === 'midpoint'\n\t\t\t\t\t? 'Gradient Midpoint'\n\t\t\t\t\t: part.kind === 'bar' || (part.kind === 'handle' && part.handle === 'start')\n\t\t\t\t\t\t? 'Move Gradient'\n\t\t\t\t\t\t: 'Gradient Handle';\n\t\treturn this.commit(label, drag.before);\n\t}\n\n\t/** Removes one width point of a path's profile. */\n\tremoveWidthPoint(ref: Pick<VectorWidthPointRef, 'nodeId' | 'index'>): VectorActionResult {\n\t\treturn this.removeWidthPoints([ref]);\n\t}\n\n\t/** Removes width points (default: the selected ones — the width tool's Delete), as one undo step. */\n\tremoveWidthPoints(refs: readonly Pick<VectorWidthPointRef, 'nodeId' | 'index'>[] = this.widthPoints): VectorActionResult {\n\t\tconst byNode = new Map<string, number[]>();\n\t\tfor (const r of refs) {\n\t\t\tconst node = this.getNode(r.nodeId);\n\t\t\tif (node?.type !== 'path' || !node.strokeWidthProfile?.[r.index]) continue;\n\t\t\tbyNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r.index]);\n\t\t}\n\t\tif (!byNode.size) return { ok: false, message: 'There is no such width point.' };\n\t\tconst count = [...byNode.values()].reduce((n, l) => n + new Set(l).size, 0);\n\t\tthis.widthPoints = [];\n\t\tthis.widthEdit = null;\n\t\tthis.change(count > 1 ? 'Delete Width Points' : 'Delete Width Point', () => {\n\t\t\tfor (const [id, indices] of byNode) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\tconst rest = removeWidthPoints(sanitizeWidthProfile(node.strokeWidthProfile), indices);\n\t\t\t\tthis.replaceNode(id, withStyle(node, { strokeWidthProfile: rest.length ? rest : null }));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Selects width points (width tool); points on other paths than the first are dropped. */\n\tselectWidthPoints(refs: readonly VectorWidthPointRef[]): void {\n\t\tconst first = refs[0]?.nodeId;\n\t\tconst next: VectorWidthPointRef[] = [];\n\t\tfor (const r of refs) {\n\t\t\tif (r.nodeId !== first || next.some((q) => q.index === r.index)) continue;\n\t\t\tconst n = this.getNode(r.nodeId);\n\t\t\tif (n?.type === 'path' && n.strokeWidthProfile?.[r.index]) next.push({ nodeId: r.nodeId, index: r.index, subpath: r.subpath ?? 0 });\n\t\t}\n\t\tthis.widthPoints = next;\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Sets one width point numerically: `index` names an existing point of path `nodeId`, null\n\t * (or left out) adds one at `values.t`. `left` / `right` are side widths in document units\n\t * (how far the stroke reaches on each side of the path), `t` the position along each subpath\n\t * (0–1). A point moved onto another one's `t` makes a step there. Selects the point and\n\t * refreshes an open width-point editor; one undo step. Ported from ArtCraft vectorcraft's\n\t * Width Point Edit dialog (`crates/tools/src/distort/width.rs`, MIT OR Apache-2.0).\n\t */\n\tsetWidthPoint(target: { nodeId: string; index?: number | null }, values: { t?: number; left?: number; right?: number }): VectorActionResult {\n\t\tconst node = this.getNode(target.nodeId);\n\t\tif (node?.type !== 'path') return { ok: false, message: 'There is no such path.' };\n\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\tif (!g || !(g.unit > 0)) return { ok: false, message: 'The path has no visible stroke.' };\n\t\tconst num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);\n\t\tconst t = num(values.t);\n\t\tconst left = num(values.left);\n\t\tconst right = num(values.right);\n\t\tconst scale = (w: number | undefined) => (w === undefined ? undefined : Math.max(0, w) / g.unit);\n\t\tconst profile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\tlet points: VectorWidthPoint[];\n\t\tlet index: number;\n\t\tconst existing = target.index ?? null;\n\t\tif (existing === null) {\n\t\t\tif (t === undefined) return { ok: false, message: 'A new width point needs a position t.' };\n\t\t\tif (profile.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) return { ok: false, message: 'The profile has too many width points.' };\n\t\t\t({ points, index } = insertWidthPoint(profile.length ? profile : null, t, { left: scale(left), right: scale(right) }, { step: true }));\n\t\t} else {\n\t\t\tconst p = profile[existing];\n\t\t\tif (!p) return { ok: false, message: 'There is no such width point.' };\n\t\t\tconst sides = { left: scale(left) ?? p.left, right: scale(right) ?? p.right };\n\t\t\tconst tt = t === undefined ? p.t : Math.min(Math.max(t, 0), 1);\n\t\t\tif (Math.abs(tt - p.t) <= VECTOR_WIDTH_SAME_T) {\n\t\t\t\tpoints = setWidthPoint(profile, existing, sides);\n\t\t\t\tindex = existing;\n\t\t\t} else {\n\t\t\t\t// Free to pass its neighbours: take it out and put it back at its new place.\n\t\t\t\tconst rest = removeWidthPoints(profile, [existing]);\n\t\t\t\tif (rest.length) ({ points, index } = insertWidthPoint(rest, tt, sides, { step: true }));\n\t\t\t\telse {\n\t\t\t\t\tpoints = [{ t: tt, ...sides }];\n\t\t\t\t\tindex = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst subpath = this.widthEdit?.nodeId === node.id ? this.widthEdit.subpath : this.widthPoints.find((r) => r.nodeId === node.id)?.subpath ?? 0;\n\t\tconst edit = this.widthEdit;\n\t\tthis.change('Width Point', () => this.replaceNode(node.id, withStyle(node, { strokeWidthProfile: points })));\n\t\tthis.widthPoints = [{ nodeId: node.id, index, subpath }];\n\t\tif (edit?.nodeId === node.id && (edit.index === existing || existing === null)) this.widthEdit = this.widthEditFor(node.id, subpath, index, null);\n\t\tthis.notify();\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Opens the width-point editor (what a double-click with the width tool does) on a width\n\t * point, or on a spot of a stroke (`t` without `index`: applying it adds a point there).\n\t * Returns false when the path has no visible stroke.\n\t */\n\topenWidthPointEdit(target: { nodeId: string; subpath?: number; index?: number | null; t?: number }): boolean {\n\t\tconst edit = this.widthEditFor(target.nodeId, target.subpath ?? 0, target.index ?? null, target.t ?? null);\n\t\tif (!edit) return false;\n\t\tthis.widthEdit = edit;\n\t\tthis.widthPoints = edit.index === null ? [] : [{ nodeId: edit.nodeId, index: edit.index, subpath: edit.subpath }];\n\t\tthis.notify();\n\t\treturn true;\n\t}\n\n\t/** Closes the width-point editor without changing anything. */\n\tcloseWidthPointEdit(): void {\n\t\tif (!this.widthEdit) return;\n\t\tthis.widthEdit = null;\n\t\tthis.notify();\n\t}\n\n\t/** Applies `values` to the width point being edited (see `setWidthPoint`) and closes the editor. */\n\tcommitWidthPointEdit(values: { t?: number; left?: number; right?: number }): VectorActionResult {\n\t\tconst edit = this.widthEdit;\n\t\tif (!edit) return { ok: false, message: 'No width point is being edited.' };\n\t\tconst r = this.setWidthPoint({ nodeId: edit.nodeId, index: edit.index }, edit.index === null ? { t: edit.t, ...values } : values);\n\t\tif (r.ok) this.closeWidthPointEdit();\n\t\treturn r;\n\t}\n\n\t/** The editor's view of point `index` (or of the stroke at `t` when index is null) of `nodeId`. */\n\tprivate widthEditFor(nodeId: string, subpath: number, index: number | null, t: number | null): VectorWidthPointEdit | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path') return null;\n\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\tif (!g) return null;\n\t\tconst profile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\tconst p = index === null ? null : profile[index];\n\t\tif (index !== null && !p) return null;\n\t\tconst tt = p ? p.t : Math.min(Math.max(t ?? 0, 0), 1);\n\t\tconst sides = p ?? widthProfileAt(profile.length ? profile : null, tt);\n\t\tconst sp = Math.min(Math.max(0, subpath), Math.max(0, node.subpaths.length - 1));\n\t\tconst at = strokePositionPoint(g.line, sp, tt);\n\t\tconst round = (v: number) => Math.round(v * 1e6) / 1e6;\n\t\tconst q = at ? applyMatrix(this.worldOf(nodeId), { x: at.point[0], y: at.point[1] }) : { x: 0, y: 0 };\n\t\tconst point = { x: round(q.x), y: round(q.y) };\n\t\treturn { nodeId, subpath: sp, index, t: round(tt), left: round(sides.left * g.unit), right: round(sides.right * g.unit), point };\n\t}\n\n\t/**\n\t * Sets the live corner radius (and optionally the kind) of anchors: `refs`, else the selected\n\t * anchors (direct tool), else every anchor of the `ids` / selected paths. Radius 0 makes the\n\t * corners sharp again. Corners shrink to fit when drawn, so any radius is accepted.\n\t */\n\tsetCornerRadius(radius: number, options: { kind?: VectorCornerKind; refs?: readonly VectorAnchorRef[]; ids?: readonly string[] } = {}): VectorActionResult {\n\t\tif (!Number.isFinite(radius) || radius < 0) return { ok: false, message: 'The radius must be a number of at least 0.' };\n\t\tconst refs = this.cornerTargets(options);\n\t\tif (!refs.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(radius > 0 ? 'Corner Radius' : 'Sharpen Corners', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, refs, (a) => setAnchorCorner(a, radius, options.kind));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Sets the live corner kind of the same anchors as `setCornerRadius`, keeping their radii. */\n\tsetCornerKind(kind: VectorCornerKind, options: { refs?: readonly VectorAnchorRef[]; ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst refs = this.cornerTargets(options);\n\t\tif (!refs.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change('Corner Kind', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, refs, (a) => setAnchorCorner(a, a.corner?.radius ?? 0, kind));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Anchors a corner change applies to (see `setCornerRadius`). */\n\tprivate cornerTargets(options: { refs?: readonly VectorAnchorRef[]; ids?: readonly string[] }): VectorAnchorRef[] {\n\t\tif (options.refs) return options.refs.filter((r) => getAnchor(this.doc, r));\n\t\tif (!options.ids && this.tool === 'direct' && this.anchors.length) return this.anchors.slice();\n\t\tconst out: VectorAnchorRef[] = [];\n\t\tfor (const id of options.ids ?? this.selection) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (!node) continue;\n\t\t\tfor (const p of collectPathNodes(node)) {\n\t\t\t\tif (p.locked) continue;\n\t\t\t\tp.subpaths.forEach((sp, s) => sp.anchors.forEach((_, i) => out.push({ nodeId: p.id, subpath: s, index: i })));\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * Outline Stroke: replaces each selected (or given) path's stroke with a filled path of the\n\t * area it paints (alignment, joins, caps, dashes and arrowheads included), placed above a copy\n\t * of the path that keeps the fill (left out when there is none). Returns the new paths' ids.\n\t */\n\toutlineStroke(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst paths: VectorPathNode[] = [];\n\t\tfor (const id of roots) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node) for (const p of collectPathNodes(node)) if (!p.locked && hasPaint(p.stroke) && (p.strokeWidth ?? 1) > 0) paths.push(p);\n\t\t}\n\t\tif (!paths.length) return [];\n\t\tconst created: string[] = [];\n\t\tconst replace = new Map<string, VectorNode[]>();\n\t\tfor (const p of paths) {\n\t\t\t// In the node's own space: the new paths keep its transform.\n\t\t\t// As drawn: path effects applied (the outline itself carries none).\n\t\t\tconst outline = bezierToSubpaths(vectorStrokeOutlinePath(vectorAppearanceOutline(p), p));\n\t\t\tif (!outline.length) continue;\n\t\t\tconst {\n\t\t\t\tstroke,\n\t\t\t\tstrokeWidth: _w,\n\t\t\t\tstrokeLinecap: _c,\n\t\t\t\tstrokeLinejoin: _j,\n\t\t\t\tstrokeDasharray: _d,\n\t\t\t\tstrokeAlign: _a,\n\t\t\t\tstartArrow: _s,\n\t\t\t\tendArrow: _e,\n\t\t\t\tarrowAlign: _al,\n\t\t\t\tstartArrowScale: _ss,\n\t\t\t\tendArrowScale: _es,\n\t\t\t\tstrokeWidthProfile: _wp,\n\t\t\t\teffects,\n\t\t\t\t...rest\n\t\t\t} = cloneVectorNode(p);\n\t\t\tconst id = this.newId();\n\t\t\tconst strokeNode: VectorPathNode = { ...rest, id, name: `${p.name ?? 'Path'} Stroke`, subpaths: outline, fill: stroke ?? null, stroke: null, fillRule: 'nonzero' };\n\t\t\tconst list: VectorNode[] = hasPaint(p.fill) ? [{ ...rest, ...(effects ? { effects } : {}), stroke: null }, strokeNode] : [strokeNode];\n\t\t\tcreated.push(id);\n\t\t\treplace.set(p.id, list);\n\t\t}\n\t\tif (!created.length) return [];\n\t\tthis.change('Outline Stroke', () => {\n\t\t\tlet nodes = this.doc.nodes;\n\t\t\tfor (const [id, list] of replace) nodes = spliceTree(nodes, id, list);\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn created;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Path effects\n\t// -------------------------------------------------------------------------\n\n\t/** Selected (or given) nodes that can carry effects: the roots of the selection. */\n\tprivate effectTargets(ids?: readonly string[]): VectorNode[] {\n\t\treturn (ids ?? this.selectedRoots()).map((id) => this.getNode(id)).filter((n): n is VectorNode => !!n && !n.blendStep);\n\t}\n\n\t/**\n\t * Adds an effect of `type` to the selected (or given) nodes, at the bottom of each stack (or\n\t * at `index`), with default parameters merged with `params`. A repeater's copies start one\n\t * shape width apart. One undo step; returns the new effect ids (one per node, in order).\n\t */\n\taddEffect(type: VectorEffectType, options: { ids?: readonly string[]; params?: Record<string, unknown>; index?: number } = {}): string[] {\n\t\tconst targets = this.effectTargets(options.ids);\n\t\tif (!targets.length || !createVectorEffect(type, '')) return [];\n\t\tconst created: string[] = [];\n\t\tconst next = new Map<string, VectorNode>();\n\t\tfor (const node of targets) {\n\t\t\tconst list = node.effects ?? [];\n\t\t\tlet k = list.length + 1;\n\t\t\twhile (list.some((e) => e.id === `fx${k}`)) k++;\n\t\t\tconst params: Record<string, unknown> = { ...(options.params ?? {}) };\n\t\t\tif (type === 'repeater' && params.position === undefined) {\n\t\t\t\tconst b = bezierPathBounds(vectorAppearanceOutline(node));\n\t\t\t\tif (b && b.maxX - b.minX > 0) params.position = { x: Math.round((b.maxX - b.minX) * 1.25 * 100) / 100, y: 0 };\n\t\t\t}\n\t\t\tconst effect = createVectorEffect(type, `fx${k}`, params)!;\n\t\t\tconst at = options.index === undefined ? list.length : Math.min(list.length, Math.max(0, Math.round(options.index)));\n\t\t\tnext.set(node.id, { ...node, effects: [...list.slice(0, at), effect, ...list.slice(at)] } as VectorNode);\n\t\t\tcreated.push(effect.id);\n\t\t}\n\t\tthis.change(`Add ${VECTOR_EFFECT_LABELS[type]}`, () => this.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n)));\n\t\treturn created;\n\t}\n\n\tprivate editEffects(nodeId: string, label: string, fn: (effects: VectorEffect[]) => VectorEffect[] | string, merge?: string): VectorActionResult {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (!node) return { ok: false, message: `There is no node \"${nodeId}\".` };\n\t\tconst result = fn(node.effects ?? []);\n\t\tif (typeof result === 'string') return { ok: false, message: result };\n\t\tthis.change(label, () => this.replaceNode(nodeId, (result.length ? { ...node, effects: result } : (({ effects: _e, ...rest }) => rest)(node)) as VectorNode), merge);\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Turns an effect on or off and changes its parameters (unknown or invalid values are\n\t * ignored). With `merge` (true, or a key of your own), consecutive updates of the same effect\n\t * fold into one undo step, as a slider drag should; call `endMergedEdit` when it ends.\n\t */\n\tupdateEffect(nodeId: string, effectId: string, patch: { enabled?: boolean; params?: Record<string, unknown> }, options: { merge?: boolean | string } = {}): VectorActionResult {\n\t\tconst merge = options.merge === true ? `effect:${nodeId}:${effectId}` : options.merge || undefined;\n\t\tconst node = this.getNode(nodeId);\n\t\tconst current = node?.effects?.find((e) => e.id === effectId);\n\t\tconst label = current ? VECTOR_EFFECT_LABELS[current.type] ?? 'Effect' : 'Effect';\n\t\treturn this.editEffects(\n\t\t\tnodeId,\n\t\t\t`Edit ${label}`,\n\t\t\t(list) => {\n\t\t\t\tconst i = list.findIndex((e) => e.id === effectId);\n\t\t\t\tif (i < 0) return `Node \"${nodeId}\" has no effect \"${effectId}\".`;\n\t\t\t\tconst e = list[i];\n\t\t\t\tconst raw = patch.params && e.type === 'envelope' && node ? this.envelopeParams(node, e, patch.params) : patch.params;\n\t\t\t\tconst params = raw ? normalizeVectorEffectParams(e.type, raw, e.params as never) : e.params;\n\t\t\t\tconst next = { ...e, params, ...(patch.enabled !== undefined ? { enabled: patch.enabled } : {}) } as VectorEffect;\n\t\t\t\tif (next.enabled !== false) delete (next as { enabled?: boolean }).enabled;\n\t\t\t\treturn list.map((x, j) => (j === i ? next : x));\n\t\t\t},\n\t\t\tmerge\n\t\t);\n\t}\n\n\t/** Removes an effect from a node's stack. */\n\tremoveEffect(nodeId: string, effectId: string): VectorActionResult {\n\t\treturn this.editEffects(nodeId, 'Remove Effect', (list) => (list.some((e) => e.id === effectId) ? list.filter((e) => e.id !== effectId) : `Node \"${nodeId}\" has no effect \"${effectId}\".`));\n\t}\n\n\t/** Moves an effect to position `index` of its stack (0 is applied first). */\n\tmoveEffect(nodeId: string, effectId: string, index: number): VectorActionResult {\n\t\treturn this.editEffects(nodeId, 'Reorder Effects', (list) => {\n\t\t\tconst i = list.findIndex((e) => e.id === effectId);\n\t\t\tif (i < 0) return `Node \"${nodeId}\" has no effect \"${effectId}\".`;\n\t\t\tconst to = Math.min(list.length - 1, Math.max(0, Math.round(index)));\n\t\t\tconst out = list.slice();\n\t\t\tconst [e] = out.splice(i, 1);\n\t\t\tout.splice(to, 0, e);\n\t\t\treturn out;\n\t\t});\n\t}\n\n\t/**\n\t * Expand Appearance: bakes the path effects and live booleans of the selected (or given)\n\t * nodes, and of everything inside them, into plain paths. A node keeps its id (a group when\n\t * it draws as several shapes); the shapes it made get new ids. Returns the ids of the expanded\n\t * nodes (empty when none was live).\n\t */\n\texpandAppearance(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst roots = (options.ids ?? this.selectedRoots()).map((id) => this.getNode(id)).filter((n): n is VectorNode => !!n && hasVectorAppearance(n));\n\t\tif (!roots.length) return [];\n\t\tconst fresh = (n: VectorNode): VectorNode => {\n\t\t\tconst id = n.id.includes('~fx') ? this.newId() : n.id;\n\t\t\treturn n.type === 'group' ? { ...n, id, children: n.children.map(fresh) } : { ...n, id };\n\t\t};\n\t\tconst bake = (n: VectorNode): VectorNode => {\n\t\t\tif (!hasVectorAppearance(n)) return n;\n\t\t\tif (!hasOwnVectorAppearance(n)) return { ...(n as VectorGroupNode), children: (n as VectorGroupNode).children.map(bake) };\n\t\t\tlet e = expandVectorAppearance(n);\n\t\t\t// A live group that draws as one shape becomes that path, in the group's place.\n\t\t\tif (e.type === 'group' && e.children.length === 1 && e.children[0].type === 'path') {\n\t\t\t\tconst { id: _id, opacity, name, ...child } = e.children[0];\n\t\t\t\tconst k = (e.opacity ?? 1) * (opacity ?? 1);\n\t\t\t\te = { ...child, id: e.id, name: e.name ?? name, ...placementOf(e), ...(k < 1 ? { opacity: k } : {}) } as VectorPathNode;\n\t\t\t}\n\t\t\treturn fresh(e);\n\t\t};\n\t\tconst next = new Map(roots.map((n) => [n.id, bake(n)]));\n\t\tthis.change('Expand Appearance', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n));\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn roots.map((n) => n.id);\n\t}\n\n\trename(id: string, name: string): VectorActionResult {\n\t\treturn this.updateNode(id, { name }, { label: 'Rename' });\n\t}\n\n\tsetVisible(id: string, visible: boolean): VectorActionResult {\n\t\treturn this.updateNode(id, { visible }, { label: visible ? 'Show' : 'Hide' });\n\t}\n\n\tsetLocked(id: string, locked: boolean): VectorActionResult {\n\t\tconst result = this.updateNode(id, { locked }, { label: locked ? 'Lock' : 'Unlock' });\n\t\tif (locked && result.ok && this.selection.includes(id)) {\n\t\t\tthis.selection = this.selection.filter((s) => s !== id);\n\t\t\tthis.notify();\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Removes nodes by id. */\n\tremoveNodes(ids: readonly string[], options: { label?: string } = {}): VectorActionResult {\n\t\tconst drop = new Set(ids.filter((id) => this.getNode(id)));\n\t\tif (!drop.size) return { ok: false, message: 'Nothing to delete.' };\n\t\tthis.change(options.label ?? 'Delete', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = this.selection.filter((id) => !drop.has(id) && this.getNode(id));\n\t\t\tthis.anchors = this.anchors.filter((r) => getAnchor(this.doc, r));\n\t\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Selection\n\t// -------------------------------------------------------------------------\n\n\tselect(ids: readonly string[], options: { add?: boolean; toggle?: boolean } = {}): void {\n\t\tconst valid = ids.filter((id) => this.getNode(id));\n\t\tlet next: string[];\n\t\tif (options.toggle) {\n\t\t\tconst set = new Set(this.selection);\n\t\t\tfor (const id of valid) set.has(id) ? set.delete(id) : set.add(id);\n\t\t\tnext = [...set];\n\t\t} else next = options.add ? [...new Set([...this.selection, ...valid])] : valid;\n\t\tthis.selection = next;\n\t\tif (!options.add && !options.toggle) this.anchors = this.anchors.filter((r) => next.includes(r.nodeId));\n\t\tthis.notify();\n\t}\n\n\tselectAll(): void {\n\t\tif (this.tool === 'direct' && this.editingId) {\n\t\t\tthis.anchors = getVisibleAnchors(this.view());\n\t\t} else {\n\t\t\tthis.selection = this.doc.nodes.filter((n) => !n.locked && n.visible !== false).map((n) => n.id);\n\t\t}\n\t\tthis.notify();\n\t}\n\n\tclearSelection(): void {\n\t\tif (!this.selection.length && !this.anchors.length && !this.editingId) return;\n\t\tthis.selection = [];\n\t\tthis.anchors = [];\n\t\tthis.editingId = null;\n\t\tthis.notify();\n\t}\n\n\tselectAnchors(refs: readonly VectorAnchorRef[], options: { add?: boolean } = {}): void {\n\t\tconst valid = refs.filter((r) => getAnchor(this.doc, r));\n\t\tthis.anchors = options.add ? [...this.anchors, ...valid.filter((r) => !this.anchors.some((a) => sameRef(a, r)))] : valid;\n\t\tif (valid.length && !this.editingId) this.editingId = valid[0].nodeId;\n\t\tthis.notify();\n\t}\n\n\t/** Top-level ids of the selection (members of selected groups are covered by the group). */\n\tprivate selectedRoots(): string[] {\n\t\treturn this.selection.filter((id) => {\n\t\t\tlet covered = false;\n\t\t\tconst loc = locateVectorNode(this.doc.nodes, id);\n\t\t\tlet parent = loc?.parent ?? null;\n\t\t\twhile (parent) {\n\t\t\t\tif (this.selection.includes(parent.id)) covered = true;\n\t\t\t\tparent = locateVectorNode(this.doc.nodes, parent.id)?.parent ?? null;\n\t\t\t}\n\t\t\treturn !covered;\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Transforms\n\t// -------------------------------------------------------------------------\n\n\t/** `m`, given in a frame rotated by `angle`, as a document-space matrix. */\n\tprivate inFrame(angle: number, m: AffineMatrix): AffineMatrix {\n\t\tif (!angle) return m;\n\t\treturn multiplyMatrices(multiplyMatrices(rotateMatrix(-angle), m), rotateMatrix(angle));\n\t}\n\n\t/** The selection frame's corners in document space, clockwise from the top left. */\n\tprivate frameCorners(frame: VectorSelectionFrame): Vec2[] {\n\t\tconst rot = rotateMatrix(frame.angle);\n\t\treturn vectorBoxCorners(frame).map((c) => (frame.angle ? applyMatrix(rot, c) : c));\n\t}\n\n\t/** `doc` with nodes `ids` sent through `f` (a map of document space), each in its own space (see `distortVectorNode`). */\n\tprivate distorted(doc: VectorDocument, ids: ReadonlySet<string>, f: (p: Vec2) => Vec2, tolerance = VECTOR_DISTORT_TOLERANCE): VectorDocument {\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix): VectorNode[] => {\n\t\t\tlet changed = false;\n\t\t\tconst out = list.map((n) => {\n\t\t\t\tlet next = n;\n\t\t\t\tif (ids.has(n.id) && !n.locked) next = distortVectorNode(n, parent, f, tolerance);\n\t\t\t\telse if (n.type === 'group') {\n\t\t\t\t\tconst children = visit(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (children !== n.children) next = { ...n, children };\n\t\t\t\t}\n\t\t\t\tif (next !== n) changed = true;\n\t\t\t\treturn next;\n\t\t\t});\n\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t};\n\t\tconst nodes = visit(doc.nodes, IDENTITY_MATRIX);\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\t/**\n\t * Free Distort mode of the selection box (`state.freeDistort`): dragging a corner distorts the\n\t * selection in perspective, each corner on its own (Shift+Alt+Mod: symmetric perspective, the\n\t * corner beside it moving the other way); dragging a side moves its two corners; Mod-dragging a\n\t * side skews along it (Alt: about the centre). Each drag is one undo step.\n\t */\n\tsetFreeDistort(on: boolean): void {\n\t\tif (this.freeDistort === on) return;\n\t\tthis.freeDistort = on;\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Distorts the selected (or given) nodes so the corners of their selection box (clockwise from\n\t * the top left, in the box's own rotation) land on `corners` (document space): a projective map,\n\t * so straight lines stay straight. Curves are followed within `tolerance` (document units).\n\t * One undo step.\n\t */\n\tdistort(corners: readonly Vec2[], options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst frame = this.frameOf(ids);\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tif (!(frame.width > 0 && frame.height > 0)) return { ok: false, message: 'The selection has no area to distort.' };\n\t\tconst from = this.frameCorners(frame);\n\t\tconst h = corners.length === 4 ? vectorHomography(from, corners) : null;\n\t\tif (!h || !vectorHomographyKeepsQuad(h, from)) return { ok: false, message: 'The four corners must make a convex quadrilateral, clockwise from the top left.' };\n\t\tthis.change('Distort', () => {\n\t\t\tthis.doc = this.distorted(this.doc, new Set(ids), (p) => applyVectorHomography(h, p) ?? p, options.tolerance);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Skews the selected (or given) nodes along the selection box's own axes by `ax` degrees\n\t * horizontally (x' = x + tan(ax)·y: vertical lines lean right for positive angles) and `ay`\n\t * vertically, about `origin` (default: the box centre, document space). One undo step.\n\t */\n\tskew(ax: number, ay = 0, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tif (![ax, ay].every((v) => Number.isFinite(v) && Math.abs(v) < 89.9)) return { ok: false, message: 'Skew angles must be between −89.9° and 89.9°.' };\n\t\tconst origin = applyMatrix(rotateMatrix(-frame.angle), options.origin ?? this.frameCenter(frame));\n\t\treturn this.transform(this.inFrame(frame.angle, vectorSkewMatrix(ax, ay, origin)), { ids: options.ids, label: 'Skew' });\n\t}\n\n\t/** A selection box handle dragged in Free Distort mode. */\n\tprivate moveDistort(drag: Extract<Drag, { kind: 'scale' }>, p: Vec2, input: VectorPointerInput) {\n\t\tconst angle = drag.frame.angle;\n\t\tconst unrotate = (v: Vec2) => (angle ? applyMatrix(rotateMatrix(-angle), v) : v);\n\t\tconst q = unrotate(p);\n\t\tconst q0 = unrotate(drag.start);\n\t\tconst d = { x: q.x - q0.x, y: q.y - q0.y };\n\t\tconst ids = new Set(this.selectedRoots());\n\t\tconst from = this.frameCorners(drag.frame);\n\t\tconst corner = drag.handle.length === 2;\n\t\tthis.setGuides(null);\n\t\tif (!corner && input.mod) {\n\t\t\tconst m = this.inFrame(angle, vectorShearForSide(drag.frame, drag.handle, d, !!input.alt));\n\t\t\tdrag.op = 'Skew';\n\t\t\tthis.doc = this.transformed(drag.base, ids, m);\n\t\t\tthis.interaction = { type: 'distort', mode: 'skew', corners: from.map((c) => applyMatrix(m, c)) };\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tconst mode: VectorDistortMode = corner && input.mod && input.alt && input.shift ? 'perspective' : 'distort';\n\t\tconst rot = rotateMatrix(angle);\n\t\tconst quad = vectorDistortQuad(drag.frame, drag.handle, d, mode).map((c) => (angle ? applyMatrix(rot, c) : c));\n\t\tconst h = vectorHomography(from, quad);\n\t\t// A quad that folds over keeps the last good shape.\n\t\tif (!h || !vectorHomographyKeepsQuad(h, from)) return;\n\t\tdrag.op = mode === 'perspective' ? 'Perspective' : 'Distort';\n\t\tthis.doc = this.distorted(drag.base, ids, (pt) => applyVectorHomography(h, pt) ?? pt);\n\t\tthis.interaction = { type: 'distort', mode, corners: quad };\n\t\tthis.notify(true);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Envelopes\n\t// -------------------------------------------------------------------------\n\n\t/** Selected (or given) roots that can carry an envelope. */\n\tprivate envelopeTargets(ids?: readonly string[]): VectorNode[] {\n\t\treturn this.effectTargets(ids).filter((n) => !n.locked);\n\t}\n\n\t/** Envelope parameters for `node` after `patch`: a preset switched to a mesh becomes the mesh it stood for. */\n\tprivate envelopeParams(node: VectorNode, current: Extract<VectorEffect, { type: 'envelope' }> | null, patch: Record<string, unknown>): Record<string, unknown> {\n\t\tif (patch.style !== 'mesh' || patch.mesh !== undefined || !current || current.params.style === 'mesh') return patch;\n\t\tconst frame = vectorEnvelopeFrame(node, current.id);\n\t\tif (!frame) return patch;\n\t\tconst rows = typeof patch.rows === 'number' ? patch.rows : current.params.rows;\n\t\tconst columns = typeof patch.columns === 'number' ? patch.columns : current.params.columns;\n\t\treturn { ...patch, mesh: resizeVectorMesh(frame.mesh, columns, rows) };\n\t}\n\n\t/**\n\t * Gives the selected (or given) nodes an envelope distortion, or changes the one they have: a\n\t * warp preset (`style` with `bend`, `horizontal` and `vertical` in percent and `orientation`) or\n\t * a mesh (`style: 'mesh'` with `rows` and `columns`, and optionally its `mesh` points). The\n\t * envelope stays live (an `envelope` effect: edit it with the Envelope tool, Expand Appearance\n\t * bakes it). One undo step (with `merge`, consecutive changes fold into one, as a slider drag\n\t * should). Returns the envelope of each node.\n\t */\n\tenvelope(params: Partial<VectorEnvelopeParams> = {}, options: { ids?: readonly string[]; merge?: boolean } = {}): { nodeId: string; effectId: string }[] {\n\t\tconst targets = this.envelopeTargets(options.ids);\n\t\tif (!targets.length) return [];\n\t\tconst out: { nodeId: string; effectId: string }[] = [];\n\t\tconst next = new Map<string, VectorNode>();\n\t\tconst raw = params as Record<string, unknown>;\n\t\tfor (const node of targets) {\n\t\t\tconst list = node.effects ?? [];\n\t\t\tconst current = (list.find((e) => e.type === 'envelope') as Extract<VectorEffect, { type: 'envelope' }> | undefined) ?? null;\n\t\t\tif (current) {\n\t\t\t\tconst p = normalizeVectorEffectParams('envelope', this.envelopeParams(node, current, raw), current.params)!;\n\t\t\t\tconst { enabled: _e, ...rest } = current;\n\t\t\t\tnext.set(node.id, { ...node, effects: list.map((e) => (e === current ? { ...rest, params: p } : e)) } as VectorNode);\n\t\t\t\tout.push({ nodeId: node.id, effectId: current.id });\n\t\t\t} else {\n\t\t\t\tlet k = list.length + 1;\n\t\t\t\twhile (list.some((e) => e.id === `fx${k}`)) k++;\n\t\t\t\tconst effect = createVectorEffect('envelope', `fx${k}`, raw)!;\n\t\t\t\tnext.set(node.id, { ...node, effects: [...list, effect] } as VectorNode);\n\t\t\t\tout.push({ nodeId: node.id, effectId: effect.id });\n\t\t\t}\n\t\t}\n\t\tconst made = out.some((o) => !targets.find((n) => n.id === o.nodeId)?.effects?.some((e) => e.id === o.effectId));\n\t\tconst merge = options.merge ? `envelope:${out.map((o) => o.nodeId).join(',')}` : undefined;\n\t\tthis.change(made ? (params.style === 'mesh' ? 'Make Envelope with Mesh' : 'Make Envelope with Warp') : 'Edit Envelope', () => this.setDoc(mapTree(this.doc.nodes, (n) => next.get(n.id) ?? n)), merge);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Make with Top Object: the topmost selected object's outline (a closed path) becomes the envelope\n\t * of the other selected objects (grouped when there are several; they must share a parent), as a\n\t * mesh of `columns × rows` patches whose border follows the outline. The top object is used up.\n\t * One undo step; returns the id of the enveloped node.\n\t */\n\tmakeEnvelopeWithTopObject(options: { ids?: readonly string[]; rows?: number; columns?: number } = {}): VectorActionResult & { nodeId?: string } {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (ids.length < 2) return { ok: false, message: 'Select the objects and, on top of them, the shape to use as the envelope.' };\n\t\tconst order = new Map<string, number>();\n\t\twalkVectorNodes(this.doc.nodes, (n) => order.set(n.id, order.size));\n\t\tconst sorted = ids.filter((id) => order.has(id)).sort((a, b) => order.get(a)! - order.get(b)!);\n\t\tconst topId = sorted[sorted.length - 1];\n\t\tconst top = this.getNode(topId);\n\t\tconst outline = top?.type === 'path' ? top.subpaths.find((sp) => sp.closed && sp.anchors.length > 1) : undefined;\n\t\tif (!top || !outline) return { ok: false, message: 'The top object must be a path with a closed outline.' };\n\t\tconst contents = sorted.slice(0, -1).map((id) => this.getNode(id)!);\n\t\tif (contents.some((n) => n.locked)) return { ok: false, message: 'Locked objects cannot be enveloped.' };\n\t\tconst parents = contents.map((n) => locateVectorNode(this.doc.nodes, n.id)?.parent?.id ?? null);\n\t\tif (parents.some((p) => p !== parents[0])) return { ok: false, message: 'The objects to envelope must be in the same group.' };\n\t\t// The node that gets the envelope: the one object, or a new group of them in place of the topmost.\n\t\tconst target: VectorNode =\n\t\t\tcontents.length === 1 ? contents[0] : { id: this.newId(), type: 'group', name: 'Envelope', children: contents.map((n) => n) };\n\t\tconst parentToDoc = parents[0] ? this.worldOf(parents[0]) : IDENTITY_MATRIX;\n\t\tconst targetToDoc = multiplyMatrices(nodeMatrix(target), parentToDoc);\n\t\tconst toLocal = multiplyMatrices(this.worldOf(topId), invertMatrix(targetToDoc));\n\t\tconst local = {\n\t\t\tclosed: true,\n\t\t\tanchors: outline.anchors.map((a) => ({\n\t\t\t\t...applyMatrix(toLocal, a),\n\t\t\t\t...(a.in ? { in: applyMatrix(toLocal, a.in) } : {}),\n\t\t\t\t...(a.out ? { out: applyMatrix(toLocal, a.out) } : {})\n\t\t\t}))\n\t\t};\n\t\tconst mesh = vectorMeshFromOutline(local, options.columns ?? 4, options.rows ?? 4);\n\t\tif (!mesh) return { ok: false, message: 'The top object’s outline is too small to use as an envelope.' };\n\t\tconst list = target.effects ?? [];\n\t\tlet k = list.length + 1;\n\t\twhile (list.some((e) => e.id === `fx${k}`)) k++;\n\t\tconst effect = createVectorEffect('envelope', `fx${k}`, { style: 'mesh', mesh })!;\n\t\tconst enveloped = { ...target, effects: [...list, effect] } as VectorNode;\n\t\tthis.change('Make Envelope with Top Object', () => {\n\t\t\tlet nodes = spliceTree(this.doc.nodes, topId, []);\n\t\t\tif (contents.length === 1) nodes = spliceTree(nodes, target.id, [enveloped]);\n\t\t\telse {\n\t\t\t\tconst last = contents[contents.length - 1].id;\n\t\t\t\tfor (const n of contents.slice(0, -1)) nodes = spliceTree(nodes, n.id, []);\n\t\t\t\tnodes = spliceTree(nodes, last, [enveloped]);\n\t\t\t}\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.selection = [target.id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn { ok: true, nodeId: target.id };\n\t}\n\n\t/**\n\t * Release: the selected (or given) nodes lose their envelope, and its shape (the mesh's border)\n\t * comes back as a path above each of them. One undo step; returns the new paths' ids.\n\t */\n\treleaseEnvelope(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst targets = this.envelopeTargets(options.ids).filter((n) => n.effects?.some((e) => e.type === 'envelope'));\n\t\tif (!targets.length) return [];\n\t\tconst created: string[] = [];\n\t\tconst replace = new Map<string, VectorNode[]>();\n\t\tfor (const node of targets) {\n\t\t\tconst effect = node.effects!.find((e) => e.type === 'envelope')!;\n\t\t\tconst frame = vectorEnvelopeFrame(node, effect.id);\n\t\t\tconst rest = node.effects!.filter((e) => e !== effect);\n\t\t\tconst { effects: _e, ...plain } = node;\n\t\t\tconst kept = (rest.length ? { ...plain, effects: rest } : plain) as VectorNode;\n\t\t\tif (!frame) {\n\t\t\t\treplace.set(node.id, [kept]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst id = this.newId();\n\t\t\tcreated.push(id);\n\t\t\tconst shape: VectorPathNode = {\n\t\t\t\tid,\n\t\t\t\ttype: 'path',\n\t\t\t\tname: 'Envelope',\n\t\t\t\t...(node.transform ? { transform: node.transform } : {}),\n\t\t\t\tsubpaths: [vectorMeshOutline(frame.mesh)],\n\t\t\t\tfill: null,\n\t\t\t\tstroke: '#808080',\n\t\t\t\tstrokeWidth: 1\n\t\t\t};\n\t\t\treplace.set(node.id, [kept, shape]);\n\t\t}\n\t\tthis.change('Release Envelope', () => {\n\t\t\tlet nodes = this.doc.nodes;\n\t\t\tfor (const [id, list] of replace) nodes = spliceTree(nodes, id, list);\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.selection = [...targets.map((n) => n.id), ...created];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn created;\n\t}\n\n\t/** The selected node the Envelope tool edits, with its mesh (node space) and node → document matrix. */\n\tprivate envelopeTarget() {\n\t\tconst target = getVectorEnvelopeTarget(this.doc, this.selection);\n\t\treturn target && !target.node.locked ? target : null;\n\t}\n\n\t/** The envelope mesh point under `screen` (handles first), or a spot inside the mesh. */\n\tprivate hitEnvelope(screen: Vec2, p: Vec2): { target: NonNullable<ReturnType<VectorEditorController['envelopeTarget']>>; index: number | null; s: number; t: number } | null {\n\t\tconst target = this.envelopeTarget();\n\t\tif (!target) return null;\n\t\tconst { mesh } = target.frame;\n\t\tconst pts = vectorMeshEditPoints(mesh);\n\t\tlet best: number | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const index of [...pts.handles.map((h) => h.index), ...pts.anchors]) {\n\t\t\tconst s = this.documentToScreen(applyMatrix(target.world, mesh.points[index]));\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\t// Handles come first, so an anchor wins only when it is clearly nearer.\n\t\t\tif (d <= this.hitRadius && d < bestD - 0.5) {\n\t\t\t\tbest = index;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\tif (best !== null) return { target, index: best, s: 0, t: 0 };\n\t\tconst local = applyMatrix(invertMatrix(target.world), p);\n\t\tconst at = vectorMeshParamAt(mesh, local);\n\t\tif (at.distance > this.tolerance()) return null;\n\t\treturn { target, index: null, s: at.s, t: at.t };\n\t}\n\n\tprivate downEnvelope(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst hit = this.hitEnvelope(screen, p);\n\t\tif (hit) {\n\t\t\tconst { node, frame } = hit.target;\n\t\t\tthis.drag = {\n\t\t\t\tkind: 'envelope',\n\t\t\t\tnodeId: node.id,\n\t\t\t\teffectId: frame.effectId,\n\t\t\t\tbase: frame.mesh,\n\t\t\t\tbaseDoc: this.doc,\n\t\t\t\tbefore: this.snapshot(),\n\t\t\t\tindex: hit.index,\n\t\t\t\ts: hit.s,\n\t\t\t\tt: hit.t,\n\t\t\t\tstart: this.toLocal(node.id, p),\n\t\t\t\tmoved: false\n\t\t\t};\n\t\t\tthis.interaction = { type: 'envelope', nodeId: node.id, index: hit.index };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\t// Elsewhere: pick the object to edit.\n\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance(), { entered: this.enteredGroups() });\n\t\tif (node) this.selection = input.shift ? (this.selection.includes(node.id) ? this.selection.filter((id) => id !== node.id) : [...this.selection, node.id]) : [node.id];\n\t\telse if (!input.shift) this.selection = [];\n\t\tthis.anchors = [];\n\t\tthis.notify();\n\t}\n\n\tprivate moveEnvelope(drag: Extract<Drag, { kind: 'envelope' }>, p: Vec2) {\n\t\tconst local = this.toLocal(drag.nodeId, p, drag.baseDoc);\n\t\tconst d = { x: local.x - drag.start.x, y: local.y - drag.start.y };\n\t\tif (!drag.moved && Math.hypot(d.x, d.y) * this.viewport.zoom < 1) return;\n\t\tdrag.moved = true;\n\t\tconst mesh = drag.index !== null ? dragVectorMeshPoint(drag.base, drag.index, d) : pullVectorMesh(drag.base, drag.s, drag.t, d);\n\t\tconst nodes = mapTree(drag.baseDoc.nodes, (n) => {\n\t\t\tif (n.id !== drag.nodeId) return n;\n\t\t\tconst effects = (n.effects ?? []).map((e) =>\n\t\t\t\te.id === drag.effectId && e.type === 'envelope'\n\t\t\t\t\t? { ...e, params: { ...e.params, style: 'mesh' as const, mesh, columns: mesh.us.length - 1, rows: mesh.vs.length - 1 } }\n\t\t\t\t\t: e\n\t\t\t);\n\t\t\treturn { ...n, effects } as VectorNode;\n\t\t});\n\t\tthis.doc = { ...drag.baseDoc, nodes };\n\t\tthis.notify(true);\n\t}\n\n\t/** Applies a matrix to the selected (or given) nodes as one undo step. */\n\ttransform(matrix: AffineMatrix, options: { ids?: readonly string[]; label?: string } = {}): VectorActionResult {\n\t\tconst ids = new Set(options.ids ?? this.selectedRoots());\n\t\tif (!ids.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(options.label ?? 'Transform', () => {\n\t\t\tthis.doc = this.transformed(this.doc, ids, matrix);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** `doc` with nodes `ids` moved by `m`, given in document space. */\n\tprivate transformed(doc: VectorDocument, ids: ReadonlySet<string>, m: AffineMatrix): VectorDocument {\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix): VectorNode[] => {\n\t\t\tlet changed = false;\n\t\t\tconst out = list.map((n) => {\n\t\t\t\tlet next = n;\n\t\t\t\tif (ids.has(n.id) && !n.locked) {\n\t\t\t\t\t// `m` in the node's parent space: parent → document, m, document → parent.\n\t\t\t\t\tconst local = isRoot(parent) ? m : multiplyMatrices(multiplyMatrices(parent, m), invertMatrix(parent));\n\t\t\t\t\tnext = transformVectorNode(n, local);\n\t\t\t\t} else if (n.type === 'group') {\n\t\t\t\t\tconst children = visit(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (children !== n.children) next = { ...n, children };\n\t\t\t\t}\n\t\t\t\tif (next !== n) changed = true;\n\t\t\t\treturn next;\n\t\t\t});\n\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t};\n\t\tconst nodes = visit(doc.nodes, IDENTITY_MATRIX);\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\ttranslate(dx: number, dy: number, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tif (this.tool === 'direct' && this.anchors.length && !options.ids) {\n\t\t\tthis.change('Move Points', () => {\n\t\t\t\tthis.doc = this.movedAnchors(this.doc, this.anchors, dx, dy);\n\t\t\t});\n\t\t\treturn { ok: true };\n\t\t}\n\t\treturn this.transform(translateMatrix(dx, dy), { ids: options.ids, label: 'Move' });\n\t}\n\n\t/** The selection frame's centre in document space. */\n\tprivate frameCenter(frame: VectorSelectionFrame): Vec2 {\n\t\treturn applyMatrix(rotateMatrix(frame.angle), { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 });\n\t}\n\n\t/**\n\t * Scales along the selection box's own axes (rotated with the selection when its nodes\n\t * share a rotation) around `origin` (default: the box centre, in document space).\n\t */\n\tscale(sx: number, sy: number = sx, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst origin = applyMatrix(rotateMatrix(-frame.angle), options.origin ?? this.frameCenter(frame));\n\t\treturn this.transform(this.inFrame(frame.angle, scaleMatrix(sx, sy, origin)), { ids: options.ids, label: 'Scale' });\n\t}\n\n\t/** Rotates clockwise by `degrees` around `origin` (default: the selection centre). */\n\trotate(degrees: number, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst origin = options.origin ?? this.frameCenter(frame);\n\t\treturn this.transform(rotateMatrix(degrees, origin), { ids: options.ids, label: 'Rotate' });\n\t}\n\n\t/** Sets each selected (or given) node's rotation to `degrees`, turning it around its own centre. */\n\tsetRotation(degrees: number, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change('Set Rotation', () => {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst frame = this.frameOf([id]);\n\t\t\t\tif (!frame) continue;\n\t\t\t\tconst delta = normalizeAngle(degrees - frame.angle);\n\t\t\t\tif (Math.abs(delta) > 1e-9) this.doc = this.transformed(this.doc, new Set([id]), rotateMatrix(delta, this.frameCenter(frame)));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Mirrors along the selection box's own axes. */\n\tflip(axis: 'horizontal' | 'vertical', options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst c = { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 };\n\t\tconst m = axis === 'horizontal' ? scaleMatrix(-1, 1, c) : scaleMatrix(1, -1, c);\n\t\treturn this.transform(this.inFrame(frame.angle, m), { ids: options.ids, label: axis === 'horizontal' ? 'Flip Horizontal' : 'Flip Vertical' });\n\t}\n\n\t/**\n\t * Aligns the selected nodes to their combined bounds, or to the artboard when one node is\n\t * selected (or `to: 'artboard'`).\n\t */\n\talign(edge: VectorAlign, options: { ids?: readonly string[]; to?: 'selection' | 'artboard' } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst target = options.to === 'artboard' || ids.length === 1 ? { x: 0, y: 0, width: this.doc.width, height: this.doc.height } : this.boundsOf(ids)!;\n\t\tthis.change(`Align ${edge[0].toUpperCase()}${edge.slice(1)}`, () => {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst b = this.boundsOf([id]);\n\t\t\t\tif (!b) continue;\n\t\t\t\tlet dx = 0;\n\t\t\t\tlet dy = 0;\n\t\t\t\tif (edge === 'left') dx = target.x - b.x;\n\t\t\t\tif (edge === 'center') dx = target.x + target.width / 2 - (b.x + b.width / 2);\n\t\t\t\tif (edge === 'right') dx = target.x + target.width - (b.x + b.width);\n\t\t\t\tif (edge === 'top') dy = target.y - b.y;\n\t\t\t\tif (edge === 'middle') dy = target.y + target.height / 2 - (b.y + b.height / 2);\n\t\t\t\tif (edge === 'bottom') dy = target.y + target.height - (b.y + b.height);\n\t\t\t\tif (dx || dy) this.doc = this.transformed(this.doc, new Set([id]), translateMatrix(dx, dy));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Spaces three or more selected nodes evenly (equal gaps). */\n\tdistribute(direction: VectorDistribute, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst items = ids.map((id) => ({ id, b: this.boundsOf([id]) })).filter((i): i is { id: string; b: VectorBounds } => !!i.b);\n\t\tif (items.length < 3) return { ok: false, message: 'Select at least three objects to distribute.' };\n\t\tconst horizontal = direction === 'horizontal';\n\t\tconst pos = (b: VectorBounds) => (horizontal ? b.x : b.y);\n\t\tconst size = (b: VectorBounds) => (horizontal ? b.width : b.height);\n\t\titems.sort((a, b) => pos(a.b) - pos(b.b));\n\t\tconst first = items[0].b;\n\t\tconst last = items[items.length - 1].b;\n\t\tconst total = pos(last) + size(last) - pos(first);\n\t\tconst gap = (total - items.reduce((s, i) => s + size(i.b), 0)) / (items.length - 1);\n\t\tthis.change(horizontal ? 'Distribute Horizontally' : 'Distribute Vertically', () => {\n\t\t\tlet cursor = pos(first);\n\t\t\tfor (const item of items) {\n\t\t\t\tconst d = cursor - pos(item.b);\n\t\t\t\tif (Math.abs(d) > 1e-9) this.doc = this.transformed(this.doc, new Set([item.id]), horizontal ? translateMatrix(d, 0) : translateMatrix(0, d));\n\t\t\t\tcursor += size(item.b) + gap;\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Structure\n\t// -------------------------------------------------------------------------\n\n\t/** Copies the selection (offset by `offset`, default 10, 10) on top of each original. */\n\tduplicate(options: { ids?: readonly string[]; offset?: Vec2 } = {}): string[] {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst offset = options.offset ?? { x: 10, y: 10 };\n\t\tconst created: string[] = [];\n\t\tif (!ids.length) return created;\n\t\tthis.change('Duplicate', () => {\n\t\t\tthis.doc = this.withDuplicates(this.doc, ids, offset, created);\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn created;\n\t}\n\n\tprivate withDuplicates(doc: VectorDocument, ids: readonly string[], offset: Vec2, created: string[]): VectorDocument {\n\t\tconst set = new Set(ids);\n\t\tconst m = translateMatrix(offset.x, offset.y);\n\t\tconst insert = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\tconst out: VectorNode[] = [];\n\t\t\tfor (const node of list) {\n\t\t\t\tconst n = node.type === 'group' ? { ...node, children: insert(node.children) } : node;\n\t\t\t\tout.push(n);\n\t\t\t\tif (set.has(node.id)) {\n\t\t\t\t\tconst copy = transformVectorNode(this.freshIds(node), m);\n\t\t\t\t\tcreated.push(copy.id);\n\t\t\t\t\tout.push(copy);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out;\n\t\t};\n\t\treturn { ...doc, nodes: insert(doc.nodes) };\n\t}\n\n\t/** Groups the selected nodes (they must share a parent). Returns the group id. */\n\tgroup(options: { ids?: readonly string[]; name?: string } = {}): string | null {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return null;\n\t\tconst locs = ids.map((id) => locateVectorNode(this.doc.nodes, id));\n\t\tif (locs.some((l) => !l)) return null;\n\t\tconst parent = locs[0]!.parent?.id ?? null;\n\t\tif (locs.some((l) => (l!.parent?.id ?? null) !== parent)) return null;\n\t\tconst id = this.newId();\n\t\tthis.change('Group', () => {\n\t\t\tconst set = new Set(ids);\n\t\t\tconst regroup = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst members = list.filter((n) => set.has(n.id));\n\t\t\t\tconst top = Math.max(...members.map((m) => list.indexOf(m)));\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlist.forEach((n, i) => {\n\t\t\t\t\tif (i === top) out.push({ id, type: 'group', name: options.name ?? 'Group', children: members });\n\t\t\t\t\tif (!set.has(n.id)) out.push(n);\n\t\t\t\t});\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tif (parent === null) this.setDoc(regroup(this.doc.nodes));\n\t\t\telse this.setDoc(mapTree(this.doc.nodes, (n) => (n.id === parent && n.type === 'group' ? { ...n, children: regroup(n.children) } : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Replaces selected groups with their children. */\n\tungroup(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst groups = (options.ids ?? this.selection).map((id) => this.getNode(id)).filter((n): n is VectorGroupNode => n?.type === 'group');\n\t\tif (!groups.length) return { ok: false, message: 'Select a group to ungroup.' };\n\t\tconst set = new Set(groups.map((g) => g.id));\n\t\tthis.change('Ungroup', () => {\n\t\t\tconst flatten = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlet changed = false;\n\t\t\t\tfor (const n of list) {\n\t\t\t\t\tif (set.has(n.id) && n.type === 'group') {\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\tconst opacity = n.opacity;\n\t\t\t\t\t\tconst m = nodeMatrix(n);\n\t\t\t\t\t\tout.push(\n\t\t\t\t\t\t\t...n.children\n\t\t\t\t\t\t\t\t.map((c) => (c.blendStep ? (({ blendStep: _s, locked: _l, ...rest }) => rest as VectorNode)(c) : c))\n\t\t\t\t\t\t\t\t.map((c) => (c.booleanOperation ? (({ booleanOperation: _b, ...rest }) => rest as VectorNode)(c) : c))\n\t\t\t\t\t\t\t\t.map((c) => (n.transform ? transformVectorNode(c, m) : c))\n\t\t\t\t\t\t\t\t.map((c) => (opacity !== undefined && opacity < 1 ? { ...c, opacity: (c.opacity ?? 1) * opacity } : c))\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (n.type === 'group') {\n\t\t\t\t\t\tconst children = flatten(n.children);\n\t\t\t\t\t\tif (children !== n.children) changed = true;\n\t\t\t\t\t\tout.push(children !== n.children ? { ...n, children } : n);\n\t\t\t\t\t} else out.push(n);\n\t\t\t\t}\n\t\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t\t};\n\t\t\tthis.setDoc(flatten(this.doc.nodes));\n\t\t\tthis.selection = groups.flatMap((g) => g.children.map((c) => c.id));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Changes stacking order within each node's parent. */\n\tarrange(op: VectorArrange, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst set = new Set(options.ids ?? this.selectedRoots());\n\t\tif (!set.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst reorder = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\tconst out = list.map((n) => (n.type === 'group' ? { ...n, children: reorder(n.children) } : n));\n\t\t\tif (op === 'front') return [...out.filter((n) => !set.has(n.id)), ...out.filter((n) => set.has(n.id))];\n\t\t\tif (op === 'back') return [...out.filter((n) => set.has(n.id)), ...out.filter((n) => !set.has(n.id))];\n\t\t\tif (op === 'forward') {\n\t\t\t\tfor (let i = out.length - 2; i >= 0; i--) if (set.has(out[i].id) && !set.has(out[i + 1].id)) [out[i], out[i + 1]] = [out[i + 1], out[i]];\n\t\t\t} else {\n\t\t\t\tfor (let i = 1; i < out.length; i++) if (set.has(out[i].id) && !set.has(out[i - 1].id)) [out[i], out[i - 1]] = [out[i - 1], out[i]];\n\t\t\t}\n\t\t\treturn out;\n\t\t};\n\t\tconst labels = { front: 'Bring to Front', forward: 'Bring Forward', backward: 'Send Backward', back: 'Send to Back' };\n\t\tthis.change(labels[op], () => this.setDoc(reorder(this.doc.nodes)));\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Combines the selected paths (two or more) into one with a boolean operation. `subtract`\n\t * removes the upper shapes from the lowest one. The result takes the lowest shape's style\n\t * and place. Shapes take part as drawn (path effects and live booleans applied).\n\t *\n\t * With `live`, the operands stay editable instead: a lone live boolean group gets the\n\t * operation (its operands follow it again), operands of live boolean groups get it as their\n\t * own, and anything else (two or more nodes with one parent) is wrapped in a new live boolean\n\t * group. Returns the result's (or the live group's) id, or null.\n\t */\n\tbooleanOp(op: VectorBooleanOperation, options: { ids?: readonly string[]; live?: boolean } = {}): string | null {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tif (options.live) return this.liveBooleanOp(op, roots);\n\t\tconst entries = vectorPathEntries(this.doc, roots, { locked: true });\n\t\tif (entries.length < 2) return null;\n\t\tconst result = pathBoolean(\n\t\t\tBOOLEAN_OPS[op],\n\t\t\tentries.map((e) => ({\n\t\t\t\tpath: vectorPathWorldBezier({ ...e.node, subpaths: e.node.subpaths.filter((s) => s.anchors.length > 1).map((s) => ({ ...s, closed: true })) }, e.parent),\n\t\t\t\tfillRule: e.node.fillRule ?? 'nonzero'\n\t\t\t}))\n\t\t);\n\t\tconst base = entries[0].node;\n\t\tconst anchorRoot = roots.find((r) => this.holds(r, base.id)) ?? base.id;\n\t\tconst subpaths = bezierToSubpaths(this.intoParentSpace(anchorRoot, result.path));\n\t\tif (result.error || !subpaths.length) return null;\n\t\tconst id = this.newId();\n\t\tconst { transform: _t, effects: _e, booleanOperation: _b, ...baseRest } = cloneVectorNode(base);\n\t\tconst node: VectorPathNode = { ...baseRest, id, name: BOOLEAN_LABELS[op], subpaths };\n\t\tconst drop = new Set([...entries.map((e) => e.node.id), ...roots]);\n\t\tthis.change(BOOLEAN_LABELS[op], () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === anchorRoot ? node : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Whether stored node `rootId` holds `id` as drawn (`id` may be an expanded path inside it). */\n\tprivate holds(rootId: string, id: string): boolean {\n\t\tconst n = this.getNode(rootId);\n\t\treturn !!n && (!!findVectorNode([n], id) || !!findVectorNode([expandVectorAppearance(n)], id));\n\t}\n\n\tprivate liveBooleanOp(op: VectorBooleanOperation, roots: readonly string[]): string | null {\n\t\tconst nodes = roots.map((id) => this.getNode(id));\n\t\tif (!nodes.length || nodes.some((n) => !n)) return null;\n\t\tconst label = `Live ${BOOLEAN_LABELS[op]}`;\n\t\tconst lone = nodes.length === 1 ? nodes[0] : null;\n\t\tif (isVectorLiveBoolean(lone)) {\n\t\t\tconst children = lone.children.map((c) => (c.booleanOperation ? (({ booleanOperation: _b, ...rest }) => rest as VectorNode)(c) : c));\n\t\t\tthis.change(label, () => this.replaceNode(lone.id, { ...lone, liveBoolean: op, children }));\n\t\t\treturn lone.id;\n\t\t}\n\t\tconst parents = roots.map((id) => locateVectorNode(this.doc.nodes, id)?.parent ?? null);\n\t\tif (parents.every((g) => isVectorLiveBoolean(g))) {\n\t\t\tconst set = new Set(roots);\n\t\t\tthis.change(label, () =>\n\t\t\t\tthis.setDoc(\n\t\t\t\t\tmapTree(this.doc.nodes, (n) => {\n\t\t\t\t\t\tif (n.type !== 'group' || !n.liveBoolean || !n.children.some((c) => set.has(c.id))) return n;\n\t\t\t\t\t\tconst group = n;\n\t\t\t\t\t\tconst children = group.children.map((c) => {\n\t\t\t\t\t\t\tif (!set.has(c.id)) return c;\n\t\t\t\t\t\t\tconst { booleanOperation: _b, ...rest } = c;\n\t\t\t\t\t\t\treturn (op === group.liveBoolean ? rest : { ...rest, booleanOperation: op }) as VectorNode;\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn { ...group, children };\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t);\n\t\t\treturn parents[0]!.id;\n\t\t}\n\t\tif (nodes.length < 2) return null;\n\t\tconst parent = parents[0]?.id ?? null;\n\t\tif (parents.some((g) => (g?.id ?? null) !== parent)) return null;\n\t\tconst id = this.newId();\n\t\tthis.change(label, () => {\n\t\t\tconst set = new Set(roots);\n\t\t\tconst wrap = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst members = list.filter((n) => set.has(n.id)).map((c) => (c.booleanOperation ? (({ booleanOperation: _b, ...rest }) => rest as VectorNode)(c) : c));\n\t\t\t\tconst top = Math.max(...list.map((n, i) => (set.has(n.id) ? i : -1)));\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlist.forEach((n, i) => {\n\t\t\t\t\tif (i === top) out.push({ id, type: 'group', name: BOOLEAN_LABELS[op], liveBoolean: op, children: members });\n\t\t\t\t\tif (!set.has(n.id)) out.push(n);\n\t\t\t\t});\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tif (parent === null) this.setDoc(wrap(this.doc.nodes));\n\t\t\telse this.setDoc(mapTree(this.doc.nodes, (n) => (n.id === parent && n.type === 'group' ? { ...n, children: wrap(n.children) } : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Joins the selected paths into one compound path (subpaths kept, lowest style). */\n\tcombine(options: { ids?: readonly string[] } = {}): string | null {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst entries = vectorPathEntries(this.doc, roots, { locked: true });\n\t\tif (entries.length < 2) return null;\n\t\tconst paths = entries.map((e) => e.node);\n\t\tconst id = this.newId();\n\t\tconst first = roots.find((r) => this.holds(r, paths[0].id)) ?? paths[0].id;\n\t\tconst subpaths = entries.flatMap((e) => bezierToSubpaths(this.intoParentSpace(first, vectorPathWorldBezier(e.node, e.parent))));\n\t\tconst { transform: _t, effects: _e, booleanOperation: _b, ...baseRest } = cloneVectorNode(paths[0]);\n\t\tconst node: VectorPathNode = { ...baseRest, id, name: 'Compound Path', subpaths };\n\t\tconst drop = new Set([...paths.map((p) => p.id), ...roots]);\n\t\tthis.change('Combine', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === first ? node : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** A document-space path mapped into the parent space of node `id`. */\n\tprivate intoParentSpace(id: string, path: BezierPath): BezierPath {\n\t\tconst parent = vectorParentMatrix(this.doc.nodes, id) ?? IDENTITY_MATRIX;\n\t\treturn isRoot(parent) ? path : transformBezierPath(path, invertMatrix(parent));\n\t}\n\n\t/** Splits selected compound paths into one path per subpath. */\n\tbreakApart(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst paths = (options.ids ?? this.selection).map((id) => this.getNode(id)).filter((n): n is VectorPathNode => n?.type === 'path' && n.subpaths.length > 1);\n\t\tif (!paths.length) return { ok: false, message: 'Select a compound path to break apart.' };\n\t\tconst created: string[] = [];\n\t\tconst set = new Set(paths.map((p) => p.id));\n\t\tthis.change('Break Apart', () => {\n\t\t\tconst split = (list: readonly VectorNode[]): VectorNode[] =>\n\t\t\t\tlist.flatMap((n): VectorNode[] => {\n\t\t\t\t\tif (n.type === 'group') return [{ ...n, children: split(n.children) }];\n\t\t\t\t\tif (!set.has(n.id)) return [n];\n\t\t\t\t\treturn n.subpaths.map((sp, i) => {\n\t\t\t\t\t\tconst id = i === 0 ? n.id : this.newId();\n\t\t\t\t\t\tcreated.push(id);\n\t\t\t\t\t\treturn { ...n, id, subpaths: [sp] };\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\tthis.setDoc(split(this.doc.nodes));\n\t\t\tthis.selection = created;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Pathfinder, Shape Builder and paint bucket\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Pathfinder: Divide, Trim, Merge, Crop, Outline or Minus Back over the selected (or given)\n\t * paths, in document space (rotated nodes and groups included, live corners cut). Unfilled\n\t * stroked paths take part as the area their stroke paints (Divide: open ones cut instead).\n\t * The results replace the operands at the place of the top-most one, grouped when there are\n\t * several; each keeps the style of the operand whose area it is. Returns the new path ids,\n\t * or an empty list when nothing came out.\n\t */\n\tpathfinder(op: VectorPathfinderOperation, options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst entries = vectorPathEntries(this.doc, roots);\n\t\tif (entries.length < (op === 'divide' || op === 'outline' ? 1 : 2)) return [];\n\t\tconst shapes = entries.map((e) => vectorPathfinderShape(e, op));\n\t\tconst result = runPathfinder(op, shapes);\n\t\tif (result.error || !result.pieces.length) return [];\n\t\tconst last = entries[entries.length - 1].node.id;\n\t\tconst topRoot = [...roots].reverse().find((r) => this.holds(r, last)) ?? last;\n\t\tconst nodes: VectorPathNode[] = [];\n\t\tfor (const piece of result.pieces) {\n\t\t\tconst subpaths = bezierToSubpaths(this.intoParentSpace(topRoot, piece.path)).map((sp) => (piece.open ? { ...sp, closed: false } : sp));\n\t\t\tif (!subpaths.length) continue;\n\t\t\tconst source = entries[piece.source].node;\n\t\t\tconst style = vectorResultStyle(source, shapes[piece.source].paint, op === 'outline');\n\t\t\tnodes.push({ ...style, type: 'path', id: this.newId(), name: source.name ?? 'Path', subpaths });\n\t\t}\n\t\tif (!nodes.length) return [];\n\t\tconst label = VECTOR_PATHFINDER_LABELS[op];\n\t\tconst container: VectorNode = nodes.length > 1 ? { id: this.newId(), type: 'group', name: label, children: nodes } : nodes[0];\n\t\tconst drop = new Set([...entries.map((e) => e.node.id), ...roots]);\n\t\tthis.change(label, () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === topRoot ? container : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [container.id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn nodes.map((n) => n.id);\n\t}\n\n\t/** The Shape Builder map of the selected (or given) paths, cached per document and selection. */\n\t// -------------------------------------------------------------------------\n\t// Blends\n\t// -------------------------------------------------------------------------\n\n\t/** Selected (or given) blend groups; a selected key or step counts as its blend. */\n\tprivate blendTargets(ids?: readonly string[]): (VectorGroupNode & { blend: VectorBlend })[] {\n\t\tconst out = new Map<string, VectorGroupNode & { blend: VectorBlend }>();\n\t\tfor (const id of ids ?? this.selection) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tconst group = isVectorBlendGroup(node) ? node : locateVectorNode(this.doc.nodes, id)?.parent;\n\t\t\tif (isVectorBlendGroup(group)) out.set(group.id, group);\n\t\t}\n\t\treturn [...out.values()];\n\t}\n\n\t/**\n\t * Blends two or more selected (or given) paths or groups: they become the keys of a live\n\t * blend group (bottom to top, or in the order given with `keepOrder`) whose in-betweens are\n\t * regenerated whenever a key or the options change. The keys must share a parent. Returns\n\t * the blend group's id, or null.\n\t */\n\tblend(input: VectorBlendInput = {}): string | null {\n\t\tconst ids = [...new Set(input.ids ?? this.selectedRoots())].filter((id) => {\n\t\t\tconst n = this.getNode(id);\n\t\t\treturn !!n && !n.blendStep && !n.locked;\n\t\t});\n\t\tif (ids.length < 2) return null;\n\t\tconst locs = ids.map((id) => locateVectorNode(this.doc.nodes, id)!);\n\t\tconst parent = locs[0].parent?.id ?? null;\n\t\tif (locs.some((l) => (l.parent?.id ?? null) !== parent)) return null;\n\t\tconst order = input.keepOrder ? ids : ids.slice().sort((a, b) => locs[ids.indexOf(a)].index - locs[ids.indexOf(b)].index);\n\t\tconst blend: VectorBlend = blendOptionsOf({ ...this.blendDefaults, ...input });\n\t\tif (input.starts) {\n\t\t\tconst starts = Object.fromEntries(Object.entries(input.starts).filter(([k, v]) => order.includes(k) && Number.isInteger(v) && v >= 0));\n\t\t\tif (Object.keys(starts).length) blend.starts = starts;\n\t\t}\n\t\tconst id = this.newId();\n\t\tthis.change('Blend', () => {\n\t\t\tconst set = new Set(order);\n\t\t\tconst regroup = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst members = order.map((m) => list.find((n) => n.id === m)!);\n\t\t\t\tconst top = Math.max(...members.map((m) => list.indexOf(m)));\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlist.forEach((n, i) => {\n\t\t\t\t\tif (i === top) out.push({ id, type: 'group', name: input.name ?? 'Blend', blend, children: members });\n\t\t\t\t\tif (!set.has(n.id)) out.push(n);\n\t\t\t\t});\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tif (parent === null) this.setDoc(regroup(this.doc.nodes));\n\t\t\telse this.setDoc(mapTree(this.doc.nodes, (n) => (n.id === parent && n.type === 'group' ? { ...n, children: regroup(n.children) } : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Sets the options new blends get (spacing, steps, distance, orientation, morph). */\n\tsetBlendDefaults(patch: Partial<VectorBlendOptions>): void {\n\t\tthis.blendDefaults = { ...this.blendDefaults, ...blendOptionsOf(patch) };\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Adds a node as the last key of a blend (it must share the blend's parent); `start` is the\n\t * anchor of its first subpath the blend starts from. One undo step.\n\t */\n\taddBlendKey(blendId: string, nodeId: string, options: { start?: number | null } = {}): VectorActionResult {\n\t\tconst group = this.getNode(blendId);\n\t\tconst node = this.getNode(nodeId);\n\t\tif (!isVectorBlendGroup(group)) return { ok: false, message: `\"${blendId}\" is not a blend.` };\n\t\tif (!node || node.blendStep || node.locked || node.id === blendId) return { ok: false, message: `\"${nodeId}\" cannot be a key.` };\n\t\tconst parentOf = (id: string) => locateVectorNode(this.doc.nodes, id)?.parent?.id ?? null;\n\t\tif (parentOf(blendId) !== parentOf(nodeId)) return { ok: false, message: 'The new key must sit beside the blend (same parent).' };\n\t\tconst start = options.start;\n\t\tthis.change('Blend', () => {\n\t\t\tconst blend = start !== null && start !== undefined ? { ...group.blend, starts: { ...group.blend.starts, [nodeId]: start } } : group.blend;\n\t\t\t// The key leaves its place and joins the blend.\n\t\t\tconst m = invertMatrix(nodeMatrix(group));\n\t\t\tconst key = group.transform ? transformVectorNode(node, m) : node;\n\t\t\t// Two passes: the key must not be removed again from inside the blend.\n\t\t\tconst without = mapTree(this.doc.nodes, (n) => (n.id === nodeId ? null : n));\n\t\t\tthis.setDoc(spliceTree(without, blendId, [{ ...group, blend, children: [...group.children, key] }]));\n\t\t\tthis.selection = [blendId];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Changes the spacing, steps, distance, orientation or morph of the selected (or given) blends. */\n\tsetBlendOptions(patch: Partial<VectorBlendOptions>, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst groups = this.blendTargets(options.ids);\n\t\tif (!groups.length) return { ok: false, message: 'Select a blend.' };\n\t\tconst clean = blendOptionsOf(patch);\n\t\tif (!Object.keys(clean).length) return { ok: false, message: 'No valid blend options were given.' };\n\t\tconst set = new Set(groups.map((g) => g.id));\n\t\tthis.change('Blend Options', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (set.has(n.id) && n.type === 'group' && n.blend ? { ...n, blend: { ...n.blend, ...clean } } : n)));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Expand: turns the selected (or given) blends into plain groups of their keys and steps. Returns their ids. */\n\texpandBlend(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst groups = this.blendTargets(options.ids);\n\t\tif (!groups.length) return [];\n\t\tconst set = new Set(groups.map((g) => g.id));\n\t\tconst used = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n) => used.add(n.id));\n\t\tconst fresh = () => {\n\t\t\tlet id = this.createId();\n\t\t\twhile (used.has(id)) id = this.createId();\n\t\t\tused.add(id);\n\t\t\treturn id;\n\t\t};\n\t\tthis.change('Expand Blend', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (set.has(n.id) && n.type === 'group' ? expandVectorBlend(n, fresh) : n)));\n\t\t\tthis.selection = [...set];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn [...set];\n\t}\n\n\t/** Release: replaces the selected (or given) blends with their keys (and a replaced spine as a path). */\n\treleaseBlend(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst groups = this.blendTargets(options.ids);\n\t\tif (!groups.length) return [];\n\t\tconst released: string[] = [];\n\t\tthis.change('Release Blend', () => {\n\t\t\tfor (const g of groups) {\n\t\t\t\tconst nodes = releaseVectorBlend(g, () => this.newId());\n\t\t\t\treleased.push(...nodes.map((n) => n.id));\n\t\t\t\tthis.setDoc(spliceTree(this.doc.nodes, g.id, nodes));\n\t\t\t}\n\t\t\tthis.selection = released;\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn released;\n\t}\n\n\t/**\n\t * Replace Spine: the selected blend's steps follow the selected path instead of the straight\n\t * lines between its keys. The path's first subpath becomes the spine (the path is removed)\n\t * and the keys move onto it, spread evenly by arc length.\n\t */\n\treplaceBlendSpine(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst groups = this.blendTargets(roots);\n\t\tconst paths = roots.map((id) => this.getNode(id)).filter((n): n is VectorPathNode => n?.type === 'path' && !n.blendStep && !isVectorBlendGroup(locateVectorNode(this.doc.nodes, n.id)?.parent));\n\t\tif (groups.length !== 1 || paths.length !== 1) return { ok: false, message: 'Select one blend and one path to be its spine.' };\n\t\tconst group = groups[0];\n\t\tconst path = paths[0];\n\t\tconst first = path.subpaths.find((sp) => sp.anchors.length >= 2);\n\t\tif (!first) return { ok: false, message: 'The spine needs a path with at least two points.' };\n\t\t// The path's first subpath in the blend group's own space.\n\t\tconst m = multiplyMatrices(this.worldOf(path.id), invertMatrix(this.worldOf(group.id)));\n\t\tconst spine = transformVectorNode<VectorPathNode>({ id: '', type: 'path', subpaths: [first] }, m).subpaths[0];\n\t\tthis.change('Replace Spine', () => {\n\t\t\tconst withSpine: VectorGroupNode = { ...group, blend: { ...group.blend, spine } };\n\t\t\tconst targets = vectorBlendKeyTargets(withSpine);\n\t\t\tlet k = 0;\n\t\t\tconst children = withSpine.children.map((c) => {\n\t\t\t\tif (c.blendStep) return c;\n\t\t\t\tconst target = targets[k++];\n\t\t\t\tconst b = vectorNodeBounds(c);\n\t\t\t\tif (!target || !b) return c;\n\t\t\t\tconst dx = target[0] - (b.x + b.width / 2);\n\t\t\t\tconst dy = target[1] - (b.y + b.height / 2);\n\t\t\t\treturn Math.hypot(dx, dy) > 1e-9 ? transformVectorNode(c, translateMatrix(dx, dy)) : c;\n\t\t\t});\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === path.id ? null : n.id === group.id ? { ...withSpine, children } : n)));\n\t\t\tthis.selection = [group.id];\n\t\t\tthis.anchors = [];\n\t\t\tif (this.editingId === path.id) this.editingId = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\tprivate shapeBuilderMap(ids?: readonly string[]): VectorShapeBuilderMap | null {\n\t\tconst roots = ids ?? this.selectedRoots();\n\t\tconst key = roots.join('\\u0000');\n\t\tif (this.builderCache?.doc === this.doc && this.builderCache.key === key) return this.builderCache.map;\n\t\t// The Shape Builder edits the shapes it takes area from: their stored geometry.\n\t\tconst entries = roots.length ? vectorPathEntries(this.doc, roots, { expand: false }) : [];\n\t\tconst map = entries.length ? vectorShapeBuilderMap(entries) : null;\n\t\tthis.builderCache = { doc: this.doc, key, map };\n\t\treturn map;\n\t}\n\n\t/** The faces the Shape Builder offers for the selected (or given) paths (document units). */\n\tgetShapeBuilderFaces(options: { ids?: readonly string[] } = {}): VectorShapeBuilderFace[] {\n\t\tconst m = this.shapeBuilderMap(options.ids);\n\t\tif (!m) return [];\n\t\treturn m.map.faces.map((f, index) => {\n\t\t\tconst p = m.map.faceInterior(index);\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\td: bezierPathToSvg(f.path, { precision: 3 }),\n\t\t\t\tarea: f.area,\n\t\t\t\tsources: m.map.faceSources(index).map((i) => m.entries[i].node.id),\n\t\t\t\tpoint: p ? { x: p[0], y: p[1] } : null\n\t\t\t};\n\t\t});\n\t}\n\n\t/** Pick distance of the Shape Builder's erase for line pieces (document units). */\n\tprivate builderLineTolerance(): number {\n\t\treturn Math.max(this.hitRadius, 4) / this.viewport.zoom;\n\t}\n\n\t/**\n\t * Shape Builder gesture along `points` (document units; one point is a click) over the faces\n\t * the selected (or given) paths make. Merges the faces touched into one shape styled like the\n\t * top-most shape over the first face (the current fill for a face only outlines enclose);\n\t * with `erase` deletes them, the pieces of unfilled open paths and the edges of other outlines\n\t * (cut where paths meet) within `tolerance`: a deleted edge opens a closed subpath there,\n\t * splits an open one or takes a subpath it runs all the way round, and edges bounding a face\n\t * deleted in the same gesture go with the face. Every shape covering a touched face loses\n\t * that area; paths keep their own transforms. One undo step.\n\t */\n\tshapeBuilder(points: readonly Vec2[], options: { ids?: readonly string[]; erase?: boolean; tolerance?: number } = {}): VectorShapeBuilderResult {\n\t\tconst none = (message: string): VectorShapeBuilderResult => ({ ok: false, message, merged: null, faces: 0, lines: 0, edges: 0 });\n\t\tif (!points.length || !points.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y))) return none('Give the points of the gesture.');\n\t\tconst m = this.shapeBuilderMap(options.ids);\n\t\tif (!m) return none('Select paths that make faces.');\n\t\tconst erase = !!options.erase;\n\t\tconst tol = erase ? (options.tolerance ?? this.builderLineTolerance()) : null;\n\t\tconst touched: VectorBuilderTouched = { faces: [], lines: [], edges: [] };\n\t\tconst size = m.map.faces.reduce((s, f) => Math.max(s, f.bounds.maxX - f.bounds.minX, f.bounds.maxY - f.bounds.minY), 1);\n\t\tfor (const p of samplePolyline(points, Math.max(size / 2000, 0.25 / this.viewport.zoom))) addBuilderHit(touched, vectorShapeBuilderHit(m, p, tol));\n\t\tif (!touched.faces.length && !touched.lines.length && !touched.edges.length) return none('There is no face under the pointer.');\n\t\treturn this.applyShapeBuilder(m, touched, erase);\n\t}\n\n\tprivate applyShapeBuilder(m: VectorShapeBuilderMap, touched: VectorBuilderTouched, erase: boolean): VectorShapeBuilderResult {\n\t\tconst plan = planShapeBuilder(m, touched, erase);\n\t\tlet mergedId: string | null = null;\n\t\tconst created = new Map<string, string[]>();\n\t\tthis.change(erase ? 'Shape Builder Delete' : 'Shape Builder', () => {\n\t\t\tlet nodes = this.doc.nodes;\n\t\t\tm.entries.forEach((entry, i) => {\n\t\t\t\tconst node = entry.node;\n\t\t\t\tconst toLocal = (path: BezierPath) => transformBezierPath(path, invertMatrix(multiplyMatrices(nodeMatrix(node), entry.parent)));\n\t\t\t\tconst list: VectorNode[] = [];\n\t\t\t\tconst r = plan.replace.get(i);\n\t\t\t\tif (r === undefined) list.push(node);\n\t\t\t\telse if (r?.kind === 'fill') list.push({ ...node, fillRule: 'nonzero', subpaths: bezierToSubpaths(toLocal(r.path)) });\n\t\t\t\telse if (r?.kind === 'outline') list.push({ ...node, subpaths: bezierToSubpaths(toLocal(r.path)) });\n\t\t\t\telse if (r?.kind === 'pieces') {\n\t\t\t\t\tr.paths.forEach((path, k) =>\n\t\t\t\t\t\tlist.push({ ...node, id: k === 0 ? node.id : this.newId(), subpaths: bezierToSubpaths(toLocal(path)).map((sp) => ({ ...sp, closed: false })) })\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (plan.merged && plan.merged.style === i) {\n\t\t\t\t\tmergedId = this.newId();\n\t\t\t\t\tconst merged: VectorPathNode = {\n\t\t\t\t\t\t...vectorResultStyle(node, 'fill'),\n\t\t\t\t\t\ttype: 'path',\n\t\t\t\t\t\tid: mergedId,\n\t\t\t\t\t\tname: 'Shape',\n\t\t\t\t\t\t...(node.transform ? { transform: node.transform } : {}),\n\t\t\t\t\t\tsubpaths: bezierToSubpaths(toLocal(plan.merged.path))\n\t\t\t\t\t};\n\t\t\t\t\tif (plan.merged.currentFill || !hasPaint(merged.fill)) merged.fill = hasPaint(this.defaults.fill) ? this.defaults.fill! : '#808080';\n\t\t\t\t\tlist.push(merged);\n\t\t\t\t}\n\t\t\t\tif (r === undefined && list.length === 1) return;\n\t\t\t\tcreated.set(node.id, list.map((n) => n.id));\n\t\t\t\tnodes = spliceTree(nodes, node.id, list);\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t\t// The shapes stay selected so the next gesture works on them too.\n\t\t\tconst selection = this.selection.flatMap((id) => created.get(id) ?? [id]);\n\t\t\tif (mergedId && !selection.includes(mergedId)) selection.push(mergedId);\n\t\t\tthis.selection = selection.filter((id, k) => !!this.getNode(id) && selection.indexOf(id) === k);\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\tthis.builderCache = null;\n\t\treturn { ok: true, merged: mergedId, faces: touched.faces.length, lines: touched.lines.length, edges: erase ? vectorBuilderErasedEdges(m, touched).length : 0 };\n\t}\n\n\t/** The paint bucket's map of the visible outlines, cached per document and gap. */\n\tprivate fillMap(gap: number): PlanarMap | null {\n\t\tif (this.fillCache?.doc === this.doc && this.fillCache.gap === gap) return this.fillCache.map;\n\t\tconst map = vectorFillMap(this.doc, gap);\n\t\tthis.fillCache = { doc: this.doc, gap, map };\n\t\treturn map;\n\t}\n\n\t/**\n\t * Paint bucket: the region the visible outlines enclose around `point` (document units),\n\t * crossings split and islands left as holes, becomes a new path filled with the current fill\n\t * default, placed just below the selection (or on top when nothing is selected). `gap`\n\t * (default `editing.fillGap`) closes gaps up to that size between loose ends. Returns the new\n\t * path's id, or null when nothing encloses the point.\n\t */\n\tfillRegion(point: Vec2, options: { gap?: number } = {}): string | null {\n\t\tif (!Number.isFinite(point.x) || !Number.isFinite(point.y)) return null;\n\t\tconst region = this.fillMap(options.gap ?? this.editing.fillGap)?.regionAt([point.x, point.y]);\n\t\tif (!region?.length) return null;\n\t\t// Below the lowest selected node, in its parent.\n\t\tlet below: string | null = null;\n\t\tconst roots = new Set(this.selectedRoots());\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (!below && roots.has(n.id)) below = n.id;\n\t\t});\n\t\tconst subpaths = bezierToSubpaths(below ? this.intoParentSpace(below, region) : region);\n\t\tif (!subpaths.length) return null;\n\t\tconst id = this.newId();\n\t\tconst node: VectorPathNode = { id, type: 'path', name: 'Fill', ...this.styleFor(false), stroke: null, fillRule: 'nonzero', subpaths };\n\t\tif (!hasPaint(node.fill)) node.fill = '#808080';\n\t\tconst target = below as string | null;\n\t\tthis.change('Fill Region', () => {\n\t\t\tif (target) {\n\t\t\t\tconst current = this.getNode(target)!;\n\t\t\t\tthis.setDoc(spliceTree(this.doc.nodes, target, [node, current]));\n\t\t\t} else this.setDoc([...this.doc.nodes, node]);\n\t\t\tif (!target) this.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Updates the Shape Builder / paint bucket highlight for the pointer at `p`; true when it changed. */\n\tprivate hoverBuilder(p: Vec2, alt: boolean): boolean {\n\t\tif (this.tool === 'paintBucket') {\n\t\t\tconst region = this.fillMap(this.editing.fillGap)?.regionAt([p.x, p.y]) ?? null;\n\t\t\tconst key = region ? bezierPathToSvg(region, { precision: 2 }) : null;\n\t\t\tif (key === this.builderHoverKey) return false;\n\t\t\tthis.builderHoverKey = key;\n\t\t\tthis.builderPreview = region ? { mode: 'fill', faces: [region], lines: [], trail: null } : null;\n\t\t\treturn true;\n\t\t}\n\t\tconst m = this.selectedRoots().length ? this.shapeBuilderMap() : null;\n\t\tconst hit = m ? vectorShapeBuilderHit(m, p, alt ? this.builderLineTolerance() : null) : null;\n\t\tconst key = hit ? `${alt ? 'erase' : 'merge'}:${JSON.stringify(hit)}` : null;\n\t\tif (key === this.builderHoverKey) return false;\n\t\tthis.builderHoverKey = key;\n\t\tconst touched: VectorBuilderTouched = { faces: [], lines: [], edges: [] };\n\t\taddBuilderHit(touched, hit);\n\t\tthis.builderPreview = hit && m ? this.builderPreviewOf(m, touched, alt, null) : null;\n\t\treturn true;\n\t}\n\n\tprivate builderPreviewOf(m: VectorShapeBuilderMap, touched: VectorBuilderTouched, erase: boolean, trail: Vec2[] | null): VectorBuilderPreview {\n\t\tconst faces = m.map.faces;\n\t\treturn {\n\t\t\tmode: erase ? 'erase' : 'merge',\n\t\t\tfaces: touched.faces.map((f) => faces[f].path),\n\t\t\t// Edges bounding a face touched too go with the face, so they are not shown apart.\n\t\t\tlines: [...touched.lines.map((k) => m.pieces[k].path), ...(erase ? vectorBuilderErasedEdges(m, touched).map((k) => m.edges[k].path) : [])],\n\t\t\ttrail\n\t\t};\n\t}\n\n\tprivate downBuilder(p: Vec2, input: VectorPointerInput) {\n\t\tthis.builderHoverKey = null;\n\t\tif (this.tool === 'paintBucket') {\n\t\t\tthis.fillRegion(p);\n\t\t\tthis.builderPreview = null;\n\t\t\tthis.hoverBuilder(p, false);\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst m = this.selectedRoots().length ? this.shapeBuilderMap() : null;\n\t\tif (!m) return;\n\t\tconst erase = !!input.alt;\n\t\tconst touched: VectorBuilderTouched = { faces: [], lines: [], edges: [] };\n\t\taddBuilderHit(touched, vectorShapeBuilderHit(m, p, erase ? this.builderLineTolerance() : null));\n\t\tthis.drag = { kind: 'builder', erase, points: [p], touched, map: m };\n\t\tthis.interaction = { type: 'builder', mode: erase ? 'erase' : 'merge', points: [p] };\n\t\tthis.builderPreview = this.builderPreviewOf(m, touched, erase, [p]);\n\t\tthis.notify();\n\t}\n\n\tprivate moveBuilder(drag: Extract<Drag, { kind: 'builder' }>, p: Vec2) {\n\t\tconst last = drag.points[drag.points.length - 1];\n\t\tif (Math.hypot(p.x - last.x, p.y - last.y) * this.viewport.zoom < 1) return;\n\t\tconst tol = drag.erase ? this.builderLineTolerance() : null;\n\t\tfor (const q of samplePolyline([last, p], 2 / this.viewport.zoom)) addBuilderHit(drag.touched, vectorShapeBuilderHit(drag.map, q, tol));\n\t\tdrag.points.push(p);\n\t\tthis.interaction = { type: 'builder', mode: drag.erase ? 'erase' : 'merge', points: drag.points.slice() };\n\t\tthis.builderPreview = this.builderPreviewOf(drag.map, drag.touched, drag.erase, drag.points.slice());\n\t\tthis.notify();\n\t}\n\n\tprivate upBuilder(drag: Extract<Drag, { kind: 'builder' }>) {\n\t\tthis.builderPreview = null;\n\t\tthis.builderHoverKey = null;\n\t\tif (!drag.touched.faces.length && !drag.touched.lines.length && !drag.touched.edges.length) {\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.applyShapeBuilder(drag.map, drag.touched, drag.erase);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Anchor editing\n\t// -------------------------------------------------------------------------\n\n\tprivate updateAnchors(doc: VectorDocument, refs: readonly VectorAnchorRef[], fn: (a: VectorAnchor, ref: VectorAnchorRef) => VectorAnchor): VectorDocument {\n\t\tconst byNode = new Map<string, VectorAnchorRef[]>();\n\t\tfor (const r of refs) byNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r]);\n\t\tconst nodes = mapTree(doc.nodes, (n) => {\n\t\t\tconst list = byNode.get(n.id);\n\t\t\tif (!list || n.type !== 'path' || n.locked) return n;\n\t\t\tconst subpaths = n.subpaths.map((sp, s) => {\n\t\t\t\tconst hits = list.filter((r) => r.subpath === s);\n\t\t\t\tif (!hits.length) return sp;\n\t\t\t\treturn { closed: sp.closed, anchors: sp.anchors.map((a, i) => (hits.some((r) => r.index === i) ? fn(a, { nodeId: n.id, subpath: s, index: i }) : a)) };\n\t\t\t});\n\t\t\treturn { ...n, subpaths };\n\t\t});\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\t/** Moves anchors by a document-space offset (converted into each node's own space). */\n\tprivate movedAnchors(doc: VectorDocument, refs: readonly VectorAnchorRef[], dx: number, dy: number): VectorDocument {\n\t\tconst local = new Map<string, Vec2>();\n\t\tfor (const r of refs) if (!local.has(r.nodeId)) local.set(r.nodeId, applyMatrixLinear(invertMatrix(this.worldOf(r.nodeId, doc)), { x: dx, y: dy }));\n\t\treturn this.updateAnchors(doc, refs, (a, ref) => {\n\t\t\tconst d = local.get(ref.nodeId)!;\n\t\t\treturn translateAnchor(a, d.x, d.y);\n\t\t});\n\t}\n\n\t/**\n\t * Moves one anchor to a document position. Its handles follow; with `curvature` (default:\n\t * the `curvatureMoves` setting) its two segments bend instead, as the Curvature tool does.\n\t */\n\tmoveAnchor(ref: VectorAnchorRef, to: Vec2, options: { curvature?: boolean } = {}): VectorActionResult {\n\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\tif (!a) return { ok: false, message: 'There is no such anchor.' };\n\t\tconst curvature = options.curvature ?? this.editing.curvatureMoves;\n\t\tthis.change('Move Point', () => {\n\t\t\tthis.doc = curvature ? this.curvatureMoved(this.doc, ref, to) : this.movedAnchors(this.doc, [ref], to.x - a.x, to.y - a.y);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** `doc` with anchor `ref` moved to document point `to` by a Curvature-tool move. */\n\tprivate curvatureMoved(doc: VectorDocument, ref: VectorAnchorRef, to: Vec2): VectorDocument {\n\t\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\t\tif (node?.type !== 'path' || node.locked || !node.subpaths[ref.subpath]) return doc;\n\t\tconst q = this.toLocal(ref.nodeId, to, doc);\n\t\tconst subpaths = node.subpaths.map((sp, i) => (i === ref.subpath ? curvatureMoveAnchor(sp, ref.index, q) : sp));\n\t\tconst nodes = mapTree(doc.nodes, (n) => (n.id === ref.nodeId ? { ...node, subpaths } : n));\n\t\treturn { ...doc, nodes };\n\t}\n\n\t/** `doc` with segment `ref` bent through document point `p` at parameter `t`. */\n\tprivate bent(doc: VectorDocument, ref: VectorSegmentRef, t: number, p: Vec2): VectorDocument {\n\t\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\t\tif (node?.type !== 'path' || node.locked || !node.subpaths[ref.subpath]) return doc;\n\t\tconst q = this.toLocal(ref.nodeId, p, doc);\n\t\tconst subpaths = node.subpaths.map((sp, i) => (i === ref.subpath ? bendSubpathSegment(sp, ref.segment, t, q) : sp));\n\t\treturn { ...doc, nodes: mapTree(doc.nodes, (n) => (n.id === ref.nodeId ? { ...node, subpaths } : n)) };\n\t}\n\n\t/**\n\t * Bends a segment so the curve passes through document point `to` at parameter `t`\n\t * (default 0.5, clamped to 0.05–0.95); see `bendSegment` in `pathEdit`.\n\t */\n\tbendSegment(ref: VectorSegmentRef, to: Vec2, t = 0.5): VectorActionResult {\n\t\tconst node = this.getNode(ref.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[ref.subpath] : undefined;\n\t\tif (!sp || ref.segment < 0 || ref.segment >= (sp.closed ? sp.anchors.length : sp.anchors.length - 1) || sp.anchors.length < 2) return { ok: false, message: 'There is no such segment.' };\n\t\tif (node!.locked) return { ok: false, message: 'The path is locked.' };\n\t\tthis.change('Bend Segment', () => {\n\t\t\tthis.doc = this.bent(this.doc, ref, t, to);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Moves one handle to a document position (see `moveAnchorHandle` for how the opposite handle follows). */\n\tmoveHandle(ref: VectorHandleRef, to: Vec2, options: { breakHandles?: boolean } = {}): VectorActionResult {\n\t\tif (!getAnchor(this.doc, ref)) return { ok: false, message: 'There is no such anchor.' };\n\t\tconst local = this.toLocal(ref.nodeId, to);\n\t\tthis.change('Move Handle', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, [ref], (a) => moveAnchorHandle(a, ref.handle, local, options.breakHandles));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Converts the selected (or given) anchors between corner, smooth and symmetric. */\n\tconvertAnchors(type: VectorAnchorType, refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tif (!refs.length) return { ok: false, message: 'Select points to convert.' };\n\t\tthis.change(type === 'corner' ? 'Make Corner' : 'Make Smooth', () => {\n\t\t\tconst nodes = mapTree(this.doc.nodes, (n) => {\n\t\t\t\tif (n.type !== 'path') return n;\n\t\t\t\tconst mine = refs.filter((r) => r.nodeId === n.id);\n\t\t\t\tif (!mine.length) return n;\n\t\t\t\tconst subpaths = n.subpaths.map((sp, s) => mine.filter((r) => r.subpath === s).reduce((acc, r) => convertAnchor(acc, r.index, type), sp));\n\t\t\t\treturn { ...n, subpaths };\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Adds an anchor on the nearest segment of `nodeId` to document point `point` (shape unchanged). */\n\tinsertAnchorAt(nodeId: string, point: Vec2): VectorAnchorRef | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path') return null;\n\t\tconst hit = nearestSegment(node, this.toLocal(nodeId, point));\n\t\tif (!hit) return null;\n\t\tconst { subpath, index } = insertAnchor(node.subpaths[hit.subpath], hit.segment, hit.t);\n\t\tconst ref = { nodeId, subpath: hit.subpath, index };\n\t\tthis.change('Add Point', () => {\n\t\t\tthis.replaceNode(nodeId, { ...node, subpaths: node.subpaths.map((sp, i) => (i === hit.subpath ? subpath : sp)) });\n\t\t\tthis.editingId = nodeId;\n\t\t\tthis.anchors = [ref];\n\t\t});\n\t\treturn ref;\n\t}\n\n\t/**\n\t * Deletes the selected (or given) anchors; subpaths left with one anchor and empty paths go\n\t * too. With `keepShape` (default: the `keepShapeOnDelete` setting, on) the neighbours'\n\t * handles are refitted so the path keeps its shape; off, the neighbours are joined as they are.\n\t */\n\tdeleteAnchors(refs: readonly VectorAnchorRef[] = this.anchors, options: { keepShape?: boolean } = {}): VectorActionResult {\n\t\tif (!refs.length) return { ok: false, message: 'Select points to delete.' };\n\t\tconst keepShape = options.keepShape ?? this.editing.keepShapeOnDelete;\n\t\tthis.change('Delete Points', () => {\n\t\t\tconst nodes = mapTree(this.doc.nodes, (n) => {\n\t\t\t\tif (n.type !== 'path' || n.locked) return n;\n\t\t\t\tconst mine = refs.filter((r) => r.nodeId === n.id);\n\t\t\t\tif (!mine.length) return n;\n\t\t\t\tconst subpaths = n.subpaths\n\t\t\t\t\t.map((sp, s) => {\n\t\t\t\t\t\tconst indices = mine.filter((r) => r.subpath === s).map((r) => r.index);\n\t\t\t\t\t\tif (!indices.length) return sp;\n\t\t\t\t\t\treturn keepShape ? removeAnchorsKeepingShape(sp, indices) : removeAnchors(sp, indices);\n\t\t\t\t\t})\n\t\t\t\t\t.filter((sp) => sp.anchors.length > 1);\n\t\t\t\treturn subpaths.length ? { ...n, subpaths } : null;\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.anchors = [];\n\t\t\tthis.selection = this.selection.filter((id) => this.getNode(id));\n\t\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Opens or closes the subpaths that contain selected anchors (or all subpaths of `nodeId`). */\n\tsetClosed(closed: boolean, nodeId?: string): VectorActionResult {\n\t\tconst targets = nodeId\n\t\t\t? (() => {\n\t\t\t\t\tconst n = this.getNode(nodeId);\n\t\t\t\t\treturn n?.type === 'path' ? n.subpaths.map((_, s) => ({ nodeId, subpath: s })) : [];\n\t\t\t\t})()\n\t\t\t: this.anchors.map((r) => ({ nodeId: r.nodeId, subpath: r.subpath }));\n\t\tif (!targets.length) return { ok: false, message: 'Select a path or points.' };\n\t\tthis.change(closed ? 'Close Path' : 'Open Path', () => {\n\t\t\tthis.setDoc(\n\t\t\t\tmapTree(this.doc.nodes, (n) =>\n\t\t\t\t\tn.type === 'path' && targets.some((t) => t.nodeId === n.id)\n\t\t\t\t\t\t? { ...n, subpaths: n.subpaths.map((sp, s) => (targets.some((t) => t.nodeId === n.id && t.subpath === s) ? { ...sp, closed } : sp)) }\n\t\t\t\t\t\t: n\n\t\t\t\t)\n\t\t\t);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Reverses the direction of every subpath of the selected paths. */\n\treversePaths(ids: readonly string[] = this.selection): VectorActionResult {\n\t\tconst set = new Set(ids.flatMap((id) => (this.getNode(id) ? collectPathNodes(this.getNode(id)!) : [])).map((p) => p.id));\n\t\tif (!set.size) return { ok: false, message: 'Select a path.' };\n\t\tthis.change('Reverse Path', () => {\n\t\t\tthis.setDoc(\n\t\t\t\tmapTree(this.doc.nodes, (n) =>\n\t\t\t\t\tn.type === 'path' && set.has(n.id)\n\t\t\t\t\t\t? { ...n, subpaths: n.subpaths.map(reverseSubpath), ...(n.strokeWidthProfile?.length ? { strokeWidthProfile: reverseWidthProfile(n.strokeWidthProfile) } : {}) }\n\t\t\t\t\t\t: n\n\t\t\t\t)\n\t\t\t);\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Path clean-up, Scissors, Knife and Eraser\n\t// -------------------------------------------------------------------------\n\n\t/** Unlocked path nodes in the given roots (default: the paths being edited, else the selection). */\n\tprivate pathTargets(ids?: readonly string[]): VectorPathNode[] {\n\t\tconst roots = ids ?? (this.tool === 'direct' && this.anchors.length ? [...new Set(this.anchors.map((r) => r.nodeId))] : this.selection);\n\t\tconst out = new Map<string, VectorPathNode>();\n\t\tfor (const id of roots) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) out.set(p.id, p);\n\t\t}\n\t\t// Document order, bottom to top.\n\t\tconst order: string[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (out.has(n.id)) order.push(n.id);\n\t\t});\n\t\treturn order.map((id) => out.get(id)!);\n\t}\n\n\t/** Subpaths of node `from` mapped into node `to`'s own space. */\n\tprivate subpathsIn(from: VectorPathNode, to: string): VectorSubpath[] {\n\t\tconst m = multiplyMatrices(this.worldOf(from.id), invertMatrix(this.worldOf(to)));\n\t\tif (isRoot(m)) return from.subpaths;\n\t\tconst map = (p: Vec2) => applyMatrix(m, p);\n\t\treturn from.subpaths.map((sp) => ({\n\t\t\tclosed: sp.closed,\n\t\t\tanchors: sp.anchors.map((a) => ({ ...map(a), ...(a.in ? { in: map(a.in) } : {}), ...(a.out ? { out: map(a.out) } : {}), ...(a.type ? { type: a.type } : {}), ...(a.corner ? { corner: { ...a.corner } } : {}) }))\n\t\t}));\n\t}\n\n\t/**\n\t * Replaces a path with pieces: each entry becomes one path (the first keeps the node's id and\n\t * place, the others go just above it with the same style). No pieces removes the path.\n\t * Returns the ids of the paths now standing in for it.\n\t */\n\tprivate replaceWithPieces(node: VectorPathNode, pieces: readonly VectorSubpath[][]): string[] {\n\t\tconst nodes = pieces.filter((p) => p.length).map((subpaths, i) => ({ ...node, id: i === 0 ? node.id : this.newId(), subpaths }) as VectorPathNode);\n\t\tthis.setDoc(spliceTree(this.doc.nodes, node.id, nodes));\n\t\treturn nodes.map((n) => n.id);\n\t}\n\n\t/** Clears anchor selections, editing and pen state that no longer point at anything. */\n\tprivate dropStaleRefs() {\n\t\tthis.selection = this.selection.filter((id) => this.getNode(id));\n\t\tthis.anchors = this.anchors.filter((r) => getAnchor(this.doc, r));\n\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t}\n\n\t/**\n\t * Join: the open subpaths of the selected (or given) paths become one open path, joined\n\t * nearest endpoints first (ends within `tolerance` document units merge into one anchor,\n\t * others get a straight segment); a single open subpath is closed. The result replaces the\n\t * lowest path, in its space and style. Default tolerance: the pick distance.\n\t */\n\tjoinPaths(options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst paths = this.pathTargets(options.ids);\n\t\tif (!paths.length) return { ok: false, message: 'Select paths to join.' };\n\t\tconst base = paths[0];\n\t\tconst all = paths.flatMap((p) => this.subpathsIn(p, base.id));\n\t\tif (!all.some((sp) => !sp.closed && sp.anchors.length > 1)) return { ok: false, message: 'There are no open paths to join.' };\n\t\tconst subpaths = joinSubpaths(all, options.tolerance ?? this.tolerance());\n\t\tconst drop = new Set(paths.slice(1).map((p) => p.id));\n\t\tthis.change('Join', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === base.id ? { ...base, subpaths } : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [base.id];\n\t\t\tthis.anchors = [];\n\t\t\tif (this.editingId && drop.has(this.editingId)) this.editingId = base.id;\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Average: moves the selected (or given) anchors onto their average position along `axis`, in document space. */\n\taverageAnchors(axis: VectorAverageAxis = 'both', refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tconst points = refs.map((r) => ({ ref: r, at: getAnchorWorld(this.doc, r) })).filter((p): p is { ref: VectorAnchorRef; at: NonNullable<ReturnType<typeof getAnchorWorld>> } => !!p.at);\n\t\tif (points.length < 2) return { ok: false, message: 'Select at least two points to average.' };\n\t\tconst cx = points.reduce((s, p) => s + p.at.x, 0) / points.length;\n\t\tconst cy = points.reduce((s, p) => s + p.at.y, 0) / points.length;\n\t\tthis.change('Average', () => {\n\t\t\tfor (const { ref, at } of points) {\n\t\t\t\tconst dx = axis === 'horizontal' ? 0 : cx - at.x;\n\t\t\t\tconst dy = axis === 'vertical' ? 0 : cy - at.y;\n\t\t\t\tif (dx || dy) this.doc = this.movedAnchors(this.doc, [ref], dx, dy);\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies `fn` to every subpath of the target paths as one undo step. */\n\tprivate editSubpaths(label: string, ids: readonly string[] | undefined, fn: (sp: VectorSubpath, node: VectorPathNode, index: number) => VectorSubpath): VectorActionResult {\n\t\tconst paths = this.pathTargets(ids);\n\t\tif (!paths.length) return { ok: false, message: 'Select a path.' };\n\t\tconst set = new Set(paths.map((p) => p.id));\n\t\tthis.change(label, () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.type === 'path' && set.has(n.id) ? { ...n, subpaths: n.subpaths.map((sp, i) => fn(sp, n, i)) } : n)));\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Remove Redundant Points: drops anchors of the selected (or given) paths that can go\n\t * without moving the outline more than `tolerance` document units (default 0.5).\n\t */\n\tremoveRedundantPoints(options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst tolerance = options.tolerance ?? 0.5;\n\t\treturn this.editSubpaths('Remove Redundant Points', options.ids, (sp) => removeRedundantSubpathPoints(sp, tolerance));\n\t}\n\n\t/**\n\t * Smooth: pulls handles towards smooth tangents by `amount` (0–1, default 1). With the direct\n\t * tool and points selected, only those points change.\n\t */\n\tsmoothPaths(options: { ids?: readonly string[]; amount?: number; refs?: readonly VectorAnchorRef[] } = {}): VectorActionResult {\n\t\tconst refs = options.refs ?? (!options.ids && this.tool === 'direct' && this.anchors.length ? this.anchors : null);\n\t\tconst ids = options.ids ?? (refs ? [...new Set(refs.map((r) => r.nodeId))] : undefined);\n\t\treturn this.editSubpaths('Smooth', ids, (sp, node, i) => {\n\t\t\tconst only = refs ? new Set(refs.filter((r) => r.nodeId === node.id && r.subpath === i).map((r) => r.index)) : undefined;\n\t\t\treturn only && !only.size ? sp : smoothSubpath(sp, options.amount ?? 1, only);\n\t\t});\n\t}\n\n\t/** Splits a cut subpath into pieces: separate paths for a one-subpath node, subpaths in place for a compound one. */\n\tprivate applyCuts(node: VectorPathNode, cut: (sp: VectorSubpath, index: number) => VectorSubpath[] | null): string[] | null {\n\t\tconst results = node.subpaths.map((sp, i) => cut(sp, i));\n\t\tif (results.every((r) => !r)) return null;\n\t\tconst subpaths = node.subpaths.flatMap((sp, i) => results[i] ?? [sp]);\n\t\tif (node.subpaths.length === 1) return this.replaceWithPieces(node, subpaths.map((sp) => [sp]));\n\t\tthis.replaceNode(node.id, { ...node, subpaths });\n\t\treturn [node.id];\n\t}\n\n\t/**\n\t * Scissors: cuts path `nodeId` at the outline point nearest document point `point` (at an\n\t * anchor when within the pick distance of one). A closed subpath opens there; an open one\n\t * splits in two (a one-subpath path becomes two paths). Returns the ids of the paths.\n\t */\n\tcutPathAt(nodeId: string, point: Vec2): string[] | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path' || node.locked) return null;\n\t\tconst local = this.toLocal(nodeId, point);\n\t\tconst hit = nearestSegment(node, local);\n\t\tif (!hit) return null;\n\t\tconst sp = node.subpaths[hit.subpath];\n\t\tconst n = sp.anchors.length;\n\t\tconst near = [hit.segment, (hit.segment + 1) % n].find((i) => Math.hypot(sp.anchors[i].x - hit.point.x, sp.anchors[i].y - hit.point.y) <= this.tolerance());\n\t\tif (!sp.closed && n > 1 && (near === 0 || near === n - 1) && !(hit.t > 1e-6 && hit.t < 1 - 1e-6)) return null;\n\t\tlet ids: string[] | null = null;\n\t\tthis.change('Cut Path', () => {\n\t\t\tids = this.applyCuts(node, (s, i) => (i !== hit.subpath ? null : near !== undefined ? cutSubpathAt(s, [near]) : splitSubpathAt(s, hit.segment, hit.t)));\n\t\t\tif (ids) {\n\t\t\t\tthis.selection = ids;\n\t\t\t\tthis.anchors = [];\n\t\t\t\tif (this.editingId === nodeId) this.editingId = null;\n\t\t\t}\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn ids;\n\t}\n\n\t/** Scissors on the selected (or given) anchors: each cuts its subpath there (see `cutPathAt`). */\n\tcutAtAnchors(refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tconst byNode = new Map<string, VectorAnchorRef[]>();\n\t\tfor (const r of refs) if (getAnchor(this.doc, r)) byNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r]);\n\t\tif (!byNode.size) return { ok: false, message: 'Select points to cut at.' };\n\t\tconst created: string[] = [];\n\t\tthis.change('Cut Path', () => {\n\t\t\tfor (const [id, list] of byNode) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\tif (node.locked) continue;\n\t\t\t\tconst ids = this.applyCuts(node, (sp, i) => {\n\t\t\t\t\tconst at = list.filter((r) => r.subpath === i).map((r) => r.index);\n\t\t\t\t\tconst pieces = at.length ? cutSubpathAt(sp, at) : null;\n\t\t\t\t\treturn pieces && !(pieces.length === 1 && pieces[0].closed === sp.closed) ? pieces : null;\n\t\t\t\t});\n\t\t\t\tif (ids) created.push(...ids);\n\t\t\t}\n\t\t\tif (created.length) this.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn created.length ? { ok: true } : { ok: false, message: 'Points at the ends of open paths do not cut.' };\n\t}\n\n\t/** Visible, unlocked paths a stroke over `points` can reach: in `ids`, the selection, or (with neither) any whose bounds it crosses. */\n\tprivate strokeTargets(points: readonly Vec2[], ids: readonly string[] | undefined, pad: number): VectorPathNode[] {\n\t\tconst blocked = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n, parent) => {\n\t\t\tif (n.visible === false || n.locked || (parent && blocked.has(parent.id))) blocked.add(n.id);\n\t\t});\n\t\tconst visible = (p: VectorPathNode) => !blocked.has(p.id);\n\t\tif (ids?.length || this.selection.length) return this.pathTargets(ids ?? this.selection).filter(visible);\n\t\tconst box = polylineBounds(points.map(toPoint), pad);\n\t\tif (!box) return [];\n\t\tconst out: VectorPathNode[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || !visible(n)) return;\n\t\t\tconst b = vectorNodeBounds(n, vectorParentMatrix(this.doc.nodes, n.id) ?? IDENTITY_MATRIX);\n\t\t\tif (b && boundsIntersect(b, box)) out.push(n);\n\t\t});\n\t\treturn out;\n\t}\n\n\t/** A stroke's points in node `id`'s own space. */\n\tprivate localPoints(id: string, points: readonly Vec2[]): Point[] {\n\t\tconst inv = invertMatrix(this.worldOf(id));\n\t\treturn points.map((p) => toPoint(applyMatrix(inv, p)));\n\t}\n\n\t/**\n\t * Knife: cuts closed paths along the polyline `points` (document space) wherever it crosses\n\t * them from edge to edge, with no gap between the pieces. It cuts the given paths, the\n\t * selection, or (with neither) every path it crosses. Returns the ids of the pieces (empty\n\t * when nothing was cut).\n\t */\n\tknife(points: readonly Vec2[], options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst pts = simplifyPolyline(points.map(toPoint), 0.25 / this.viewport.zoom).map(([x, y]) => ({ x, y }));\n\t\tif (pts.length < 2) return [];\n\t\tconst plan: { node: VectorPathNode; pieces: VectorSubpath[][] }[] = [];\n\t\tfor (const node of this.strokeTargets(pts, options.ids, 0)) {\n\t\t\tconst closed = node.subpaths.filter((sp) => sp.anchors.length > 1);\n\t\t\tif (!closed.length || closed.some((sp) => !sp.closed)) continue;\n\t\t\tconst result = knifePath(subpathsToBezier(closed), node.fillRule ?? 'nonzero', this.localPoints(node.id, pts));\n\t\t\tif (result) plan.push({ node, pieces: result.map((path) => bezierToSubpaths(path)) });\n\t\t}\n\t\tif (!plan.length) return [];\n\t\tconst created: string[] = [];\n\t\tthis.change('Knife', () => {\n\t\t\tfor (const { node, pieces } of plan) created.push(...this.replaceWithPieces(node, pieces));\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn created;\n\t}\n\n\t/**\n\t * Eraser: rubs out a round stroke of diameter `size` (default: the `eraserSize` setting)\n\t * along `points` (document space). Filled closed paths lose that area (pieces that come\n\t * apart become separate paths); outlines are cut where they pass under it. It erases from\n\t * the given paths, the selection, or (with neither) every path it reaches. Returns the ids\n\t * of the paths it changed or created.\n\t */\n\terase(points: readonly Vec2[], options: { ids?: readonly string[]; size?: number } = {}): string[] {\n\t\tconst width = options.size ?? this.editing.eraserSize;\n\t\tif (!(width > 0) || !points.length) return [];\n\t\tconst pts = simplifyPolyline(points.map(toPoint), Math.min(width * 0.05, 0.25 / this.viewport.zoom));\n\t\tconst region = eraserRegion(pts, width);\n\t\tif (!region.length) return [];\n\t\tconst plan: { node: VectorPathNode; pieces: VectorSubpath[][] }[] = [];\n\t\tconst rb = bezierPathBounds(region);\n\t\tconst reach = rb ? [{ x: rb.minX, y: rb.minY }, { x: rb.maxX, y: rb.maxY }] : points;\n\t\tfor (const node of this.strokeTargets(reach, options.ids, 0)) {\n\t\t\tconst local = transformBezierPath(region, invertMatrix(this.worldOf(node.id)));\n\t\t\tconst live = node.subpaths.filter((sp) => sp.anchors.length > 1);\n\t\t\tif (!live.length) continue;\n\t\t\tif (hasPaint(node.fill) && live.every((sp) => sp.closed)) {\n\t\t\t\tconst faces = eraseFromFill(subpathsToBezier(live), node.fillRule ?? 'nonzero', local);\n\t\t\t\tif (faces) plan.push({ node, pieces: faces.map((f) => bezierToSubpaths(f)) });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst results = live.map((sp) => eraseFromOutline(sp, local));\n\t\t\tif (results.every((r) => !r)) continue;\n\t\t\tconst subpaths = live.flatMap((sp, i) => results[i] ?? [sp]);\n\t\t\tplan.push({ node, pieces: live.length === 1 ? subpaths.map((sp) => [sp]) : [subpaths] });\n\t\t}\n\t\tif (!plan.length) return [];\n\t\tconst changed: string[] = [];\n\t\tthis.change('Erase', () => {\n\t\t\tfor (const { node, pieces } of plan) changed.push(...this.replaceWithPieces(node, pieces));\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t\tif (this.selection.length || options.ids) this.selection = [...new Set([...this.selection, ...changed.filter((id) => this.getNode(id))])];\n\t\t});\n\t\treturn changed;\n\t}\n\n\t/** Ends the pen path being drawn (a lone anchor is removed). */\n\tfinishPath(): void {\n\t\tif (!this.pen) return;\n\t\tconst node = this.getNode(this.pen.nodeId) as VectorPathNode | undefined;\n\t\tconst sp = node?.subpaths[this.pen.subpath];\n\t\tconst pen = this.pen;\n\t\tthis.pen = null;\n\t\tthis.pointer = null;\n\t\tif (node && sp && sp.anchors.length < 2) {\n\t\t\tconst subpaths = node.subpaths.filter((_, i) => i !== pen.subpath);\n\t\t\tthis.change('Delete Path', () => {\n\t\t\t\tthis.replaceNode(node.id, subpaths.length ? { ...node, subpaths } : null);\n\t\t\t\tif (!subpaths.length) {\n\t\t\t\t\tthis.selection = this.selection.filter((id) => id !== node.id);\n\t\t\t\t\tif (this.editingId === node.id) this.editingId = null;\n\t\t\t\t}\n\t\t\t\tthis.anchors = [];\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis.notify();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Clipboard\n\t// -------------------------------------------------------------------------\n\n\t/** Copies the selection. Returns JSON text for the system clipboard (or null). */\n\tcopy(): string | null {\n\t\tconst nodes = this.selectedRoots()\n\t\t\t.map((id) => this.getNode(id))\n\t\t\t.filter((n): n is VectorNode => !!n)\n\t\t\t.map((n) => cloneVectorNode(n));\n\t\tif (!nodes.length) return null;\n\t\tthis.clipboard = nodes;\n\t\treturn JSON.stringify({ type: VECTOR_CLIPBOARD_TYPE, nodes });\n\t}\n\n\tcut(): string | null {\n\t\tconst text = this.copy();\n\t\tif (text) this.removeNodes(this.selectedRoots(), { label: 'Cut' });\n\t\treturn text;\n\t}\n\n\t/**\n\t * Pastes `text` (from `copy()`, or SVG markup) or the internal clipboard, offset by 10, 10.\n\t * Returns the new ids.\n\t */\n\tpaste(text?: string, options: { offset?: Vec2 } = {}): string[] {\n\t\tlet nodes: VectorNode[] | null = null;\n\t\tif (text) {\n\t\t\tconst trimmed = text.trim();\n\t\t\tif (trimmed.startsWith('{')) {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(trimmed);\n\t\t\t\t\tif (data?.type === VECTOR_CLIPBOARD_TYPE && Array.isArray(data.nodes)) nodes = data.nodes;\n\t\t\t\t} catch {\n\t\t\t\t\tnodes = null;\n\t\t\t\t}\n\t\t\t} else if (/<svg[\\s>]/i.test(trimmed)) {\n\t\t\t\ttry {\n\t\t\t\t\tnodes = parseVectorSvg(trimmed).nodes;\n\t\t\t\t} catch {\n\t\t\t\t\tnodes = null;\n\t\t\t\t}\n\t\t\t}\n\t\t} else nodes = this.clipboard;\n\t\tif (!nodes?.length) return [];\n\t\tconst offset = options.offset ?? (text && !text.trim().startsWith('{') ? { x: 0, y: 0 } : { x: 10, y: 10 });\n\t\tconst copies = nodes.map((n) => transformVectorNode(this.freshIds(n), translateMatrix(offset.x, offset.y)));\n\t\tthis.change('Paste', () => {\n\t\t\tthis.setDoc([...this.doc.nodes, ...copies]);\n\t\t\tthis.selection = copies.map((n) => n.id);\n\t\t\tthis.anchors = [];\n\t\t});\n\t\tif (!text) this.clipboard = copies.map((n) => cloneVectorNode(n));\n\t\treturn copies.map((n) => n.id);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Undo\n\t// -------------------------------------------------------------------------\n\n\tundo(): boolean {\n\t\tthis.cancelDrag();\n\t\tthis.pen = null;\n\t\treturn this.history.undo();\n\t}\n\n\tredo(): boolean {\n\t\tthis.cancelDrag();\n\t\treturn this.history.redo();\n\t}\n\n\t/** Deletes selected anchors (direct tool) or nodes. */\n\tdeleteSelection(): VectorActionResult {\n\t\tif (this.tool === 'direct' && this.anchors.length) return this.deleteAnchors();\n\t\treturn this.removeNodes(this.selectedRoots());\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Pointer input\n\t// -------------------------------------------------------------------------\n\n\t/** The fields the anchor / handle helpers read, without building a full state. */\n\tprivate view() {\n\t\treturn { document: this.doc, selection: this.selection, editingId: this.editingId, tool: this.tool, pen: this.pen, selectedAnchors: this.anchors };\n\t}\n\n\tprivate tolerance() {\n\t\treturn this.hitRadius / this.viewport.zoom;\n\t}\n\n\tprivate hitTransformHandle(screen: Vec2): VectorTransformHandle | null {\n\t\tif (this.tool !== 'select' || !this.selection.length) return null;\n\t\tconst frame = this.frameOf(this.selectedRoots());\n\t\tif (!frame) return null;\n\t\tconst { box, handles } = getVectorSelectionBoxGeometry(frame, this.viewport);\n\t\tconst r = this.hitRadius + 2;\n\t\t// Tiny boxes: only corners and rotation, so the box can still be grabbed.\n\t\tconst usable = box.width < 2 * r || box.height < 2 * r ? handles.filter((h) => h.handle.length === 2 || h.handle === 'rotate') : handles;\n\t\tfor (const h of usable) if (Math.hypot(h.screen.x - screen.x, h.screen.y - screen.y) <= r * Math.SQRT2) return h.handle;\n\t\treturn null;\n\t}\n\n\tprivate hitHandle(screen: Vec2): VectorHandleRef | null {\n\t\tfor (const ref of getVisibleHandles(this.view()).reverse()) {\n\t\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\t\tconst h = a?.[ref.handle];\n\t\t\tif (!h) continue;\n\t\t\tconst s = this.documentToScreen(h);\n\t\t\tif (Math.hypot(s.x - screen.x, s.y - screen.y) <= this.hitRadius) return ref;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate cornerView() {\n\t\treturn { ...this.view(), viewport: this.viewport };\n\t}\n\n\tprivate hitCornerWidget(screen: Vec2): VectorCornerWidget | null {\n\t\tlet best: VectorCornerWidget | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const w of getVectorCornerWidgets(this.cornerView())) {\n\t\t\tconst s = this.documentToScreen(w);\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\tif (d <= this.hitRadius && d < bestD) {\n\t\t\t\tbest = w;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\tprivate hitAnchor(screen: Vec2, refs: readonly VectorAnchorRef[]): VectorAnchorRef | null {\n\t\tlet best: VectorAnchorRef | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const ref of refs) {\n\t\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\t\tif (!a) continue;\n\t\t\tconst s = this.documentToScreen(a);\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\tif (d <= this.hitRadius && d < bestD) {\n\t\t\t\tbest = ref;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** Deepest unlocked visible path under `p`. */\n\t/** Live groups being edited (selected, or holding the selection or the edited path): their children are hit as stored. */\n\tprivate enteredGroups(): Set<string> {\n\t\treturn vectorEnteredGroups(this.doc.nodes, this.editingId ? [...this.selection, this.editingId] : this.selection);\n\t}\n\n\tprivate hitPath(p: Vec2): VectorPathNode | null {\n\t\tconst tol = this.tolerance();\n\t\tconst entered = this.enteredGroups();\n\t\tconst search = (list: readonly VectorNode[], parent: AffineMatrix): VectorPathNode | null => {\n\t\t\tfor (let i = list.length - 1; i >= 0; i--) {\n\t\t\t\tconst n = list[i];\n\t\t\t\tif (n.visible === false || n.locked) continue;\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\t// A live group not being edited is hit where it draws (a click in a subtracted\n\t\t\t\t\t// hole goes through), then picks the child under the pointer.\n\t\t\t\t\tif (hasOwnVectorAppearance(n) && !entered.has(n.id) && !hitTestVectorNode(n, p, tol, parent, { entered })) continue;\n\t\t\t\t\tconst found = search(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (found) return found;\n\t\t\t\t} else if (hitTestVectorNode(n, p, tol, parent, { entered })) return n;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\t\treturn search(this.doc.nodes, IDENTITY_MATRIX);\n\t}\n\n\t/** Endpoints of open subpaths of unlocked visible paths (pen tool resumes from them). */\n\tprivate openEndpoints(): VectorAnchorRef[] {\n\t\tconst out: VectorAnchorRef[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || n.locked || n.visible === false) return;\n\t\t\tn.subpaths.forEach((sp, s) => {\n\t\t\t\tif (sp.closed || sp.anchors.length < 1) return;\n\t\t\t\tout.push({ nodeId: n.id, subpath: s, index: 0 });\n\t\t\t\tif (sp.anchors.length > 1) out.push({ nodeId: n.id, subpath: s, index: sp.anchors.length - 1 });\n\t\t\t});\n\t\t});\n\t\treturn out;\n\t}\n\n\tprivate computeHover(screen: Vec2): VectorHover | null {\n\t\tconst p = this.screenToDocument(screen);\n\t\tswitch (this.tool) {\n\t\t\tcase 'select': {\n\t\t\t\tconst handle = this.hitTransformHandle(screen);\n\t\t\t\tif (handle) return { nodeId: null, transformHandle: handle };\n\t\t\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance(), { entered: this.enteredGroups() });\n\t\t\t\treturn node ? { nodeId: node.id } : null;\n\t\t\t}\n\t\t\tcase 'direct': {\n\t\t\t\tconst handle = this.hitHandle(screen);\n\t\t\t\tif (handle) return { nodeId: handle.nodeId, handle };\n\t\t\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\t\t\tif (anchor) return { nodeId: anchor.nodeId, anchor };\n\t\t\t\tconst widget = this.hitCornerWidget(screen);\n\t\t\t\tif (widget) return { nodeId: widget.ref.nodeId, corner: widget.ref };\n\t\t\t\tfor (const id of getEditablePathIds(this.view())) {\n\t\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\t\tconst seg = nearestSegment(node, this.toLocal(id, p));\n\t\t\t\t\tif (seg && seg.distance <= this.tolerance()) {\n\t\t\t\t\t\tconst point = applyMatrix(this.worldOf(id), seg.point);\n\t\t\t\t\t\treturn { nodeId: id, segment: { nodeId: id, subpath: seg.subpath, segment: seg.segment, t: seg.t, point } };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst path = this.hitPath(p);\n\t\t\t\treturn path ? { nodeId: path.id } : null;\n\t\t\t}\n\t\t\tcase 'pen': {\n\t\t\t\tconst refs = this.pen ? [{ nodeId: this.pen.nodeId, subpath: this.pen.subpath, index: 0 }] : this.openEndpoints();\n\t\t\t\tconst anchor = this.hitAnchor(screen, refs);\n\t\t\t\treturn anchor ? { nodeId: anchor.nodeId, anchor } : null;\n\t\t\t}\n\t\t\tcase 'scissors': {\n\t\t\t\tconst seg = this.nearestOutline(p);\n\t\t\t\treturn seg ? { nodeId: seg.nodeId, segment: seg } : null;\n\t\t\t}\n\t\t\tcase 'blend': {\n\t\t\t\tconst hit = this.blendHit(screen, p);\n\t\t\t\tif (!hit) return null;\n\t\t\t\treturn hit.anchor === null ? { nodeId: hit.nodeId } : { nodeId: hit.nodeId, anchor: { nodeId: hit.nodeId, subpath: 0, index: hit.anchor } };\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tconst hit = this.hitWidthHandle(screen);\n\t\t\t\tif (hit) return { nodeId: hit.ref.nodeId, widthPoint: hit.ref };\n\t\t\t\tconst spot = this.strokeSpotAt(p);\n\t\t\t\treturn spot ? { nodeId: spot.nodeId, strokeSpot: spot } : null;\n\t\t\t}\n\t\t\tcase 'gradient': {\n\t\t\t\tconst a = this.getGradientAnnotator();\n\t\t\t\tconst part = a ? hitVectorGradientAnnotator(a, screen) : null;\n\t\t\t\tif (a && part) return { nodeId: a.nodeId, gradient: part };\n\t\t\t\tconst path = this.hitPath(p);\n\t\t\t\treturn path ? { nodeId: path.id } : null;\n\t\t\t}\n\t\t\tcase 'envelope': {\n\t\t\t\tconst hit = this.hitEnvelope(screen, p);\n\t\t\t\tif (hit) return { nodeId: hit.target.node.id, envelope: { nodeId: hit.target.node.id, index: hit.index } };\n\t\t\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance(), { entered: this.enteredGroups() });\n\t\t\t\treturn node ? { nodeId: node.id } : null;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate widthView(): Pick<VectorEditorState, 'document' | 'selection' | 'tool' | 'hover' | 'interaction' | 'selectedWidthPoints'> {\n\t\treturn { document: this.doc, selection: this.selection, tool: this.tool, hover: this.hover, interaction: this.interaction, selectedWidthPoints: this.widthPoints };\n\t}\n\n\t/** The width point centre or side end under `screen` (width tool). */\n\tprivate hitWidthHandle(screen: Vec2): { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null {\n\t\tconst shown = this.hitWidthHandleIn(screen, this.widthView());\n\t\tif (shown) return shown;\n\t\t// The points of the stroke under the pointer, when no hover has shown them yet.\n\t\tconst spot = this.strokeSpotAt(this.screenToDocument(screen));\n\t\treturn spot && spot.nodeId !== this.hover?.nodeId ? this.hitWidthHandleIn(screen, { ...this.widthView(), hover: { nodeId: spot.nodeId } }) : null;\n\t}\n\n\tprivate hitWidthHandleIn(screen: Vec2, view: Pick<VectorEditorState, 'document' | 'selection' | 'tool' | 'hover' | 'interaction' | 'selectedWidthPoints'>): { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null {\n\t\tlet best: { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const h of getVectorWidthHandles(view)) {\n\t\t\tfor (const [part, q] of [['center', h], ['left', h.left], ['right', h.right]] as const) {\n\t\t\t\tconst s = this.documentToScreen(q);\n\t\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\t\t// Ties go to the centre (listed first), so a zero-width point can still be moved.\n\t\t\t\tif (d <= this.hitRadius && d < bestD - 1e-9) {\n\t\t\t\t\tbest = { ref: { ...h.ref, part } };\n\t\t\t\t\tbestD = d;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** The nearest stroked, unlocked visible path whose stroke is under document point `p` (width tool). */\n\tprivate strokeSpotAt(p: Vec2): VectorStrokeSpot | null {\n\t\tlet best: (VectorStrokeSpot & { distance: number }) | null = null;\n\t\tconst tol = this.tolerance();\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || n.visible === false || n.locked) return;\n\t\t\tif (hiddenOrLocked(this.doc.nodes, n.id)) return;\n\t\t\tconst g = vectorStrokeWidthGeometry(n);\n\t\t\tif (!g) return;\n\t\t\tconst m = this.worldOf(n.id);\n\t\t\tconst local = applyMatrix(invertMatrix(m), p);\n\t\t\tconst near = nearestStrokePosition(g.line, [local.x, local.y]);\n\t\t\tif (!near) return;\n\t\t\tconst profile = strokeWidthProfileOf(n);\n\t\t\tconst w = widthProfileAt(profile, near.t);\n\t\t\tconst reach = Math.max(near.side === 'left' ? w.left : w.right, 0) * g.unit + tol;\n\t\t\tif (near.distance > reach || near.distance > widthProfileMaxScale(profile) * g.unit + tol) return;\n\t\t\tif (best && near.distance >= best.distance) return;\n\t\t\tconst nx = near.tangent[1];\n\t\t\tconst ny = -near.tangent[0];\n\t\t\tconst [cx, cy] = near.point;\n\t\t\tbest = {\n\t\t\t\tnodeId: n.id,\n\t\t\t\tsubpath: near.contour,\n\t\t\t\tt: near.t,\n\t\t\t\tpoint: applyMatrix(m, { x: cx, y: cy }),\n\t\t\t\tleft: applyMatrix(m, { x: cx + nx * w.left * g.unit, y: cy + ny * w.left * g.unit }),\n\t\t\t\tright: applyMatrix(m, { x: cx - nx * w.right * g.unit, y: cy - ny * w.right * g.unit }),\n\t\t\t\tdistance: near.distance\n\t\t\t};\n\t\t});\n\t\tif (!best) return null;\n\t\tconst { distance: _d, ...spot } = best as VectorStrokeSpot & { distance: number };\n\t\treturn spot;\n\t}\n\n\tprivate downWidth(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst hit = this.hitWidthHandle(screen);\n\t\tconst spot = hit ? null : this.strokeSpotAt(p);\n\t\tconst nodeId = hit?.ref.nodeId ?? spot?.nodeId;\n\t\tconst node = nodeId ? this.getNode(nodeId) : undefined;\n\t\tconst g = node?.type === 'path' ? vectorStrokeWidthGeometry(node) : null;\n\t\tif (this.widthEdit) this.widthEdit = null;\n\t\tif (!node || node.type !== 'path' || !g) {\n\t\t\t// A click away from strokes deselects (Shift keeps the selection).\n\t\t\tif (!input.shift) this.widthPoints = [];\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst before = this.snapshot();\n\t\tconst local = this.toLocal(node.id, p);\n\t\tlet profile: VectorWidthPoint[];\n\t\tlet ref: VectorWidthPointRef;\n\t\tlet mode: 'width' | 'move' | 'copy' = 'width';\n\t\tlet side: 'both' | 'left' | 'right' = 'both';\n\t\tlet group: number[] = [];\n\t\tlet shift = false;\n\t\tlet t: number;\n\t\tlet subpath: number;\n\t\tif (hit) {\n\t\t\tprofile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\t\tref = { nodeId: node.id, index: hit.ref.index, subpath: hit.ref.subpath };\n\t\t\tt = profile[ref.index]?.t ?? 0;\n\t\t\tsubpath = hit.ref.subpath;\n\t\t\tif (hit.ref.part === 'center') mode = input.alt && profile.length < VECTOR_WIDTH_PROFILE_MAX_POINTS ? 'copy' : 'move';\n\t\t\telse if (input.alt) side = hit.ref.part;\n\t\t\tconst same = this.widthPoints.length > 0 && this.widthPoints[0].nodeId === node.id;\n\t\t\tconst selected = same && this.widthPoints.some((r) => r.index === ref.index);\n\t\t\tif (input.shift && mode !== 'copy') {\n\t\t\t\t// Shift-click adds the point to the selection, or takes it out (and drags nothing).\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.widthPoints = this.widthPoints.filter((r) => r.index !== ref.index);\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.widthPoints = same ? [...this.widthPoints, ref] : [ref];\n\t\t\t\tshift = true;\n\t\t\t} else if (mode === 'copy' || !selected) this.widthPoints = [ref];\n\t\t\tif (mode !== 'copy') group = this.widthPoints.filter((r) => r.index !== ref.index).map((r) => r.index);\n\t\t} else {\n\t\t\tconst near = nearestStrokePosition(g.line, [local.x, local.y])!;\n\t\t\tconst inserted = insertWidthPoint(strokeWidthProfileOf(node), near.t);\n\t\t\tprofile = inserted.points;\n\t\t\tsubpath = near.contour;\n\t\t\tt = near.t;\n\t\t\tref = { nodeId: node.id, index: inserted.index, subpath };\n\t\t\tif (input.alt) side = near.side;\n\t\t\tthis.widthPoints = [ref];\n\t\t}\n\t\tconst at = strokePositionPoint(g.line, subpath, t);\n\t\tif (!at) return;\n\t\tconst base = { ...this.doc, nodes: mapTree(this.doc.nodes, (n) => (n.id === node.id ? { ...(n as VectorPathNode), strokeWidthProfile: profile } : n)) };\n\t\tthis.doc = base;\n\t\tthis.drag = {\n\t\t\tkind: 'width',\n\t\t\tref,\n\t\t\tmode,\n\t\t\tside,\n\t\t\tsource: ref.index,\n\t\t\tgroup,\n\t\t\tshift,\n\t\t\trenumber: null,\n\t\t\torigin: { x: at.point[0], y: at.point[1] },\n\t\t\tnormal: { x: at.tangent[1], y: -at.tangent[0] },\n\t\t\tunit: g.unit,\n\t\t\tprofile,\n\t\t\tbefore,\n\t\t\tbase,\n\t\t\tstart: p,\n\t\t\tmoved: false,\n\t\t\tcreated: !hit\n\t\t};\n\t\tconst w = profile[ref.index];\n\t\tthis.interaction = { type: 'width', ref, mode, width: (w.left + w.right) * g.unit };\n\t\tthis.notify(!hit);\n\t}\n\n\t/**\n\t * A width-tool slide to `t` on the dragged point's subpath lands exactly on another width\n\t * point (not `skip`) within the pick distance on screen: dropping a point onto another makes\n\t * a discontinuous point (two points at one `t`, the width steps there).\n\t */\n\tprivate snapWidthT(drag: Extract<Drag, { kind: 'width' }>, node: VectorPathNode, line: BezierPath, t: number, skip: number): number {\n\t\tconst m = this.worldOf(node.id, drag.base);\n\t\tconst at = strokePositionPoint(line, drag.ref.subpath, t);\n\t\tif (!at) return t;\n\t\tconst here = this.documentToScreen(applyMatrix(m, { x: at.point[0], y: at.point[1] }));\n\t\tlet best = t;\n\t\tlet bestD = this.hitRadius;\n\t\tdrag.profile.forEach((w, i) => {\n\t\t\tif (i === skip || drag.group.includes(i)) return;\n\t\t\tconst q = strokePositionPoint(line, drag.ref.subpath, w.t);\n\t\t\tif (!q) return;\n\t\t\tconst s = this.documentToScreen(applyMatrix(m, { x: q.point[0], y: q.point[1] }));\n\t\t\tconst d = Math.hypot(s.x - here.x, s.y - here.y);\n\t\t\tif (d <= bestD) {\n\t\t\t\tbest = w.t;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t});\n\t\treturn best;\n\t}\n\n\t/** The nearest outline point of any visible, unlocked path within the pick distance of document point `p`. */\n\tprivate nearestOutline(p: Vec2): NonNullable<VectorHover['segment']> | null {\n\t\tlet best: (NonNullable<VectorHover['segment']> & { distance: number }) | null = null;\n\t\tconst tol = this.tolerance();\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (let i = list.length - 1; i >= 0; i--) {\n\t\t\t\tconst n = list[i];\n\t\t\t\tif (n.visible === false || n.locked) continue;\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tvisit(n.children, m);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst hit = nearestSegment(n, applyMatrix(invertMatrix(m), p));\n\t\t\t\t// Node matrices are rigid, so local distances are document distances.\n\t\t\t\tif (hit && hit.distance <= tol && (!best || hit.distance < best.distance - 1e-9)) {\n\t\t\t\t\tbest = { nodeId: n.id, subpath: hit.subpath, segment: hit.segment, t: hit.t, point: applyMatrix(m, hit.point), distance: hit.distance };\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvisit(this.doc.nodes, IDENTITY_MATRIX);\n\t\tif (!best) return null;\n\t\tconst { distance: _d, ...seg } = best as NonNullable<VectorHover['segment']> & { distance: number };\n\t\treturn seg;\n\t}\n\n\tprivate sameHover(a: VectorHover | null, b: VectorHover | null): boolean {\n\t\treturn JSON.stringify(a) === JSON.stringify(b);\n\t}\n\n\t/** Primary button down on the canvas at `screen` (pixels relative to the canvas). */\n\tpointerDown(screen: Vec2, input: VectorPointerInput = {}): void {\n\t\tthis.cancelDrag();\n\t\tif (input.button === 1 || this.spaceHeld) {\n\t\t\tthis.drag = { kind: 'pan', start: screen, viewport: this.viewport };\n\t\t\tthis.interaction = { type: 'pan' };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (input.button !== undefined && input.button !== 0) return;\n\t\tconst p = this.screenToDocument(screen);\n\t\tthis.pointer = p;\n\t\tswitch (this.tool) {\n\t\t\tcase 'select':\n\t\t\t\treturn this.downSelect(screen, p, input);\n\t\t\tcase 'direct':\n\t\t\t\treturn this.downDirect(screen, p, input);\n\t\t\tcase 'pen':\n\t\t\t\treturn this.downPen(screen, p, input);\n\t\t\tcase 'pencil':\n\t\t\t\treturn this.downPencil(p, input);\n\t\t\tcase 'width':\n\t\t\t\treturn this.downWidth(screen, p, input);\n\t\t\tcase 'shapeBuilder':\n\t\t\tcase 'paintBucket':\n\t\t\t\treturn this.downBuilder(p, input);\n\t\t\tcase 'blend':\n\t\t\t\treturn this.downBlend(screen, p);\n\t\t\tcase 'gradient':\n\t\t\t\treturn this.downGradient(screen, p, input);\n\t\t\tcase 'envelope':\n\t\t\t\treturn this.downEnvelope(screen, p, input);\n\t\t\tcase 'scissors': {\n\t\t\t\tconst seg = this.nearestOutline(p);\n\t\t\t\tif (seg) this.cutPathAt(seg.nodeId, seg.point);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'knife':\n\t\t\tcase 'eraser':\n\t\t\t\tthis.drag = { kind: 'stroke', tool: this.tool, points: [p], before: this.snapshot() };\n\t\t\t\tthis.interaction = { type: 'stroke', tool: this.tool, points: [p], width: this.tool === 'eraser' ? this.editing.eraserSize : 0 };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\treturn this.downShape(p, input);\n\t\t}\n\t}\n\n\t/** The shape under the pointer for the Blend tool, and the anchor of its first subpath under it. */\n\tprivate blendHit(screen: Vec2, p: Vec2): VectorBlendStart | null {\n\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance());\n\t\tif (!node) return null;\n\t\tlet anchor: number | null = null;\n\t\tif (node.type === 'path' && node.subpaths[0]) {\n\t\t\tconst refs = node.subpaths[0].anchors.map((_, index) => ({ nodeId: node.id, subpath: 0, index }));\n\t\t\tanchor = this.hitAnchor(screen, refs)?.index ?? null;\n\t\t}\n\t\treturn { nodeId: node.id, anchor };\n\t}\n\n\t/** Blend tool: the first click picks the shape to blend from, the next one blends it into the shape clicked. */\n\tprivate downBlend(screen: Vec2, p: Vec2) {\n\t\tconst hit = this.blendHit(screen, p);\n\t\tconst start = this.blendStart;\n\t\tif (!hit) {\n\t\t\tif (start) {\n\t\t\t\tthis.blendStart = null;\n\t\t\t\tthis.notify();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!start || start.nodeId === hit.nodeId) {\n\t\t\tthis.blendStart = hit;\n\t\t\tthis.selection = [hit.nodeId];\n\t\t\tthis.anchors = [];\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.blendStart = null;\n\t\tconst first = this.getNode(start.nodeId);\n\t\tif (isVectorBlendGroup(first)) {\n\t\t\t// Clicking on from a blend adds the shape as its next key.\n\t\t\tif (!this.addBlendKey(first.id, hit.nodeId, { start: hit.anchor }).ok) this.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst starts: Record<string, number> = {};\n\t\tif (start.anchor !== null) starts[start.nodeId] = start.anchor;\n\t\tif (hit.anchor !== null) starts[hit.nodeId] = hit.anchor;\n\t\tif (!this.blend({ ids: [start.nodeId, hit.nodeId], keepOrder: true, starts })) this.notify();\n\t}\n\n\tprivate downSelect(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst handle = this.hitTransformHandle(screen);\n\t\tif (handle) {\n\t\t\tconst frame = this.frameOf(this.selectedRoots())!;\n\t\t\tconst before = this.snapshot();\n\t\t\tconst center = applyMatrix(rotateMatrix(frame.angle), { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 });\n\t\t\tthis.drag =\n\t\t\t\thandle === 'rotate'\n\t\t\t\t\t? { kind: 'rotate', start: p, center, before, base: this.doc }\n\t\t\t\t\t: { kind: 'scale', handle, start: p, frame, before, base: this.doc };\n\t\t\tthis.interaction = handle === 'rotate' ? { type: 'rotate', angle: 0 } : { type: 'scale', handle, sx: 1, sy: 1 };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance(), { entered: this.enteredGroups() });\n\t\tif (node) {\n\t\t\tconst selected = this.selection.includes(node.id);\n\t\t\tif (input.shift) {\n\t\t\t\tthis.selection = selected ? this.selection.filter((id) => id !== node.id) : [...this.selection, node.id];\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!selected) this.selection = [node.id];\n\t\t\tthis.anchors = [];\n\t\t\tconst before = this.snapshot();\n\t\t\tthis.drag = {\n\t\t\t\tkind: 'move',\n\t\t\t\tstart: p,\n\t\t\t\torigin: this.boundsOf(this.selectedRoots()),\n\t\t\t\tbefore,\n\t\t\t\tbase: this.doc,\n\t\t\t\tmoved: false,\n\t\t\t\tduplicated: false,\n\t\t\t\tclickId: selected && !input.shift ? node.id : null\n\t\t\t};\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!input.shift) this.selection = [];\n\t\tthis.drag = { kind: 'marquee', start: p, base: this.selection, baseAnchors: [], anchorsMode: false };\n\t\tthis.interaction = { type: 'marquee', bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify();\n\t}\n\n\tprivate downDirect(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst handle = this.hitHandle(screen);\n\t\tif (handle) {\n\t\t\tthis.drag = { kind: 'handle', ref: handle, before: this.snapshot(), base: this.doc };\n\t\t\tthis.interaction = { type: 'handle', ref: handle };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\tif (anchor) {\n\t\t\tconst selected = this.anchors.some((a) => sameRef(a, anchor));\n\t\t\tthis.editingId = anchor.nodeId;\n\t\t\tif (input.alt) {\n\t\t\t\t// Alt-drag an anchor pulls out fresh symmetric handles.\n\t\t\t\tthis.anchors = [anchor];\n\t\t\t\tthis.drag = { kind: 'pull', ref: anchor, before: this.snapshot(), base: this.doc, label: 'Make Smooth', outOnly: false, closing: false, altBreaks: false };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (input.shift) {\n\t\t\t\tthis.anchors = selected ? this.anchors.filter((a) => !sameRef(a, anchor)) : [...this.anchors, anchor];\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!selected) this.anchors = [anchor];\n\t\t\tthis.drag = { kind: 'anchors', start: p, before: this.snapshot(), base: this.doc, moved: false, clickRef: selected && !input.shift ? anchor : null, lead: anchor };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst widget = this.hitCornerWidget(screen);\n\t\tif (widget) {\n\t\t\tconst refs = getVectorCornerWidgets(this.cornerView()).map((w) => w.ref);\n\t\t\tthis.drag = { kind: 'corner', widget, refs, start: p, before: this.snapshot(), base: this.doc, moved: false, alt: !!input.alt, shift: !!input.shift };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tfor (const id of getEditablePathIds(this.view())) {\n\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\tconst seg = nearestSegment(node, this.toLocal(id, p));\n\t\t\tif (!seg || seg.distance > this.tolerance()) continue;\n\t\t\tconst sp = node.subpaths[seg.subpath];\n\t\t\tif (input.alt) {\n\t\t\t\tconst before = this.snapshot();\n\t\t\t\tconst { subpath, index } = insertAnchor(sp, seg.segment, seg.t);\n\t\t\t\tthis.replaceNode(id, { ...node, subpaths: node.subpaths.map((s, i) => (i === seg.subpath ? subpath : s)) });\n\t\t\t\tconst ref = { nodeId: id, subpath: seg.subpath, index };\n\t\t\t\tthis.anchors = [ref];\n\t\t\t\tthis.editingId = id;\n\t\t\t\tthis.drag = { kind: 'anchors', start: p, before, base: this.doc, moved: true, clickRef: null, lead: ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A click selects the segment's anchors; a drag bends it through the pointer.\n\t\t\tconst a = { nodeId: id, subpath: seg.subpath, index: seg.segment };\n\t\t\tconst b = { nodeId: id, subpath: seg.subpath, index: (seg.segment + 1) % sp.anchors.length };\n\t\t\tthis.anchors = input.shift ? [...this.anchors.filter((r) => !sameRef(r, a) && !sameRef(r, b)), a, b] : [a, b];\n\t\t\tthis.editingId = id;\n\t\t\tthis.drag = { kind: 'bend', ref: { nodeId: id, subpath: seg.subpath, segment: seg.segment }, t: seg.t, start: p, before: this.snapshot(), base: this.doc, moved: false };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst path = this.hitPath(p);\n\t\tif (path) {\n\t\t\tthis.editingId = path.id;\n\t\t\tif (!input.shift) this.selection = [path.id];\n\t\t\telse if (!this.selection.includes(path.id)) this.selection = [...this.selection, path.id];\n\t\t\tthis.anchors = path.subpaths.flatMap((sp, s) => sp.anchors.map((_, i) => ({ nodeId: path.id, subpath: s, index: i })));\n\t\t\tthis.drag = { kind: 'anchors', start: p, before: this.snapshot(), base: this.doc, moved: false, clickRef: null, lead: null };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!input.shift) {\n\t\t\tthis.anchors = [];\n\t\t}\n\t\tthis.drag = { kind: 'marquee', start: p, base: this.selection, baseAnchors: this.anchors, anchorsMode: getEditablePathIds(this.view()).length > 0 };\n\t\tthis.interaction = { type: 'marquee', bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify();\n\t}\n\n\tprivate downPen(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\tconst sp = this.pen ? (this.getNode(this.pen.nodeId) as VectorPathNode | undefined)?.subpaths[this.pen.subpath] : undefined;\n\t\tif (this.pen && sp) {\n\t\t\tconst pen = this.pen;\n\t\t\tconst first = { nodeId: pen.nodeId, subpath: pen.subpath, index: 0 };\n\t\t\tif (sp.anchors.length >= 2 && this.hitAnchor(screen, [first])) {\n\t\t\t\tconst node = this.getNode(pen.nodeId) as VectorPathNode;\n\t\t\t\tthis.replaceNode(pen.nodeId, { ...node, subpaths: node.subpaths.map((s, i) => (i === pen.subpath ? { ...s, closed: true } : s)) });\n\t\t\t\tthis.drag = { kind: 'pull', ref: first, before, base: this.doc, label: 'Close Path', outOnly: false, closing: true, altBreaks: true };\n\t\t\t\tthis.interaction = { type: 'pen', nodeId: pen.nodeId };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst last = getAnchorWorld(this.doc, { nodeId: pen.nodeId, subpath: pen.subpath, index: sp.anchors.length - 1 })!;\n\t\t\tconst leave = { at: { x: last.x, y: last.y }, constrain: input.shift ? ('angle' as const) : null };\n\t\t\tlet pt = this.snapDrawn(p, leave, input, () => this.drawingTargets(pen.nodeId));\n\t\t\tpt = this.toLocal(pen.nodeId, pt);\n\t\t\tconst node = this.getNode(pen.nodeId) as VectorPathNode;\n\t\t\tconst anchors = [...sp.anchors, { x: pt.x, y: pt.y }];\n\t\t\tthis.replaceNode(pen.nodeId, { ...node, subpaths: node.subpaths.map((s, i) => (i === pen.subpath ? { ...s, anchors } : s)) });\n\t\t\tconst ref = { nodeId: pen.nodeId, subpath: pen.subpath, index: anchors.length - 1 };\n\t\t\tthis.anchors = [ref];\n\t\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Add Point', outOnly: false, closing: false, altBreaks: true };\n\t\t\tthis.interaction = { type: 'pen', nodeId: pen.nodeId };\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tconst endpoint = this.hitAnchor(screen, this.openEndpoints());\n\t\tif (endpoint) {\n\t\t\tlet node = this.getNode(endpoint.nodeId) as VectorPathNode;\n\t\t\tlet index = endpoint.index;\n\t\t\tif (index === 0 && node.subpaths[endpoint.subpath].anchors.length > 1) {\n\t\t\t\tnode = { ...node, subpaths: node.subpaths.map((s, i) => (i === endpoint.subpath ? reverseSubpath(s) : s)) };\n\t\t\t\tthis.replaceNode(node.id, node);\n\t\t\t\tindex = node.subpaths[endpoint.subpath].anchors.length - 1;\n\t\t\t}\n\t\t\tthis.pen = { nodeId: node.id, subpath: endpoint.subpath };\n\t\t\tthis.selection = [node.id];\n\t\t\tthis.editingId = node.id;\n\t\t\tconst ref = { nodeId: node.id, subpath: endpoint.subpath, index };\n\t\t\tthis.anchors = [ref];\n\t\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Continue Path', outOnly: true, closing: false, altBreaks: true };\n\t\t\tthis.interaction = { type: 'pen', nodeId: node.id };\n\t\t\tthis.notify(this.doc !== before.doc);\n\t\t\treturn;\n\t\t}\n\t\tconst pt = this.snapDrawn(p, null, input, () => this.drawingTargets(null));\n\t\tconst node: VectorPathNode = { id: this.newId(), type: 'path', name: 'Path', ...this.styleFor(true), subpaths: [{ anchors: [{ x: pt.x, y: pt.y }], closed: false }] };\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tthis.pen = { nodeId: node.id, subpath: 0 };\n\t\tthis.selection = [node.id];\n\t\tthis.editingId = node.id;\n\t\tconst ref = { nodeId: node.id, subpath: 0, index: 0 };\n\t\tthis.anchors = [ref];\n\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Start Path', outOnly: false, closing: false, altBreaks: true };\n\t\tthis.interaction = { type: 'pen', nodeId: node.id };\n\t\tthis.notify(true);\n\t}\n\n\tprivate downPencil(p: Vec2, input: VectorPointerInput = {}) {\n\t\tconst before = this.snapshot();\n\t\tconst node: VectorPathNode = {\n\t\t\tid: this.newId(),\n\t\t\ttype: 'path',\n\t\t\tname: 'Pencil',\n\t\t\t...this.styleFor(true),\n\t\t\tstrokeLinecap: this.defaults.strokeLinecap ?? 'round',\n\t\t\tstrokeLinejoin: this.defaults.strokeLinejoin ?? 'round',\n\t\t\tsubpaths: [{ anchors: [{ x: p.x, y: p.y }], closed: false }]\n\t\t};\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tconst lazy = new LazyMouse((this.editing.pencilSmoothing * VECTOR_PENCIL_STRING_PX) / this.viewport.zoom);\n\t\tlazy.push([p.x, p.y]);\n\t\tconst mode = this.editing.pencilPressure;\n\t\tconst hasPressure = typeof input.pressure === 'number' && Number.isFinite(input.pressure);\n\t\tconst record = hasPressure && (mode === 'all' || (mode === 'pen' && input.pointerType === 'pen'));\n\t\tconst pressure = hasPressure ? input.pressure! : 0.5;\n\t\tthis.drag = { kind: 'pencil', nodeId: node.id, points: [[p.x, p.y]], before, lazy, pressures: record ? [pressure] : null, pressure };\n\t\tthis.interaction = { type: 'draw', tool: 'pencil', nodeId: node.id, bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify(true);\n\t}\n\n\tprivate downShape(p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\t// The targets are gathered before the new shape joins the document, and kept for the drag.\n\t\tconst targets = this.drawingTargets(null);\n\t\tconst start = this.snapDrawn(p, null, input, () => targets);\n\t\tconst kind = this.tool as VectorShapeInput['kind'];\n\t\tconst node = this.createShapeNode({ kind, x: start.x, y: start.y, width: 0, height: 0 });\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tthis.drag = { kind: 'shape', tool: this.tool, start, nodeId: node.id, before, targets };\n\t\tthis.interaction = { type: 'draw', tool: this.tool, nodeId: node.id, bounds: { x: start.x, y: start.y, width: 0, height: 0 } };\n\t\tthis.notify(true);\n\t}\n\n\t/** Pointer moved over the canvas (with or without a button down). */\n\tpointerMove(screen: Vec2, input: VectorPointerInput = {}): void {\n\t\tconst p = this.screenToDocument(screen);\n\t\tconst drag = this.drag;\n\t\tif (!drag && (this.tool === 'shapeBuilder' || this.tool === 'paintBucket')) {\n\t\t\tthis.pointer = p;\n\t\t\tif (this.hoverBuilder(p, !!input.alt)) this.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!drag) {\n\t\t\tconst hover = this.computeHover(screen);\n\t\t\tconst pointerMatters = this.tool === 'pen' && !!this.pen;\n\t\t\tconst guides = this.guides;\n\t\t\tthis.hover = hover;\n\t\t\tconst pointer = this.hoverSnap(p, input);\n\t\t\tif (this.sameHover(hover, this.state.hover) && !pointerMatters && JSON.stringify(guides) === JSON.stringify(this.guides)) return;\n\t\t\tthis.pointer = pointer;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.pointer = p;\n\t\tswitch (drag.kind) {\n\t\t\tcase 'pan':\n\t\t\t\tthis.viewport = { ...drag.viewport, x: drag.viewport.x + screen.x - drag.start.x, y: drag.viewport.y + screen.y - drag.start.y };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tcase 'gradient':\n\t\t\t\treturn this.moveGradient(drag, screen, p, input);\n\t\t\tcase 'envelope':\n\t\t\t\treturn this.moveEnvelope(drag, p);\n\t\t\tcase 'move': {\n\t\t\t\tlet dx = p.x - drag.start.x;\n\t\t\t\tlet dy = p.y - drag.start.y;\n\t\t\t\tif (!drag.moved && Math.hypot(dx, dy) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tif (input.shift) Math.abs(dx) > Math.abs(dy) ? (dy = 0) : (dx = 0);\n\t\t\t\tif (input.alt && !drag.duplicated) {\n\t\t\t\t\tdrag.duplicated = true;\n\t\t\t\t\tconst created: string[] = [];\n\t\t\t\t\tdrag.base = this.withDuplicates(drag.base, this.selectedRoots(), { x: 0, y: 0 }, created);\n\t\t\t\t\tthis.selection = created;\n\t\t\t\t\t// The originals stay behind as targets.\n\t\t\t\t\tdrag.targets = undefined;\n\t\t\t\t}\n\t\t\t\t({ dx, dy } = this.snapMove(drag, dx, dy, input));\n\t\t\t\tthis.doc = this.transformed(drag.base, new Set(this.selectedRoots()), translateMatrix(dx, dy));\n\t\t\t\tthis.interaction = { type: 'move', dx, dy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'scale': {\n\t\t\t\tif (this.freeDistort && drag.handle !== 'rotate') return this.moveDistort(drag, p, input);\n\t\t\t\t// Scale in the box's own (possibly rotated) frame.\n\t\t\t\tconst angle = drag.frame.angle;\n\t\t\t\tconst q = angle ? applyMatrix(rotateMatrix(-angle), p) : p;\n\t\t\t\tlet { sx, sy, origin } = scaleFor(drag.handle, drag.frame, q, input);\n\t\t\t\tif (this.snap.objects && !input.mod && drag.handle !== 'rotate') {\n\t\t\t\t\tdrag.targets ??= VectorSnapTargets.forResize(drag.base, this.selectedRoots());\n\t\t\t\t\tconst res = drag.targets.snapScale(drag.frame, drag.handle, sx, sy, input, this.snapTolerance());\n\t\t\t\t\t({ sx, sy } = res);\n\t\t\t\t\tthis.setGuides(res);\n\t\t\t\t} else this.setGuides(null);\n\t\t\t\tconst ids = new Set(this.selectedRoots());\n\t\t\t\tthis.doc = this.transformed(drag.base, ids, this.inFrame(angle, scaleMatrix(sx, sy, origin)));\n\t\t\t\tthis.interaction = { type: 'scale', handle: drag.handle, sx, sy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'rotate': {\n\t\t\t\tconst a0 = Math.atan2(drag.start.y - drag.center.y, drag.start.x - drag.center.x);\n\t\t\t\tconst a1 = Math.atan2(p.y - drag.center.y, p.x - drag.center.x);\n\t\t\t\tlet angle = ((a1 - a0) * 180) / Math.PI;\n\t\t\t\tif (input.shift) angle = Math.round(angle / 15) * 15;\n\t\t\t\tthis.doc = this.transformed(drag.base, new Set(this.selectedRoots()), rotateMatrix(angle, drag.center));\n\t\t\t\tthis.interaction = { type: 'rotate', angle };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'marquee': {\n\t\t\t\tconst bounds = boundsFromPoints(drag.start, p);\n\t\t\t\tthis.interaction = { type: 'marquee', bounds };\n\t\t\t\tif (drag.anchorsMode) {\n\t\t\t\t\tconst inside = getVisibleAnchors(this.view()).filter((r) => {\n\t\t\t\t\t\tconst a = getAnchorWorld(this.doc, r)!;\n\t\t\t\t\t\treturn a.x >= bounds.x && a.x <= bounds.x + bounds.width && a.y >= bounds.y && a.y <= bounds.y + bounds.height;\n\t\t\t\t\t});\n\t\t\t\t\tthis.anchors = [...drag.baseAnchors, ...inside.filter((r) => !drag.baseAnchors.some((b) => sameRef(b, r)))];\n\t\t\t\t} else {\n\t\t\t\t\tconst hits = this.doc.nodes\n\t\t\t\t\t\t.filter((n) => !n.locked && n.visible !== false)\n\t\t\t\t\t\t.filter((n) => {\n\t\t\t\t\t\t\tconst b = vectorNodeBounds(n);\n\t\t\t\t\t\t\treturn b && boundsIntersect(b, bounds);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.map((n) => n.id);\n\t\t\t\t\tthis.selection = [...new Set([...drag.base, ...hits])];\n\t\t\t\t}\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'anchors': {\n\t\t\t\tlet dx = p.x - drag.start.x;\n\t\t\t\tlet dy = p.y - drag.start.y;\n\t\t\t\tif (!drag.moved && Math.hypot(dx, dy) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst lead = this.leadAnchor(drag);\n\t\t\t\tif (lead) {\n\t\t\t\t\t// The grabbed (or nearest) anchor snaps; the others move with it.\n\t\t\t\t\tconst leave = input.shift ? { at: lead, constrain: 'axis' as const, curves: false } : null;\n\t\t\t\t\tconst q = this.snapDrawn({ x: lead.x + dx, y: lead.y + dy }, leave, input, () => (drag.targets ??= VectorSnapTargets.forAnchorDrag(drag.base, this.anchors)));\n\t\t\t\t\tdx = q.x - lead.x;\n\t\t\t\t\tdy = q.y - lead.y;\n\t\t\t\t} else if (input.shift) Math.abs(dx) > Math.abs(dy) ? (dy = 0) : (dx = 0);\n\t\t\t\tconst single = this.anchors.length === 1 ? this.anchors[0] : null;\n\t\t\t\tconst from = single ? getAnchorWorld(drag.base, single) : undefined;\n\t\t\t\t// A lone point bends its segments with the Curvature setting (Alt held flips it).\n\t\t\t\tif (single && from && this.editing.curvatureMoves !== !!input.alt) this.doc = this.curvatureMoved(drag.base, single, { x: from.x + dx, y: from.y + dy });\n\t\t\t\telse this.doc = this.movedAnchors(drag.base, this.anchors, dx, dy);\n\t\t\t\tthis.interaction = { type: 'anchors', dx, dy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'handle': {\n\t\t\t\tconst anchor = getAnchorWorld(drag.base, drag.ref);\n\t\t\t\tconst leave = anchor ? { at: { x: anchor.x, y: anchor.y }, constrain: input.shift ? ('angle' as const) : null } : null;\n\t\t\t\tconst pt = this.snapDrawn(p, leave, input, () => (drag.targets ??= VectorSnapTargets.forHandle(drag.base, drag.ref.nodeId)));\n\t\t\t\tconst local = this.toLocal(drag.ref.nodeId, pt, drag.base);\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, [drag.ref], (a) => moveAnchorHandle(a, drag.ref.handle, local, input.alt));\n\t\t\t\tthis.interaction = { type: 'handle', ref: drag.ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'corner': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 3) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst c = drag.widget.corner;\n\t\t\t\tconst inv = invertMatrix(this.worldOf(drag.widget.ref.nodeId, drag.base));\n\t\t\t\tconst d = applyMatrixLinear(inv, { x: p.x - drag.start.x, y: p.y - drag.start.y });\n\t\t\t\tconst radius = Math.max(0, Math.min(c.maxRadius, drag.widget.drawnRadius + cornerRadiusChange(c, d)));\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, drag.refs, (a) => setAnchorCorner(a, radius));\n\t\t\t\tthis.interaction = { type: 'corner', ref: drag.widget.ref, radius };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'bend': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tthis.doc = this.bent(drag.base, drag.ref, drag.t, p);\n\t\t\t\tthis.interaction = { type: 'bend', ref: drag.ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'builder':\n\t\t\t\treturn this.moveBuilder(drag, p);\n\t\t\tcase 'stroke': {\n\t\t\t\tconst last = drag.points[drag.points.length - 1];\n\t\t\t\tif (Math.hypot(p.x - last.x, p.y - last.y) * this.viewport.zoom < 1.5) return;\n\t\t\t\tdrag.points.push(p);\n\t\t\t\tthis.interaction = { type: 'stroke', tool: drag.tool, points: drag.points.slice(), width: drag.tool === 'eraser' ? this.editing.eraserSize : 0 };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pull': {\n\t\t\t\tconst anchor = getAnchorWorld(drag.base, drag.ref);\n\t\t\t\tif (!anchor) return;\n\t\t\t\tif (Math.hypot(p.x - anchor.x, p.y - anchor.y) * this.viewport.zoom < 2) {\n\t\t\t\t\tthis.doc = drag.base;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.guides = null;\n\t\t\t\tlet pt = p;\n\t\t\t\tif (input.shift) pt = constrain45(anchor, pt);\n\t\t\t\tconst side = drag.closing ? 'in' : 'out';\n\t\t\t\t// Dragging out of the closing anchor pulls its incoming handle toward the pointer's mirror.\n\t\t\t\tconst pos = this.toLocal(drag.ref.nodeId, drag.closing ? { x: 2 * anchor.x - pt.x, y: 2 * anchor.y - pt.y } : pt, drag.base);\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, [drag.ref], (a) => {\n\t\t\t\t\tif (drag.outOnly || (drag.altBreaks && input.alt)) return moveAnchorHandle(a, side, pos, true);\n\t\t\t\t\treturn moveAnchorHandle({ ...a, type: 'symmetric' }, side, pos);\n\t\t\t\t});\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'shape': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path') return;\n\t\t\t\tconst leave = { at: drag.start, constrain: input.shift ? (drag.tool === 'line' ? ('angle' as const) : ('square' as const)) : null, curves: false };\n\t\t\t\tlet end = this.snapDrawn(p, leave, input, () => (drag.targets ??= this.drawingTargets(null)));\n\t\t\t\tif (!this.snappedToObject && drag.tool !== 'line' && !input.shift && !input.mod && this.snap.objects && drag.targets) end = this.matchShapeSize(drag.targets, drag.start, end, input.alt);\n\t\t\t\tlet start = drag.start;\n\t\t\t\tlet bounds: VectorBounds;\n\t\t\t\tif (drag.tool === 'line') {\n\t\t\t\t\tif (input.shift) end = constrain45(start, end);\n\t\t\t\t\tif (input.alt) start = { x: 2 * start.x - end.x, y: 2 * start.y - end.y };\n\t\t\t\t\tbounds = { x: start.x, y: start.y, width: end.x - start.x, height: end.y - start.y };\n\t\t\t\t} else {\n\t\t\t\t\tlet w = end.x - start.x;\n\t\t\t\t\tlet h = end.y - start.y;\n\t\t\t\t\tif (input.shift) {\n\t\t\t\t\t\tconst s = Math.max(Math.abs(w), Math.abs(h));\n\t\t\t\t\t\tw = Math.sign(w || 1) * s;\n\t\t\t\t\t\th = Math.sign(h || 1) * s;\n\t\t\t\t\t}\n\t\t\t\t\tif (input.alt) start = { x: start.x - w, y: start.y - h };\n\t\t\t\t\tconst x2 = drag.start.x + w;\n\t\t\t\t\tconst y2 = drag.start.y + h;\n\t\t\t\t\tbounds = boundsFromPoints(start, { x: x2, y: y2 });\n\t\t\t\t}\n\t\t\t\tconst shaped = this.createShapeNode({ kind: drag.tool as VectorShapeInput['kind'], ...bounds });\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths: shaped.subpaths });\n\t\t\t\tthis.interaction = { type: 'draw', tool: drag.tool, nodeId: drag.nodeId, bounds };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst node = findVectorNode(drag.base.nodes, drag.ref.nodeId) as VectorPathNode;\n\t\t\t\tconst local = this.toLocal(node.id, p, drag.base);\n\t\t\t\tconst src = drag.profile[drag.source];\n\t\t\t\tlet profile: VectorWidthPoint[];\n\t\t\t\tlet index = drag.source;\n\t\t\t\tif (drag.mode !== 'width') {\n\t\t\t\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\t\t\t\tconst near = g ? nearestStrokePosition(g.line, [local.x, local.y], drag.ref.subpath) : null;\n\t\t\t\t\tif (!g || !near) return;\n\t\t\t\t\tconst t = drag.group.length ? near.t : this.snapWidthT(drag, node, g.line, near.t, drag.source);\n\t\t\t\t\tif (drag.mode === 'copy') {\n\t\t\t\t\t\t// The source stays; a copy of it slides (and may pass other points).\n\t\t\t\t\t\t({ points: profile, index } = insertWidthPoint(drag.profile, t, { left: src.left, right: src.right }, { step: true }));\n\t\t\t\t\t} else if (drag.group.length) {\n\t\t\t\t\t\tconst shifted = shiftWidthPoints(drag.profile, [drag.source, ...drag.group], t - src.t);\n\t\t\t\t\t\tprofile = shifted.points;\n\t\t\t\t\t\tdrag.renumber = shifted.renumber;\n\t\t\t\t\t\tindex = shifted.renumber.get(drag.source) ?? drag.source;\n\t\t\t\t\t} else profile = setWidthPoint(drag.profile, drag.source, { t });\n\t\t\t\t} else {\n\t\t\t\t\tconst off = ((local.x - drag.origin.x) * drag.normal.x + (local.y - drag.origin.y) * drag.normal.y) / drag.unit;\n\t\t\t\t\tconst patch =\n\t\t\t\t\t\tdrag.side === 'both' ? { left: Math.abs(off), right: Math.abs(off) } : drag.side === 'left' ? { left: Math.max(0, off) } : { right: Math.max(0, -off) };\n\t\t\t\t\tprofile = setWidthPoint(drag.profile, drag.source, patch);\n\t\t\t\t\tif (drag.group.length) {\n\t\t\t\t\t\t// Every selected point widens by as much as the dragged one.\n\t\t\t\t\t\tconst dl = profile[drag.source].left - src.left;\n\t\t\t\t\t\tconst dr = profile[drag.source].right - src.right;\n\t\t\t\t\t\tfor (const i of drag.group) profile = setWidthPoint(profile, i, { left: Math.max(0, drag.profile[i].left + dl), right: Math.max(0, drag.profile[i].right + dr) });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.doc = { ...drag.base, nodes: mapTree(drag.base.nodes, (n) => (n.id === node.id ? { ...(n as VectorPathNode), strokeWidthProfile: profile } : n)) };\n\t\t\t\tdrag.ref = { ...drag.ref, index };\n\t\t\t\tconst w = profile[index];\n\t\t\t\tthis.interaction = { type: 'width', ref: drag.ref, mode: drag.mode, width: (w.left + w.right) * drag.unit };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pencil': {\n\t\t\t\tconst last = drag.points[drag.points.length - 1];\n\t\t\t\tlet moved = false;\n\t\t\t\tif (typeof input.pressure === 'number' && Number.isFinite(input.pressure)) drag.pressure = input.pressure;\n\t\t\t\tfor (const q of drag.lazy.push([p.x, p.y])) {\n\t\t\t\t\tif (Math.hypot(q[0] - last[0], q[1] - last[1]) * this.viewport.zoom < 1.5) continue;\n\t\t\t\t\tdrag.points.push(q);\n\t\t\t\t\tdrag.pressures?.push(drag.pressure);\n\t\t\t\t\tmoved = true;\n\t\t\t\t}\n\t\t\t\tconst string = drag.lazy.string();\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path') return;\n\t\t\t\tif (!moved) {\n\t\t\t\t\tif (string && this.interaction?.type === 'draw') {\n\t\t\t\t\t\tthis.interaction = { ...this.interaction, string: [{ x: string[0][0], y: string[0][1] }, { x: string[1][0], y: string[1][1] }] };\n\t\t\t\t\t\tthis.notify();\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths: [{ anchors: drag.points.map(([x, y]) => ({ x, y })), closed: false }] });\n\t\t\t\tconst xs = drag.points.map((q) => q[0]);\n\t\t\t\tconst ys = drag.points.map((q) => q[1]);\n\t\t\t\tthis.interaction = {\n\t\t\t\t\ttype: 'draw',\n\t\t\t\t\ttool: 'pencil',\n\t\t\t\t\tnodeId: drag.nodeId,\n\t\t\t\t\tbounds: { x: Math.min(...xs), y: Math.min(...ys), width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys) },\n\t\t\t\t\t...(string ? { string: [{ x: string[0][0], y: string[0][1] }, { x: string[1][0], y: string[1][1] }] as [Vec2, Vec2] } : {})\n\t\t\t\t};\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Snaps a move of the selection by (dx, dy): its bounds line up with targets or space evenly, else go to the grid. */\n\tprivate snapMove(drag: Extract<Drag, { kind: 'move' }>, dx: number, dy: number, input: VectorModifiers): { dx: number; dy: number } {\n\t\tconst origin = drag.origin;\n\t\tif (input.mod || !origin) {\n\t\t\tthis.setGuides(null);\n\t\t\treturn { dx, dy };\n\t\t}\n\t\t// A Shift-locked axis stays put.\n\t\tconst axes = { x: !input.shift || dx !== 0, y: !input.shift || dy !== 0 };\n\t\tlet res = null;\n\t\tif (this.snap.objects) {\n\t\t\tdrag.targets ??= VectorSnapTargets.forMove(drag.base, this.selectedRoots());\n\t\t\tres = drag.targets.snapRect({ ...origin, x: origin.x + dx, y: origin.y + dy }, this.snapTolerance(), { spacing: true, axes });\n\t\t}\n\t\tthis.setGuides(res);\n\t\treturn {\n\t\t\tdx: res?.x ? dx + res.dx : axes.x ? this.gridValue(origin.x + dx) - origin.x : dx,\n\t\t\tdy: res?.y ? dy + res.dy : axes.y ? this.gridValue(origin.y + dy) - origin.y : dy\n\t\t};\n\t}\n\n\t/** The anchor a point drag snaps by, where it started: the grabbed one, else the moving one nearest the press. */\n\tprivate leadAnchor(drag: Extract<Drag, { kind: 'anchors' }>): Vec2 | null {\n\t\tconst ref = drag.lead && this.anchors.some((a) => sameRef(a, drag.lead!)) ? drag.lead : null;\n\t\tif (ref) {\n\t\t\tconst a = getAnchorWorld(drag.base, ref);\n\t\t\treturn a ? { x: a.x, y: a.y } : null;\n\t\t}\n\t\tlet best: Vec2 | null = null;\n\t\tfor (const r of this.anchors) {\n\t\t\tconst a = getAnchorWorld(drag.base, r);\n\t\t\tif (a && (!best || Math.hypot(a.x - drag.start.x, a.y - drag.start.y) < Math.hypot(best.x - drag.start.x, best.y - drag.start.y))) best = { x: a.x, y: a.y };\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** A shape's dragged corner moved so its width or height matches another object's, when one is within reach. */\n\tprivate matchShapeSize(targets: VectorSnapTargets, start: Vec2, end: Vec2, fromCentre = false): Vec2 {\n\t\t// Dragged from the centre, the shape is twice as large as the drag.\n\t\tconst k = fromCentre ? 2 : 1;\n\t\tconst tol = this.snapTolerance() * k;\n\t\tconst out = { ...end };\n\t\tconst guides: VectorSnapGuides = { lines: [], labels: [] };\n\t\tfor (const axis of ['x', 'y'] as const) {\n\t\t\tconst d = end[axis] - start[axis];\n\t\t\tconst len = Math.abs(d) > 1e-9 ? targets.matchSize(Math.abs(d) * k, tol) : null;\n\t\t\tif (len === null || len <= 0) continue;\n\t\t\tout[axis] = start[axis] + (Math.sign(d) * len) / k;\n\t\t\tconst from = { ...out, [axis]: fromCentre ? 2 * start[axis] - out[axis] : start[axis] };\n\t\t\tguides.lines.push({ kind: 'size', x1: from.x, y1: from.y, x2: out.x, y2: out.y });\n\t\t\tguides.labels.push({ kind: 'size', x: (from.x + out.x) / 2, y: (from.y + out.y) / 2, text: `${axis === 'x' ? 'W' : 'H'} ${Math.round(len * 100) / 100}` });\n\t\t}\n\t\tthis.setGuides(guides);\n\t\treturn out;\n\t}\n\n\t/** Primary button released. */\n\tpointerUp(screen?: Vec2, input: VectorPointerInput = {}): void {\n\t\t// A pen reports no pressure as it lifts: keep the last pressure for the final move.\n\t\tif (screen && this.drag && this.drag.kind !== 'pan') this.pointerMove(screen, { ...input, pressure: undefined });\n\t\tconst drag = this.drag;\n\t\tthis.drag = null;\n\t\tthis.interaction = null;\n\t\tthis.guides = null;\n\t\tif (!drag) return;\n\t\tswitch (drag.kind) {\n\t\t\tcase 'pan':\n\t\t\tcase 'marquee':\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tcase 'move':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tif (drag.clickId) this.selection = [drag.clickId];\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit(drag.duplicated ? 'Duplicate' : 'Move', drag.before);\n\t\t\tcase 'scale':\n\t\t\t\treturn this.commit(drag.op ?? 'Scale', drag.before);\n\t\t\tcase 'envelope':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit('Edit Envelope', drag.before);\n\t\t\tcase 'rotate':\n\t\t\t\treturn this.commit('Rotate', drag.before);\n\t\t\tcase 'anchors':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tif (drag.clickRef) this.anchors = [drag.clickRef];\n\t\t\t\t\tif (drag.before.doc !== this.doc) return this.commit('Add Point', drag.before);\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit(drag.before.doc !== drag.base ? 'Add Point' : 'Move Points', drag.before);\n\t\t\tcase 'handle':\n\t\t\t\treturn this.commit('Move Handle', drag.before);\n\t\t\tcase 'bend':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit('Bend Segment', drag.before);\n\t\t\tcase 'corner': {\n\t\t\t\tif (drag.moved) return this.commit('Corner Radius', drag.before);\n\t\t\t\tif (drag.alt) {\n\t\t\t\t\tconst kind = nextVectorCornerKind(drag.widget.kind);\n\t\t\t\t\tthis.doc = this.updateAnchors(drag.base, drag.refs, (a) => setAnchorCorner(a, a.corner?.radius ?? 0, kind));\n\t\t\t\t\treturn this.commit('Corner Kind', drag.before);\n\t\t\t\t}\n\t\t\t\t// A click selects the widget's corner, so the next drag rounds that corner alone.\n\t\t\t\tconst ref = drag.widget.ref;\n\t\t\t\tconst has = this.anchors.some((a) => sameRef(a, ref));\n\t\t\t\tthis.editingId = ref.nodeId;\n\t\t\t\tthis.anchors = drag.shift ? (has ? this.anchors.filter((a) => !sameRef(a, ref)) : [...this.anchors, ref]) : [ref];\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tif (drag.moved) {\n\t\t\t\t\tconst several = drag.group.length > 0;\n\t\t\t\t\tif (drag.mode === 'copy') this.widthPoints = [drag.ref];\n\t\t\t\t\telse if (drag.mode === 'move' && several) {\n\t\t\t\t\t\t// Points moved together stay selected (re-sorting may renumber them).\n\t\t\t\t\t\tthis.widthPoints = [drag.source, ...drag.group].map((i) => ({ ...drag.ref, index: drag.renumber?.get(i) ?? i }));\n\t\t\t\t\t} else if (!several) this.widthPoints = [drag.ref];\n\t\t\t\t\tconst label = drag.mode === 'copy' ? 'Copy Width Point' : drag.mode === 'move' ? (several ? 'Move Width Points' : 'Move Width Point') : several ? 'Width Points' : 'Width Point';\n\t\t\t\t\treturn this.commit(label, drag.before);\n\t\t\t\t}\n\t\t\t\t// A click adds nothing; on a width point it selects it (just it, among several selected).\n\t\t\t\tif (drag.created) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.widthPoints = [];\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t} else {\n\t\t\t\t\tif (!drag.shift && drag.group.length) this.widthPoints = [drag.ref];\n\t\t\t\t\tthis.notify();\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'builder':\n\t\t\t\treturn this.upBuilder(drag);\n\t\t\tcase 'gradient':\n\t\t\t\treturn this.upGradient(drag);\n\t\t\tcase 'stroke': {\n\t\t\t\tthis.notify();\n\t\t\t\tif (drag.tool === 'knife') this.knife(drag.points);\n\t\t\t\telse this.erase(drag.points);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pull':\n\t\t\t\tif (drag.closing) this.pen = null;\n\t\t\t\treturn this.commit(drag.label, drag.before);\n\t\t\tcase 'shape': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tconst b = node ? vectorNodeBounds(node) : null;\n\t\t\t\tconst min = 2 / this.viewport.zoom;\n\t\t\t\tif (!b || (b.width < min && b.height < min)) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\tthis.anchors = [];\n\t\t\t\tthis.tool = 'select';\n\t\t\t\treturn this.commit(`Draw ${TOOL_LABELS[drag.tool]}`, drag.before);\n\t\t\t}\n\t\t\tcase 'pencil': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path' || drag.points.length < 2) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor (const q of drag.lazy.finish()) {\n\t\t\t\t\tdrag.points.push(q);\n\t\t\t\t\tdrag.pressures?.push(drag.pressure);\n\t\t\t\t}\n\t\t\t\tconst shape = this.editing.recognizeShapes ? recognizeInkShape(drag.points, { minSize: 6 / this.viewport.zoom }) : null;\n\t\t\t\tif (shape) {\n\t\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, name: inkShapeLabel(shape), subpaths: [inkShapeSubpath(shape)] });\n\t\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\t\treturn this.commit(`Draw ${inkShapeLabel(shape)}`, drag.before);\n\t\t\t\t}\n\t\t\t\tconst fitted = fitCubics(drag.points, 1.5 / this.viewport.zoom, { cornerAngleDeg: 60 });\n\t\t\t\tconst anchors: VectorAnchor[] = [];\n\t\t\t\tfor (const c of fitted) {\n\t\t\t\t\tif (!anchors.length) anchors.push({ x: c.p0[0], y: c.p0[1] });\n\t\t\t\t\tanchors[anchors.length - 1].out = { x: c.p1[0], y: c.p1[1] };\n\t\t\t\t\tanchors.push({ x: c.p3[0], y: c.p3[1], in: { x: c.p2[0], y: c.p2[1] } });\n\t\t\t\t}\n\t\t\t\tconst subpaths = anchors.length > 1 ? bezierToSubpaths(subpathsToBezier([{ anchors, closed: false }])) : node.subpaths;\n\t\t\t\tconst profile = drag.pressures ? pencilPressureProfile(drag.points, drag.pressures) : [];\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths, ...(profile.length ? { strokeWidthProfile: profile } : {}) });\n\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\treturn this.commit('Draw', drag.before);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The pointer left the canvas. */\n\tpointerLeave(): void {\n\t\tif (this.drag) return;\n\t\tif (!this.hover && !this.pointer && !this.guides) return;\n\t\tthis.hover = null;\n\t\tthis.pointer = null;\n\t\tthis.guides = null;\n\t\tthis.notify();\n\t}\n\n\t/** Abandons the drag in progress (Escape, lost capture). */\n\tcancelDrag(): void {\n\t\tconst drag = this.drag;\n\t\tif (!drag) return;\n\t\tthis.drag = null;\n\t\tthis.interaction = null;\n\t\tthis.guides = null;\n\t\tif (drag.kind === 'pan' || drag.kind === 'builder') {\n\t\t\tif (drag.kind === 'builder') this.builderPreview = null;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (drag.kind === 'marquee') {\n\t\t\tthis.selection = drag.base;\n\t\t\tthis.anchors = drag.baseAnchors;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.restore(drag.before);\n\t}\n\n\t/**\n\t * Double click: select tool enters path editing, direct tool toggles an anchor or adds one,\n\t * width tool opens the width-point editor (`widthPointEdit`).\n\t */\n\tdoubleClick(screen: Vec2): void {\n\t\tconst p = this.screenToDocument(screen);\n\t\tif (this.tool === 'select') {\n\t\t\tconst path = this.hitPath(p);\n\t\t\tif (!path) return;\n\t\t\tthis.tool = 'direct';\n\t\t\tthis.selection = [path.id];\n\t\t\tthis.editingId = path.id;\n\t\t\tthis.anchors = [];\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'direct') {\n\t\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\t\tif (anchor) {\n\t\t\t\tconst a = getAnchor(this.doc, anchor)!;\n\t\t\t\tthis.convertAnchors(a.in || a.out ? 'corner' : 'smooth', [anchor]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.hover?.segment?.nodeId ?? this.editingId;\n\t\t\tif (id) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode | undefined;\n\t\t\t\tconst seg = node ? nearestSegment(node, this.toLocal(id, p)) : null;\n\t\t\t\tif (seg && seg.distance <= this.tolerance()) this.insertAnchorAt(id, p);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'width') {\n\t\t\t// Width Point Edit: on a width point, or on a stroke (applying it adds a point there).\n\t\t\tconst hit = this.hitWidthHandle(screen);\n\t\t\tif (hit) {\n\t\t\t\tthis.openWidthPointEdit(hit.ref);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst spot = this.strokeSpotAt(p);\n\t\t\tif (spot) this.openWidthPointEdit({ nodeId: spot.nodeId, subpath: spot.subpath, t: spot.t });\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'pen') this.finishPath();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Keyboard input\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Handles editor shortcuts. Returns true when the key was used (call `preventDefault`).\n\t * Do not forward keys typed into text inputs.\n\t */\n\tkeyDown(input: VectorKeyInput): boolean {\n\t\tconst key = input.key;\n\t\tconst lower = key.length === 1 ? key.toLowerCase() : key;\n\t\tif (key === ' ') {\n\t\t\tif (!this.spaceHeld) {\n\t\t\t\tthis.spaceHeld = true;\n\t\t\t\tthis.notify();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (input.mod) {\n\t\t\tswitch (lower) {\n\t\t\t\tcase 'z':\n\t\t\t\t\tinput.shift ? this.redo() : this.undo();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'y':\n\t\t\t\t\tthis.redo();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'a':\n\t\t\t\t\tthis.selectAll();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'd':\n\t\t\t\t\tthis.duplicate();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'g':\n\t\t\t\t\tinput.shift ? this.ungroup() : this.group();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'j':\n\t\t\t\t\treturn input.alt ? this.averageAnchors('both').ok : this.joinPaths().ok;\n\t\t\t\tcase ']':\n\t\t\t\t\tthis.arrange(input.alt ? 'front' : 'forward');\n\t\t\t\t\treturn true;\n\t\t\t\tcase '[':\n\t\t\t\t\tthis.arrange(input.alt ? 'back' : 'backward');\n\t\t\t\t\treturn true;\n\t\t\t\tcase '=':\n\t\t\t\tcase '+':\n\t\t\t\t\tthis.setViewport({ zoom: this.viewport.zoom * 1.25 });\n\t\t\t\t\treturn true;\n\t\t\t\tcase '-':\n\t\t\t\t\tthis.setViewport({ zoom: this.viewport.zoom / 1.25 });\n\t\t\t\t\treturn true;\n\t\t\t\tcase '0':\n\t\t\t\t\tthis.setViewport({ zoom: 1 });\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tswitch (key) {\n\t\t\tcase 'Escape':\n\t\t\t\tif (this.drag) this.cancelDrag();\n\t\t\t\telse if (this.widthEdit) this.closeWidthPointEdit();\n\t\t\t\telse if (this.tool === 'width' && this.widthPoints.length) {\n\t\t\t\t\tthis.widthPoints = [];\n\t\t\t\t\tthis.notify();\n\t\t\t\t}\n\t\t\t\telse if (this.pen) this.finishPath();\n\t\t\t\telse if (this.blendStart) {\n\t\t\t\t\tthis.blendStart = null;\n\t\t\t\t\tthis.notify();\n\t\t\t\t} else if (this.tool === 'direct' && this.anchors.length) {\n\t\t\t\t\tthis.anchors = [];\n\t\t\t\t\tthis.notify();\n\t\t\t\t} else if (this.tool !== 'select') this.setTool('select');\n\t\t\t\telse this.clearSelection();\n\t\t\t\treturn true;\n\t\t\tcase 'Enter':\n\t\t\t\tif (this.pen) {\n\t\t\t\t\tthis.finishPath();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (this.tool === 'select' && this.selection.length === 1 && this.getNode(this.selection[0])?.type === 'path') {\n\t\t\t\t\tthis.tool = 'direct';\n\t\t\t\t\tthis.editingId = this.selection[0];\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\tcase 'Delete':\n\t\t\tcase 'Backspace':\n\t\t\t\tif (this.tool === 'width' && this.widthPoints.length) return this.removeWidthPoints().ok;\n\t\t\t\tif (this.tool === 'gradient' && this.gradientEdit.stop !== null) return this.removeGradientStop(this.gradientEdit.stop).ok;\n\t\t\t\tif (this.pen) {\n\t\t\t\t\tconst node = this.getNode(this.pen.nodeId) as VectorPathNode;\n\t\t\t\t\tconst sp = node.subpaths[this.pen.subpath];\n\t\t\t\t\tif (sp.anchors.length > 2) this.deleteAnchors([{ nodeId: node.id, subpath: this.pen.subpath, index: sp.anchors.length - 1 }]);\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.removeNodes([node.id], { label: 'Delete Path' });\n\t\t\t\t\t\tthis.pen = null;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn this.deleteSelection().ok;\n\t\t\tcase 'ArrowLeft':\n\t\t\tcase 'ArrowRight':\n\t\t\tcase 'ArrowUp':\n\t\t\tcase 'ArrowDown': {\n\t\t\t\tconst step = input.shift ? 10 : 1;\n\t\t\t\tconst dx = key === 'ArrowLeft' ? -step : key === 'ArrowRight' ? step : 0;\n\t\t\t\tconst dy = key === 'ArrowUp' ? -step : key === 'ArrowDown' ? step : 0;\n\t\t\t\treturn this.translate(dx, dy).ok;\n\t\t\t}\n\t\t}\n\t\tif (key.length === 1 && !input.alt) {\n\t\t\tconst tool = TOOL_KEYS[lower];\n\t\t\tif (tool) {\n\t\t\t\tthis.setTool(tool);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tkeyUp(input: VectorKeyInput): void {\n\t\tif (input.key === ' ' && this.spaceHeld) {\n\t\t\tthis.spaceHeld = false;\n\t\t\tthis.notify();\n\t\t}\n\t}\n}\n\n/** \"Rectangle\", \"Square\", \"Ellipse\", \"Circle\", \"Line\", \"Triangle\" or \"Polygon\". */\nfunction inkShapeLabel(shape: VectorInkShape): string {\n\tconst name = vectorInkShapeName(shape);\n\treturn name[0].toUpperCase() + name.slice(1);\n}\n\n/** The subpath of a recognised pencil shape. */\nfunction inkShapeSubpath(shape: VectorInkShape): VectorSubpath {\n\tswitch (shape.kind) {\n\t\tcase 'line':\n\t\t\treturn lineSubpath({ x: shape.a[0], y: shape.a[1] }, { x: shape.b[0], y: shape.b[1] });\n\t\tcase 'rect':\n\t\t\treturn rectSubpath(shape);\n\t\tcase 'ellipse':\n\t\t\treturn ellipseSubpath(shape);\n\t\tcase 'polygon':\n\t\t\treturn { anchors: shape.points.map(([x, y]) => ({ x, y })), closed: true };\n\t}\n}\n\n/** Snaps `p` to the nearest 45° direction from `origin`, keeping its distance. */\nfunction constrain45(origin: Vec2, p: Vec2): Vec2 {\n\tconst dx = p.x - origin.x;\n\tconst dy = p.y - origin.y;\n\tconst len = Math.hypot(dx, dy);\n\tconst a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);\n\treturn { x: origin.x + Math.cos(a) * len, y: origin.y + Math.sin(a) * len };\n}\n\n/** Scale factors and origin for dragging a selection-box handle to `p`. */\nexport function scaleFor(handle: VectorTransformHandle, b: VectorBounds, p: Vec2, mods: VectorModifiers = {}): { sx: number; sy: number; origin: Vec2 } {\n\tconst west = handle.includes('w');\n\tconst east = handle.includes('e');\n\tconst north = handle.startsWith('n');\n\tconst south = handle.startsWith('s');\n\tconst center = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\tconst origin = mods.alt ? center : { x: west ? b.x + b.width : east ? b.x : center.x, y: north ? b.y + b.height : south ? b.y : center.y };\n\tconst reachX = mods.alt ? b.width / 2 : b.width;\n\tconst reachY = mods.alt ? b.height / 2 : b.height;\n\tlet sx = west || east ? (reachX > 1e-9 ? ((p.x - origin.x) * (west ? -1 : 1)) / reachX : 1) : 1;\n\tlet sy = north || south ? (reachY > 1e-9 ? ((p.y - origin.y) * (north ? -1 : 1)) / reachY : 1) : 1;\n\tif (mods.shift) {\n\t\tif ((west || east) && (north || south)) {\n\t\t\tconst s = Math.max(Math.abs(sx), Math.abs(sy));\n\t\t\tsx = Math.sign(sx || 1) * s;\n\t\t\tsy = Math.sign(sy || 1) * s;\n\t\t} else if (west || east) sy = Math.abs(sx);\n\t\telse sx = Math.abs(sy);\n\t}\n\treturn { sx, sy, origin };\n}\n\n/** A style applied to a path; a `null` (or empty) width profile removes it. */\nfunction withStyle(node: VectorPathNode, style: VectorStyle & { opacity?: number }): VectorNode {\n\tconst next = { ...node, ...style } as VectorPathNode;\n\tif ('strokeWidthProfile' in style) {\n\t\tconst p = style.strokeWidthProfile ? sanitizeWidthProfile(style.strokeWidthProfile) : [];\n\t\tif (p.length) next.strokeWidthProfile = p;\n\t\telse delete next.strokeWidthProfile;\n\t}\n\treturn next;\n}\n\n/** True when node `id` or one of its ancestors is locked or hidden. */\nfunction hiddenOrLocked(nodes: readonly VectorNode[], id: string): boolean {\n\tconst loc = locateVectorNode(nodes as VectorNode[], id);\n\tif (!loc) return false;\n\tconst n = loc.list[loc.index];\n\tif (n.locked || n.visible === false) return true;\n\treturn loc.parent ? hiddenOrLocked(nodes, loc.parent.id) : false;\n}\n\n/** The width profile of pencil samples and their pressures (positions by length along the samples). */\nfunction pencilPressureProfile(points: readonly Point[], pressures: readonly number[]): VectorWidthPoint[] {\n\tconst n = Math.min(points.length, pressures.length);\n\tif (n < 2) return [];\n\tconst s = [0];\n\tfor (let i = 1; i < n; i++) s.push(s[i - 1] + Math.hypot(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]));\n\tconst total = s[n - 1];\n\tif (!(total > 0)) return [];\n\treturn pressureWidthProfile(s.map((d, i) => ({ t: d / total, pressure: pressures[i] })));\n}\n","/**\n * Framework-neutral render data for a vector editor: the scene (document-space SVG paths and\n * gradient defs) and the overlay (screen-space selection box, anchors, handles, marquee and\n * pen preview). React, Svelte or plain DOM code turns these into `<svg>` elements.\n */\nimport { bezierPathToSvg, transformBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { hatchPath } from '../canvas/pathops/hatch.js';\nimport type { SvgGradientDef } from '../canvas/gradient.js';\nimport { expandVectorGradientStops, isCentredVectorGradient, isVectorGradient, parseVectorColor, sortedVectorGradientStops, type VectorGradientHandle, type VectorPaintDef } from './gradient.js';\nimport { getVectorGradientAnnotator, VECTOR_GRADIENT_STOP_GAP } from './gradientTool.js';\n\nexport type { SvgGradientDef };\nimport {\n\tgetAnchorWorld,\n\tgetVectorCornerWidgets,\n\tgetVectorEnvelopeTarget,\n\tgetVectorSelectionBoxGeometry,\n\tgetVectorWidthHandles,\n\tgetVisibleAnchors,\n\tgetVisibleHandles,\n\ttype VectorEditorController,\n\ttype VectorEditorState,\n\ttype VectorSelectionBoxGeometry,\n\ttype VectorWidthPointRef\n} from './controller.js';\nimport { sanitizeWidthProfile, widthProfilePresetId, type VectorWidthPreset } from './width.js';\nimport {\n\tfindVectorNode,\n\twalkVectorNodes,\n\tlocateVectorNode,\n\tsubpathsToBezier,\n\tvectorWorldMatrix,\n\tIDENTITY_MATRIX,\n\tinferAnchorType,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\tvectorNodeBounds,\n\tvectorParentMatrix,\n\tvectorPathData,\n\tvectorPathWorldBezier,\n\ttype AffineMatrix\n} from './geometry.js';\nimport { vectorPaintToSvg, vectorStrokeSvgParts, type VectorRenderStrokeParts } from './svg.js';\nimport { vectorCorners } from './corners.js';\nimport {\n\texpandVectorAppearance,\n\thasOwnVectorAppearance,\n\thasVectorAppearance,\n\tvectorAppearanceOutline,\n\tvectorEnteredGroups,\n\tVECTOR_EFFECT_LABELS,\n\tVECTOR_EFFECT_PARAM_SPECS,\n\ttype VectorEffectParamSpec,\n\ttype VectorEnvelopeParams\n} from './appearance.js';\nimport { vectorMeshEditPoints, vectorMeshGridCurves, VECTOR_WARP_STYLES, VECTOR_WARP_STYLE_LABELS } from './warp.js';\nimport { VECTOR_EFFECT_TYPES, type VectorEffectType } from './types.js';\nimport { isVectorBlendGroup, resolveVectorBlendOptions, vectorBlendRailAt, vectorBlendSpine } from './blendGroup.js';\nimport type { VectorGuideKind, VectorSnapKind } from './snap.js';\nimport type {\n\tVectorAnchorRef,\n\tVectorAnchorType,\n\tVectorArrowAlign,\n\tVectorArrowhead,\n\tVectorBlendOptions,\n\tVectorBlendSpacing,\n\tVectorBounds,\n\tVectorCornerKind,\n\tVectorGradient,\n\tVectorGradientInterpolation,\n\tVectorGradientSpread,\n\tVectorGradientStop,\n\tVectorGradientType,\n\tVectorStrokeGradientMode,\n\tVectorGroupNode,\n\tVectorHandleRef,\n\tVectorNode,\n\tVectorPaint,\n\tVectorPathfinderOperation,\n\tVectorPathNode,\n\tVectorStrokeAlign,\n\tVectorTransformHandle,\n\tVectorWidthPoint,\n\tVec2\n} from './types.js';\n\nexport interface VectorRenderPath {\n\tkind: 'path';\n\tid: string;\n\t/** SVG `transform` (`matrix(…)`) for a rotated node. */\n\ttransform?: string;\n\td: string;\n\t/** `none`, a colour, or `url(#id)` of a gradient in `defs`. */\n\tfill: string;\n\tstroke: string;\n\tstrokeWidth: number;\n\tstrokeLinecap?: string;\n\tstrokeLinejoin?: string;\n\tstrokeDasharray?: string;\n\tfillRule: 'nonzero' | 'evenodd';\n\topacity: number;\n\t/**\n\t * Set when the stroke takes more than one element: an inside / outside alignment or\n\t * arrowheads. Draw `d` with the fill only, then `stroke.d` with the stroke (at\n\t * `stroke.width`, clipped or masked as `stroke.clip` says), then each head filled with\n\t * `stroke`; group them under `id`, `transform` and `opacity`.\n\t */\n\tstrokeParts?: VectorRenderStrokeParts;\n}\n\nexport interface VectorRenderGroup {\n\tkind: 'group';\n\tid: string;\n\t/** SVG `transform` (`matrix(…)`) for a rotated group. */\n\ttransform?: string;\n\topacity: number;\n\tchildren: VectorRenderNode[];\n}\n\nexport type VectorRenderNode = VectorRenderPath | VectorRenderGroup;\n\nexport interface VectorSceneRenderData {\n\t/** SVG `transform` for the document layer: `translate(x y) scale(zoom)`. */\n\ttransform: string;\n\twidth: number;\n\theight: number;\n\tbackground?: string;\n\t/**\n\t * Paint servers referenced by `fill` / `stroke` values: `<linearGradient>` /\n\t * `<radialGradient>` descriptors and `pattern`s (conic, diamond and stroke-mode gradients:\n\t * draw each of `gradients`, then each tile filled, inside a `<pattern>`).\n\t */\n\tdefs: VectorPaintDef[];\n\t/** Visible nodes, bottom to top. */\n\tnodes: VectorRenderNode[];\n}\n\nexport interface VectorRenderAnchor {\n\tref: VectorAnchorRef;\n\t/** Screen position. */\n\tx: number;\n\ty: number;\n\ttype: VectorAnchorType;\n\tselected: boolean;\n\thovered: boolean;\n\t/** The pen tool closes the path when this anchor is clicked. */\n\tcloses: boolean;\n}\n\nexport interface VectorRenderHandle {\n\tref: VectorHandleRef;\n\tx: number;\n\ty: number;\n\t/** Screen position of the handle's anchor (draw a line to it). */\n\tanchorX: number;\n\tanchorY: number;\n\thovered: boolean;\n}\n\n/** A live corner widget in screen pixels. */\nexport interface VectorRenderCornerWidget {\n\tref: VectorAnchorRef;\n\tx: number;\n\ty: number;\n\tradius: number;\n\tkind: VectorCornerKind;\n\thovered: boolean;\n\t/** Its corners are being dragged. */\n\tactive: boolean;\n}\n\n/**\n * A width point of the width tool in screen pixels: a diamond at (`x`, `y`) on the path and a\n * line across the stroke from `left` to `right`, with a handle at each end.\n */\nexport interface VectorRenderWidthPoint {\n\tref: VectorWidthPointRef;\n\tx: number;\n\ty: number;\n\tleft: Vec2;\n\tright: Vec2;\n\tselected: boolean;\n\t/** The part under the pointer, if any. */\n\thovered: 'center' | 'left' | 'right' | null;\n\t/** Being dragged. */\n\tactive: boolean;\n}\n\n/** A smart guide line in screen pixels. */\nexport interface VectorRenderGuideLine {\n\tkind: VectorGuideKind;\n\tx1: number;\n\ty1: number;\n\tx2: number;\n\ty2: number;\n}\n\n/** A smart guide label (\"anchor\", \"intersect\", \"align\", \"centre\", a gap or a size) at a screen position. */\nexport interface VectorRenderGuideLabel {\n\tkind: VectorSnapKind;\n\tx: number;\n\ty: number;\n\ttext: string;\n}\n\nexport interface VectorOverlayRenderData {\n\t/** Outlines (screen-space path data) of hovered and selected nodes. */\n\toutlines: { id: string; d: string; selected: boolean }[];\n\t/**\n\t * Selection box with resize and rotate handles (select tool). `x / y / width / height` and\n\t * each handle's `x / y` are the unrotated box in screen pixels: draw them inside\n\t * `<g transform={transform}>`. `corners` and each handle's `screen` are true positions.\n\t */\n\tselectionBox:\n\t\t| (VectorBounds & { angle: number; transform: string; corners: Vec2[]; handles: VectorSelectionBoxGeometry['handles']; freeDistort: boolean })\n\t\t| null;\n\t/**\n\t * A Free Distort drag (screen space): the quad the selection box's corners make so far (`d`,\n\t * closed path data) and its corners clockwise from the top left. The box is hidden meanwhile.\n\t */\n\tdistort: { mode: 'distort' | 'perspective' | 'skew'; d: string; corners: Vec2[] } | null;\n\t/**\n\t * The Envelope tool's mesh of the selected envelope (screen space): `grid` is the grid lines as\n\t * path data, `anchors` the points where they cross and `handles` the handles along them, each\n\t * with the anchor it belongs to (`index` is the point's index in the mesh). Draw anchors as\n\t * squares and handles as dots joined to their anchors.\n\t */\n\tenvelope: {\n\t\tnodeId: string;\n\t\tgrid: string;\n\t\tanchors: { index: number; x: number; y: number; hovered: boolean; active: boolean }[];\n\t\thandles: { index: number; x: number; y: number; anchorX: number; anchorY: number; hovered: boolean; active: boolean }[];\n\t} | null;\n\tanchors: VectorRenderAnchor[];\n\thandles: VectorRenderHandle[];\n\t/** Marquee rectangle, screen space. */\n\tmarquee: VectorBounds | null;\n\t/** Rubber-band segment from the pen path's last anchor to the pointer, screen space. */\n\tpenPreview: string | null;\n\t/** Artboard rectangle, screen space. */\n\tartboard: VectorBounds;\n\t/** Smart guides of the snap in progress, screen space (empty when nothing snapped). */\n\tguides: { lines: VectorRenderGuideLine[]; labels: VectorRenderGuideLabel[] };\n\t/**\n\t * The knife or eraser stroke being drawn, screen space: `d` is an open polyline; draw the\n\t * eraser's with a round-capped stroke `width` pixels wide (0 for the knife: a thin line).\n\t */\n\ttoolStroke: { tool: 'knife' | 'eraser'; d: string; width: number } | null;\n\t/** The pencil's lazy-mouse string from the pen to the pointer, screen space. */\n\tpencilString: { x1: number; y1: number; x2: number; y2: number } | null;\n\t/** Where the scissors would cut (screen space). */\n\tcutPoint: Vec2 | null;\n\t/**\n\t * Live corner widgets of the direct tool (screen space): drag one to round its corners,\n\t * Alt-click to cycle round / inverted / chamfer, click to pick its corner alone.\n\t */\n\tcornerWidgets: VectorRenderCornerWidget[];\n\t/** Width points of the width tool (screen space). */\n\twidthPoints: VectorRenderWidthPoint[];\n\t/**\n\t * Where a width-tool drag would add a width point (screen space): draw a dashed line from\n\t * `left` to `right` and a hollow diamond at (`x`, `y`).\n\t */\n\twidthSpot: { x: number; y: number; left: Vec2; right: Vec2 } | null;\n\t/**\n\t * Shape Builder and paint bucket highlight (screen space): `faces` are filled paths (fill\n\t * them translucent and outline them), `hatches` the 45° hatch lines over each face\n\t * (`hatchPath`, a few pixels apart; merge and erase only, empty strings for the paint\n\t * bucket: stroke them over the translucent fill), `lines` are the line pieces and outline\n\t * edges an erase deletes, `trail` is the drag's polyline. `mode` is `merge`, `erase` (Alt)\n\t * or `fill` (paint bucket).\n\t */\n\tbuilder: { mode: 'merge' | 'erase' | 'fill'; faces: string[]; hatches: string[]; lines: string[]; trail: string | null } | null;\n\t/**\n\t * Blends (screen space): the spine of each selected blend (`d`, draw it dashed; `keys` are\n\t * where its keys sit on it; `replaced` when it is a replaced spine) and, with the Blend tool,\n\t * the outline of the shape it blends from (`start`, with the clicked anchor) and the anchors\n\t * of the first subpath under the pointer (click one to start the blend there).\n\t */\n\tblend: {\n\t\tspines: { id: string; d: string; keys: Vec2[]; replaced: boolean }[];\n\t\tstart: { d: string; anchor: Vec2 | null } | null;\n\t\tanchors: { x: number; y: number; hovered: boolean }[];\n\t};\n\t/** The gradient tool's annotator over the selection's gradient (screen space), or null. */\n\tgradient: VectorRenderGradientAnnotator | null;\n\t/** A short status, e.g. \"W 120 × H 80\" or \"45°\". */\n\tstatus: string | null;\n}\n\n/**\n * The gradient annotator in screen pixels: draw the `extent` outline (dashed), the bar from\n * `start` to `end`, the handles, each stop's chip (a swatch at `x, y` with a tick to `barX, barY`;\n * `removing`: the dragged stop is off the bar and will be deleted, draw it faded) and the\n * midpoint diamonds.\n */\nexport interface VectorRenderGradientAnnotator {\n\tnodeId: string;\n\ttype: VectorGradientType;\n\tstart: { x: number; y: number; hovered: boolean };\n\t/** `radius` for radial, conic and diamond gradients. */\n\tend: { x: number; y: number; hovered: boolean; handle: 'end' | 'radius' };\n\taspect: { x: number; y: number; hovered: boolean } | null;\n\tfocal: { x: number; y: number; hovered: boolean } | null;\n\tstops: { index: number; x: number; y: number; barX: number; barY: number; color: string; opacity: number; selected: boolean; hovered: boolean }[];\n\tmidpoints: { index: number; x: number; y: number; hovered: boolean }[];\n\textent: string | null;\n\tremoving: boolean;\n}\n\nconst fmt = (n: number) => Math.round(n * 100) / 100;\nconst fmtMatrix = (m: AffineMatrix) => `matrix(${m.map((n) => Math.round(n * 1e6) / 1e6).join(' ')})`;\n/** Distance between the Shape Builder's hatch lines over a face (screen pixels). */\nexport const VECTOR_BUILDER_HATCH_GAP = 6;\n\nfunction renderNode(stored: VectorNode, defs: VectorPaintDef[], idPrefix: string): VectorRenderNode | null {\n\tif (stored.visible === false) return null;\n\t// Path effects and live booleans draw as their expanded shapes.\n\tconst node = expandVectorAppearance(stored);\n\tif (node.type === 'group') {\n\t\tconst children = node.children.map((c) => renderNode(c, defs, idPrefix)).filter((c): c is VectorRenderNode => !!c);\n\t\treturn { kind: 'group', id: node.id, ...(node.transform ? { transform: fmtMatrix(node.transform) } : {}), opacity: node.opacity ?? 1, children };\n\t}\n\tconst fill = vectorPaintToSvg(node.fill, `${idPrefix}fill-${node.id}`, { node });\n\tconst stroke = vectorPaintToSvg(node.stroke, `${idPrefix}stroke-${node.id}`, { node, role: 'stroke' });\n\tdefs.push(...fill.defs, ...stroke.defs);\n\tconst strokeParts = stroke.value !== 'none' ? vectorStrokeSvgParts(node, `${idPrefix}clip-${node.id}`) : undefined;\n\treturn {\n\t\tkind: 'path',\n\t\tid: node.id,\n\t\t...(node.transform ? { transform: fmtMatrix(node.transform) } : {}),\n\t\t...(strokeParts ? { strokeParts } : {}),\n\t\td: vectorPathData(node),\n\t\tfill: fill.value,\n\t\tstroke: stroke.value,\n\t\tstrokeWidth: node.strokeWidth ?? 1,\n\t\t...(node.strokeLinecap ? { strokeLinecap: node.strokeLinecap } : {}),\n\t\t...(node.strokeLinejoin ? { strokeLinejoin: node.strokeLinejoin } : {}),\n\t\t...(node.strokeDasharray?.length ? { strokeDasharray: node.strokeDasharray.join(' ') } : {}),\n\t\tfillRule: node.fillRule ?? 'nonzero',\n\t\topacity: node.opacity ?? 1\n\t};\n}\n\n/**\n * The document layer. Render the nodes inside `<g transform={transform}>` and `defs` in a\n * `<defs>` block. Pass a unique `idPrefix` when several editors share a page.\n */\nexport function getVectorSceneRenderData(state: Pick<VectorEditorState, 'document' | 'viewport'>, options: { idPrefix?: string } = {}): VectorSceneRenderData {\n\tconst defs: VectorPaintDef[] = [];\n\tconst prefix = options.idPrefix ?? 've-';\n\tconst nodes = state.document.nodes.map((n) => renderNode(n, defs, prefix)).filter((n): n is VectorRenderNode => !!n);\n\tconst v = state.viewport;\n\treturn {\n\t\ttransform: `translate(${fmt(v.x)} ${fmt(v.y)}) scale(${v.zoom})`,\n\t\twidth: state.document.width,\n\t\theight: state.document.height,\n\t\t...(state.document.background ? { background: state.document.background } : {}),\n\t\tdefs,\n\t\tnodes\n\t};\n}\n\nconst toScreen = (state: Pick<VectorEditorState, 'viewport'>, p: Vec2) => ({ x: p.x * state.viewport.zoom + state.viewport.x, y: p.y * state.viewport.zoom + state.viewport.y });\n\nfunction screenOutline(state: VectorEditorState, node: VectorNode, entered: ReadonlySet<string>): string {\n\tconst v = state.viewport;\n\tconst view: AffineMatrix = [v.zoom, 0, 0, v.zoom, v.x, v.y];\n\tconst parent = vectorParentMatrix(state.document.nodes, node.id) ?? IDENTITY_MATRIX;\n\treturn outlinePaths(node, parent, entered)\n\t\t.map((path) => bezierPathToSvg(transformBezierPath(path, view), { precision: 2 }))\n\t\t.join(' ');\n}\n\n/**\n * Document-space outlines of a subtree: paths as stored (their anchors are what is edited; the\n * scene shows their effects), live groups as drawn unless they are being edited (then their\n * children, as figcraft outlines a boolean group's operands).\n */\nfunction outlinePaths(node: VectorNode, parent: AffineMatrix, entered: ReadonlySet<string>): BezierPath[] {\n\tif (node.type === 'path') return [vectorPathWorldBezier(node, parent, { effects: false })];\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\tif (hasOwnVectorAppearance(node) && !entered.has(node.id)) return [transformBezierPath(vectorAppearanceOutline(node), m)];\n\treturn node.children.filter((c) => c.visible !== false).flatMap((c) => outlinePaths(c, m, entered));\n}\n\n/** Live groups being edited in `state` (see `vectorEnteredGroups`). */\nexport function getVectorEnteredGroups(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId'>): Set<string> {\n\treturn vectorEnteredGroups(state.document.nodes, state.editingId ? [...state.selection, state.editingId] : state.selection);\n}\n\nfunction collect(node: VectorNode): VectorPathNode[] {\n\tif (node.type === 'path') return [node];\n\treturn node.children.flatMap(collect);\n}\n\n/** The editing overlay in screen pixels. Render it on top of the scene, untransformed. */\nexport function getVectorOverlayRenderData(state: VectorEditorState): VectorOverlayRenderData {\n\tconst doc = state.document;\n\tconst z = state.viewport.zoom;\n\tconst outlines: VectorOverlayRenderData['outlines'] = [];\n\tconst entered = getVectorEnteredGroups(state);\n\tconst seen = new Set<string>();\n\tconst outline = (id: string, selected: boolean) => {\n\t\tif (seen.has(id)) return;\n\t\tconst node = findVectorNode(doc.nodes, id);\n\t\tif (!node || node.visible === false) return;\n\t\tseen.add(id);\n\t\toutlines.push({ id, d: screenOutline(state, node, entered), selected });\n\t};\n\tfor (const id of state.selection) outline(id, true);\n\tif (state.editingId) outline(state.editingId, true);\n\tif (state.hover?.nodeId && !state.interaction) outline(state.hover.nodeId, false);\n\n\tlet selectionBox: VectorOverlayRenderData['selectionBox'] = null;\n\tif (state.tool === 'select' && state.selectionFrame && state.interaction?.type !== 'marquee' && state.interaction?.type !== 'distort') {\n\t\tconst g = getVectorSelectionBoxGeometry(state.selectionFrame, state.viewport);\n\t\tselectionBox = { ...g.box, angle: g.angle, transform: g.transform, corners: g.corners, handles: g.handles, freeDistort: state.freeDistort };\n\t}\n\n\tconst selected = (r: VectorAnchorRef) => state.selectedAnchors.some((a) => a.nodeId === r.nodeId && a.subpath === r.subpath && a.index === r.index);\n\tconst sameAnchor = (a: VectorAnchorRef | undefined, b: VectorAnchorRef) => !!a && a.nodeId === b.nodeId && a.subpath === b.subpath && a.index === b.index;\n\tconst anchors: VectorRenderAnchor[] = getVisibleAnchors(state).map((ref) => {\n\t\tconst a = getAnchorWorld(doc, ref)!;\n\t\tconst s = toScreen(state, a);\n\t\tconst closes = !!state.pen && state.pen.nodeId === ref.nodeId && state.pen.subpath === ref.subpath && ref.index === 0;\n\t\treturn { ref, x: s.x, y: s.y, type: a.type ?? inferAnchorType(a), selected: selected(ref), hovered: sameAnchor(state.hover?.anchor, ref), closes };\n\t});\n\tif (state.tool === 'pen' && !state.pen && state.hover?.anchor) {\n\t\tconst a = getAnchorWorld(doc, state.hover.anchor);\n\t\tif (a) {\n\t\t\tconst s = toScreen(state, a);\n\t\t\tanchors.push({ ref: state.hover.anchor, x: s.x, y: s.y, type: a.type ?? 'corner', selected: false, hovered: true, closes: false });\n\t\t}\n\t}\n\n\tconst handles: VectorRenderHandle[] = getVisibleHandles(state).flatMap((ref) => {\n\t\tconst a = getAnchorWorld(doc, ref);\n\t\tconst h = a?.[ref.handle];\n\t\tif (!a || !h) return [];\n\t\tconst s = toScreen(state, h);\n\t\tconst sa = toScreen(state, a);\n\t\tconst hovered = !!state.hover?.handle && sameAnchor(state.hover.handle, ref) && state.hover.handle.handle === ref.handle;\n\t\treturn [{ ref, x: s.x, y: s.y, anchorX: sa.x, anchorY: sa.y, hovered }];\n\t});\n\n\tlet marquee: VectorBounds | null = null;\n\tif (state.interaction?.type === 'marquee') {\n\t\tconst b = state.interaction.bounds;\n\t\tconst tl = toScreen(state, b);\n\t\tmarquee = { x: tl.x, y: tl.y, width: b.width * z, height: b.height * z };\n\t}\n\n\tlet penPreview: string | null = null;\n\tif (state.tool === 'pen' && state.pen && state.pointer && !state.interaction) {\n\t\tconst node = findVectorNode(doc.nodes, state.pen.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[state.pen.subpath] : undefined;\n\t\tconst last = sp ? getAnchorWorld(doc, { nodeId: state.pen.nodeId, subpath: state.pen.subpath, index: sp.anchors.length - 1 }) : undefined;\n\t\tif (last) {\n\t\t\tconst a = toScreen(state, last);\n\t\t\tconst p = toScreen(state, state.pointer);\n\t\t\tconst c = last.out ? toScreen(state, last.out) : null;\n\t\t\tpenPreview = c ? `M${fmt(a.x)} ${fmt(a.y)}Q${fmt(c.x)} ${fmt(c.y)} ${fmt(p.x)} ${fmt(p.y)}` : `M${fmt(a.x)} ${fmt(a.y)}L${fmt(p.x)} ${fmt(p.y)}`;\n\t\t}\n\t}\n\n\tconst origin = toScreen(state, { x: 0, y: 0 });\n\tconst artboard = { x: origin.x, y: origin.y, width: doc.width * z, height: doc.height * z };\n\n\tlet status: string | null = null;\n\tconst it = state.interaction;\n\tif (it?.type === 'rotate') status = `${Math.round(it.angle)}°`;\n\telse if (it?.type === 'move' || it?.type === 'anchors') status = `Δ ${fmt(it.dx)}, ${fmt(it.dy)}`;\n\telse if (it?.type === 'scale' || it?.type === 'draw') {\n\t\tconst b = it.type === 'draw' ? (findVectorNode(doc.nodes, it.nodeId) ? vectorNodeBounds(findVectorNode(doc.nodes, it.nodeId)!) : null) : state.selectionFrame;\n\t\tif (b) status = `W ${fmt(b.width)} × H ${fmt(b.height)}`;\n\t}\n\n\tconst guides: VectorOverlayRenderData['guides'] = { lines: [], labels: [] };\n\tif (state.guides) {\n\t\tfor (const l of state.guides.lines) {\n\t\t\tconst a = toScreen(state, { x: l.x1, y: l.y1 });\n\t\t\tconst b = toScreen(state, { x: l.x2, y: l.y2 });\n\t\t\tguides.lines.push({ kind: l.kind, x1: fmt(a.x), y1: fmt(a.y), x2: fmt(b.x), y2: fmt(b.y) });\n\t\t}\n\t\tfor (const l of state.guides.labels) {\n\t\t\tconst p = toScreen(state, l);\n\t\t\tguides.labels.push({ kind: l.kind, x: fmt(p.x), y: fmt(p.y), text: l.text });\n\t\t}\n\t}\n\n\tlet toolStroke: VectorOverlayRenderData['toolStroke'] = null;\n\tif (it?.type === 'stroke') {\n\t\tconst pts = it.points.map((q) => toScreen(state, q));\n\t\tconst d = pts.map((q, i) => `${i ? 'L' : 'M'}${fmt(q.x)} ${fmt(q.y)}`).join('') + (pts.length === 1 ? `L${fmt(pts[0].x)} ${fmt(pts[0].y)}` : '');\n\t\ttoolStroke = { tool: it.tool, d, width: fmt(it.width * z) };\n\t}\n\tlet pencilString: VectorOverlayRenderData['pencilString'] = null;\n\tif (it?.type === 'draw' && it.string) {\n\t\tconst a = toScreen(state, it.string[0]);\n\t\tconst b = toScreen(state, it.string[1]);\n\t\tpencilString = { x1: fmt(a.x), y1: fmt(a.y), x2: fmt(b.x), y2: fmt(b.y) };\n\t}\n\tconst dragged = it?.type === 'corner' ? it.ref : null;\n\tconst cornerWidgets: VectorRenderCornerWidget[] = getVectorCornerWidgets(state).map((w) => {\n\t\tconst s = toScreen(state, w);\n\t\treturn { ref: w.ref, x: fmt(s.x), y: fmt(s.y), radius: w.radius, kind: w.kind, hovered: sameAnchor(state.hover?.corner, w.ref), active: !!dragged };\n\t});\n\tif (it?.type === 'corner') status = `R ${fmt(it.radius)}`;\n\tconst cutPoint = state.tool === 'scissors' && state.hover?.segment && !it ? (({ x, y }) => ({ x: fmt(x), y: fmt(y) }))(toScreen(state, state.hover.segment.point)) : null;\n\n\tconst sc = (p: Vec2) => {\n\t\tconst q = toScreen(state, p);\n\t\treturn { x: fmt(q.x), y: fmt(q.y) };\n\t};\n\tconst sameWidth = (a: VectorWidthPointRef | null | undefined, b: VectorWidthPointRef) => !!a && a.nodeId === b.nodeId && a.index === b.index;\n\tconst widthPoints: VectorRenderWidthPoint[] = getVectorWidthHandles(state).map((h) => {\n\t\tconst c = sc(h);\n\t\tconst hw = state.hover?.widthPoint;\n\t\tconst hovered = hw && sameWidth(hw, h.ref) && hw.subpath === h.ref.subpath ? hw.part : null;\n\t\treturn { ref: h.ref, x: c.x, y: c.y, left: sc(h.left), right: sc(h.right), selected: h.selected, hovered, active: it?.type === 'width' && sameWidth(it.ref, h.ref) };\n\t});\n\tconst spot = state.tool === 'width' && !it ? state.hover?.strokeSpot : null;\n\tconst widthSpot = spot ? { ...sc(spot.point), left: sc(spot.left), right: sc(spot.right) } : null;\n\tif (it?.type === 'width') status = it.mode === 'move' ? 'Move width point' : it.mode === 'copy' ? 'Copy width point' : `W ${fmt(it.width)}`;\n\n\tlet builder: VectorOverlayRenderData['builder'] = null;\n\tif (state.builder) {\n\t\tconst v = state.viewport;\n\t\tconst view: AffineMatrix = [v.zoom, 0, 0, v.zoom, v.x, v.y];\n\t\tconst svg = (path: BezierPath) => bezierPathToSvg(path, { precision: 2 });\n\t\tconst screen = state.builder.faces.map((f) => transformBezierPath(f, view));\n\t\tconst hatch = state.builder.mode !== 'fill';\n\t\tconst trail = state.builder.trail && state.builder.trail.length > 1 ? state.builder.trail.map((q, i) => `${i ? 'L' : 'M'}${sc(q).x} ${sc(q).y}`).join('') : null;\n\t\tbuilder = {\n\t\t\tmode: state.builder.mode,\n\t\t\tfaces: screen.map(svg),\n\t\t\thatches: screen.map((f) => (hatch ? svg(hatchPath(f, { gap: VECTOR_BUILDER_HATCH_GAP })) : '')),\n\t\t\tlines: state.builder.lines.map((l) => svg(transformBezierPath(l, view))),\n\t\t\ttrail\n\t\t};\n\t\tif (state.builder.mode !== 'fill' && it?.type === 'builder') {\n\t\t\tconst n = state.builder.faces.length;\n\t\t\tstatus = state.builder.mode === 'erase' ? `Delete ${n} ${n === 1 ? 'face' : 'faces'}` : `Merge ${n} ${n === 1 ? 'face' : 'faces'}`;\n\t\t}\n\t}\n\n\tconst blend = blendOverlay(state);\n\tif (state.tool === 'blend' && !it) status = state.blendStart ? 'Click another shape to blend into' : 'Click a shape to blend from';\n\n\tlet gradient: VectorRenderGradientAnnotator | null = null;\n\tif (state.tool === 'gradient') {\n\t\tgradient = gradientOverlay(state);\n\t\tif (!gradient && !it) status = 'Drag across a shape to set a gradient';\n\t\telse if (it?.type === 'gradient' && it.removing) status = 'Release to delete the stop';\n\t}\n\n\tlet distort: VectorOverlayRenderData['distort'] = null;\n\tif (it?.type === 'distort') {\n\t\tconst corners = it.corners.map(sc);\n\t\tdistort = { mode: it.mode, corners, d: corners.map((c, i) => `${i ? 'L' : 'M'}${c.x} ${c.y}`).join('') + 'Z' };\n\t\tstatus = it.mode === 'skew' ? 'Skew' : it.mode === 'perspective' ? 'Perspective' : 'Distort';\n\t}\n\n\tconst envelope = state.tool === 'envelope' ? envelopeOverlay(state) : null;\n\tif (state.tool === 'envelope' && !envelope && !it) status = 'Select an object with an envelope to edit its mesh';\n\n\treturn { outlines, selectionBox, distort, anchors, handles, marquee, penPreview, artboard, guides, status, toolStroke, pencilString, cutPoint, cornerWidgets, widthPoints, widthSpot, builder, blend, gradient, envelope };\n}\n\nfunction envelopeOverlay(state: VectorEditorState): VectorOverlayRenderData['envelope'] {\n\tconst target = getVectorEnvelopeTarget(state.document, state.selection);\n\tif (!target) return null;\n\tconst v = state.viewport;\n\tconst m = multiplyMatrices(target.world, [v.zoom, 0, 0, v.zoom, v.x, v.y]);\n\tconst sc = (p: Vec2) => ({ x: fmt(m[0] * p.x + m[2] * p.y + m[4]), y: fmt(m[1] * p.x + m[3] * p.y + m[5]) });\n\tconst { mesh } = target.frame;\n\tconst grid = vectorMeshGridCurves(mesh)\n\t\t.map((c) => {\n\t\t\tconst [a, b, cc, d] = c.map(sc);\n\t\t\treturn `M${a.x} ${a.y}C${b.x} ${b.y} ${cc.x} ${cc.y} ${d.x} ${d.y}`;\n\t\t})\n\t\t.join('');\n\tconst hover = state.hover?.envelope?.nodeId === target.node.id ? state.hover.envelope.index : undefined;\n\tconst it = state.interaction;\n\tconst active = it?.type === 'envelope' && it.nodeId === target.node.id ? it.index : undefined;\n\tconst pts = vectorMeshEditPoints(mesh);\n\treturn {\n\t\tnodeId: target.node.id,\n\t\tgrid,\n\t\tanchors: pts.anchors.map((index) => ({ index, ...sc(mesh.points[index]), hovered: !it && hover === index, active: active === index })),\n\t\thandles: pts.handles.map((h) => {\n\t\t\tconst a = sc(mesh.points[h.anchor]);\n\t\t\treturn { index: h.index, ...sc(mesh.points[h.index]), anchorX: a.x, anchorY: a.y, hovered: !it && hover === h.index, active: active === h.index };\n\t\t})\n\t};\n}\n\n/** Warp choices of an envelope: the fifteen presets, then Mesh. */\nexport const VECTOR_ENVELOPE_STYLE_OPTIONS: readonly { value: VectorEnvelopeParams['style']; label: string }[] = [\n\t...VECTOR_WARP_STYLES.map((value) => ({ value, label: VECTOR_WARP_STYLE_LABELS[value] })),\n\t{ value: 'mesh', label: 'Mesh' }\n];\n\n/** What a Distort / Envelope panel shows for the selection. */\nexport interface VectorEnvelopePanelData {\n\t/** The one selected node, or null when several are selected. */\n\tnodeId: string | null;\n\tcount: number;\n\t/** The selected node's envelope (the first one in its stack), if any. */\n\tenvelope: { effectId: string; enabled: boolean; params: VectorEnvelopeParams } | null;\n\t/** Some selected node can take an envelope (Make with Warp / Mesh). */\n\tcanMake: boolean;\n\t/** Make with Top Object: several objects selected and the topmost is a closed path. */\n\tcanMakeWithTopObject: boolean;\n\t/** Some selected node has an envelope (Release, Expand). */\n\tcanRelease: boolean;\n}\n\n/** The Distort / Envelope panel of the selection, or null when nothing is selected. */\nexport function getVectorEnvelopePanel(state: Pick<VectorEditorState, 'document' | 'selection'>): VectorEnvelopePanelData | null {\n\tconst nodes = state.selection.map((id) => findVectorNode(state.document.nodes, id)).filter((n): n is VectorNode => !!n && !n.blendStep);\n\tif (!nodes.length) return null;\n\tconst one = nodes.length === 1 ? nodes[0] : null;\n\tconst first = one?.effects?.find((e) => e.type === 'envelope');\n\tconst order = new Map<string, number>();\n\twalkVectorNodes(state.document.nodes, (n) => order.set(n.id, order.size));\n\tconst top = nodes.length > 1 ? nodes.slice().sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))[nodes.length - 1] : null;\n\treturn {\n\t\tnodeId: one?.id ?? null,\n\t\tcount: nodes.length,\n\t\tenvelope: first?.type === 'envelope' ? { effectId: first.id, enabled: first.enabled !== false, params: first.params } : null,\n\t\tcanMake: nodes.some((n) => !n.locked),\n\t\tcanMakeWithTopObject: top?.type === 'path' && top.subpaths.some((sp) => sp.closed && sp.anchors.length > 1),\n\t\tcanRelease: nodes.some((n) => !n.locked && !!n.effects?.some((e) => e.type === 'envelope'))\n\t};\n}\n\nfunction gradientOverlay(state: VectorEditorState): VectorRenderGradientAnnotator | null {\n\tconst a = getVectorGradientAnnotator(state.document, state.selection, state.viewport, state.gradientEdit.target);\n\tif (!a) return null;\n\tconst hover = state.interaction ? null : state.hover?.gradient;\n\tconst handleHovered = (h: VectorGradientHandle) => hover?.kind === 'handle' && hover.handle === h;\n\tconst pt = (p: Vec2) => ({ x: fmt(p.x), y: fmt(p.y) });\n\tconst centred = isCentredVectorGradient(a.gradient.type);\n\tconst removing = state.interaction?.type === 'gradient' && !!state.interaction.removing;\n\treturn {\n\t\tnodeId: a.nodeId,\n\t\ttype: a.gradient.type,\n\t\tstart: { ...pt(a.start), hovered: handleHovered('start') },\n\t\tend: { ...pt(a.end), hovered: handleHovered(centred ? 'radius' : 'end'), handle: centred ? 'radius' : 'end' },\n\t\taspect: a.aspect ? { ...pt(a.aspect), hovered: handleHovered('aspect') } : null,\n\t\tfocal: a.focal ? { ...pt(a.focal), hovered: handleHovered('focal') } : null,\n\t\tstops: a.stops.map((s) => ({\n\t\t\tindex: s.index,\n\t\t\t...pt(s),\n\t\t\tbarX: fmt(s.x - a.normal.x * VECTOR_GRADIENT_STOP_GAP),\n\t\t\tbarY: fmt(s.y - a.normal.y * VECTOR_GRADIENT_STOP_GAP),\n\t\t\tcolor: s.color,\n\t\t\topacity: s.opacity ?? 1,\n\t\t\tselected: state.gradientEdit.stop === s.index,\n\t\t\thovered: hover?.kind === 'stop' && hover.index === s.index\n\t\t})),\n\t\tmidpoints: a.midpoints.map((m) => ({ index: m.index, ...pt(m), hovered: hover?.kind === 'midpoint' && hover.index === m.index })),\n\t\textent: a.extent,\n\t\tremoving\n\t};\n}\n\n/** Blend groups the selection covers (a selected key counts as its blend). */\nfunction selectedBlends(state: Pick<VectorEditorState, 'document' | 'selection'>): VectorGroupNode[] {\n\tconst out = new Map<string, VectorGroupNode>();\n\tfor (const id of state.selection) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tconst group = isVectorBlendGroup(node) ? node : locateVectorNode(state.document.nodes, id)?.parent;\n\t\tif (isVectorBlendGroup(group)) out.set(group.id, group);\n\t}\n\treturn [...out.values()];\n}\n\nfunction blendOverlay(state: VectorEditorState): VectorOverlayRenderData['blend'] {\n\tconst v = state.viewport;\n\tconst view: AffineMatrix = [v.zoom, 0, 0, v.zoom, v.x, v.y];\n\tconst doc = state.document;\n\tconst sc = (p: Vec2, m: AffineMatrix) => {\n\t\tconst q = { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] };\n\t\treturn { x: fmt(q.x), y: fmt(q.y) };\n\t};\n\tconst spines = selectedBlends(state).flatMap((g) => {\n\t\tconst s = vectorBlendSpine(g);\n\t\tif (!s) return [];\n\t\tconst m = multiplyMatrices(vectorWorldMatrix(doc.nodes, g.id) ?? IDENTITY_MATRIX, view);\n\t\tconst d = bezierPathToSvg(transformBezierPath(subpathsToBezier([s.spine], { corners: false }), m), { precision: 2 });\n\t\tconst keys = s.stops.map((stop) => {\n\t\t\tconst p = vectorBlendRailAt(s.rail, stop).point;\n\t\t\treturn sc({ x: p[0], y: p[1] }, m);\n\t\t});\n\t\treturn [{ id: g.id, d, keys, replaced: s.replaced }];\n\t});\n\tlet start: VectorOverlayRenderData['blend']['start'] = null;\n\tconst anchors: VectorOverlayRenderData['blend']['anchors'] = [];\n\tif (state.tool === 'blend') {\n\t\tconst from = state.blendStart ? findVectorNode(doc.nodes, state.blendStart.nodeId) : undefined;\n\t\tif (from && state.blendStart) {\n\t\t\tconst a = state.blendStart.anchor === null ? undefined : getAnchorWorld(doc, { nodeId: from.id, subpath: 0, index: state.blendStart.anchor });\n\t\t\tstart = { d: screenOutline(state, from, new Set()), anchor: a ? sc(a, view) : null };\n\t\t}\n\t\tconst hovered = state.hover?.nodeId ? findVectorNode(doc.nodes, state.hover.nodeId) : undefined;\n\t\tif (hovered?.type === 'path' && hovered.subpaths[0]) {\n\t\t\thovered.subpaths[0].anchors.forEach((_, index) => {\n\t\t\t\tconst a = getAnchorWorld(doc, { nodeId: hovered.id, subpath: 0, index });\n\t\t\t\tif (a) anchors.push({ ...sc(a, view), hovered: state.hover?.anchor?.index === index });\n\t\t\t});\n\t\t}\n\t}\n\treturn { spines, start, anchors };\n}\n\n/** What the Blend controls of a toolbar or style panel show. */\nexport interface VectorBlendControls {\n\t/** Ids of the selected blends (a selected key counts as its blend). */\n\tids: string[];\n\t/** The first selected blend's options, or the options new blends get. */\n\toptions: Required<VectorBlendOptions>;\n\t/** Two or more shapes that share a parent are selected: Blend can run. */\n\tcanBlend: boolean;\n\t/** One blend and one path are selected: Replace Spine can run. */\n\tcanReplaceSpine: boolean;\n\t/** The first selected blend follows a replaced spine. */\n\thasSpine: boolean;\n}\n\n/** State of the Blend controls for the current selection. */\nexport function getVectorBlendControls(state: Pick<VectorEditorState, 'document' | 'selection' | 'blendDefaults'>): VectorBlendControls {\n\tconst blends = selectedBlends(state);\n\tconst doc = state.document;\n\tconst roots = state.selection.filter((id) => {\n\t\tconst node = findVectorNode(doc.nodes, id);\n\t\treturn !!node && !node.blendStep && !node.locked && !state.selection.includes(locateVectorNode(doc.nodes, id)?.parent?.id ?? '');\n\t});\n\tconst parents = new Set(roots.map((id) => locateVectorNode(doc.nodes, id)?.parent?.id ?? null));\n\tconst paths = roots.filter((id) => findVectorNode(doc.nodes, id)?.type === 'path' && !isVectorBlendGroup(locateVectorNode(doc.nodes, id)?.parent));\n\tconst first = blends[0];\n\treturn {\n\t\tids: blends.map((g) => g.id),\n\t\toptions: resolveVectorBlendOptions(first ? first.blend : state.blendDefaults),\n\t\tcanBlend: roots.length >= 2 && parents.size === 1,\n\t\tcanReplaceSpine: blends.length === 1 && paths.length === 1,\n\t\thasSpine: !!first?.blend?.spine\n\t};\n}\n\n/**\n * Applies blend options from a toolbar: to the selected blends (one undo step) and to the\n * options new blends get, so the controls keep showing what was picked.\n */\nexport function applyVectorBlendOptions(controller: VectorEditorController, patch: Partial<VectorBlendOptions>): void {\n\tcontroller.setBlendDefaults(patch);\n\tif (getVectorBlendControls(controller.getState()).ids.length) controller.setBlendOptions(patch);\n}\n\n/** Labels of the blend spacing modes, for toolbars. */\nexport const VECTOR_BLEND_SPACING_LABELS: Readonly<Record<VectorBlendSpacing, string>> = { steps: 'Specified Steps', distance: 'Specified Distance', smoothColor: 'Smooth Color' };\n\n// ---------------------------------------------------------------------------\n// Event adapters (duck-typed, so they work with DOM, React and Svelte events)\n// ---------------------------------------------------------------------------\n\n/** Colours and sizes (screen pixels) the bundled canvases draw the overlay with. */\nexport const VECTOR_OVERLAY_THEME = {\n\taccent: '#0ea5e9',\n\t/** Smart guide lines and labels. */\n\tguide: '#ff3dfc',\n\thandleFill: '#ffffff',\n\tmarqueeFill: 'rgba(14, 165, 233, 0.08)',\n\t/** The eraser's swath while it is dragged. */\n\teraserFill: 'rgba(239, 68, 68, 0.25)',\n\ttransformHandleSize: 8,\n\tanchorSize: 7,\n\thandleRadius: 3.5,\n\t/** Radius of a live corner widget (a ring with a dot). */\n\tcornerWidgetRadius: 4,\n\t/** Half the diagonal of a width point's diamond. */\n\twidthPointSize: 5,\n\t/** Shape Builder faces to merge and paint bucket regions. */\n\tbuilderFill: 'rgba(14, 165, 233, 0.22)',\n\t/** Shape Builder faces and line pieces an Alt gesture deletes. */\n\tbuilderErase: '#ef4444',\n\tbuilderEraseFill: 'rgba(239, 68, 68, 0.22)',\n\t/** Opacity of the hatch lines over Shape Builder faces (drawn in the face's outline colour). */\n\tbuilderHatchOpacity: 0.6\n} as const;\n\n/** SVG path data of the diamond a width point is drawn with (screen pixels). */\nexport function vectorDiamondPath(x: number, y: number, r: number = VECTOR_OVERLAY_THEME.widthPointSize): string {\n\treturn `M${fmt(x)} ${fmt(y - r)}L${fmt(x + r)} ${fmt(y)}L${fmt(x)} ${fmt(y + r)}L${fmt(x - r)} ${fmt(y)}Z`;\n}\n\ninterface ModifierEventLike {\n\tshiftKey?: boolean;\n\taltKey?: boolean;\n\tmetaKey?: boolean;\n\tctrlKey?: boolean;\n}\n\n/** Modifiers of a mouse / pointer / key event (`mod` is Cmd or Ctrl). */\nexport function toVectorModifiers(event: ModifierEventLike): { shift: boolean; alt: boolean; mod: boolean } {\n\treturn { shift: !!event.shiftKey, alt: !!event.altKey, mod: !!(event.metaKey || event.ctrlKey) };\n}\n\n/**\n * A pointer event as `VectorEditorController.pointerDown/Move/Up` input: modifiers, button,\n * and the pressure and pointer type the pencil records as a width profile.\n */\nexport function toVectorPointerInput(event: ModifierEventLike & { button?: number; pressure?: number; pointerType?: string }) {\n\treturn {\n\t\t...toVectorModifiers(event),\n\t\tbutton: event.button,\n\t\t...(typeof event.pressure === 'number' ? { pressure: event.pressure } : {}),\n\t\t...(event.pointerType ? { pointerType: event.pointerType } : {})\n\t};\n}\n\n/** A key event as `VectorEditorController.keyDown/keyUp` input. */\nexport function toVectorKeyInput(event: ModifierEventLike & { key: string }) {\n\treturn { key: event.key, ...toVectorModifiers(event) };\n}\n\n/** True for targets that should keep their own keys (inputs, textareas, contenteditable). */\nexport function isVectorTextTarget(target: unknown): boolean {\n\tconst el = target as { tagName?: string; isContentEditable?: boolean; getAttribute?: (name: string) => string | null } | null;\n\tif (!el || typeof el !== 'object') return false;\n\tconst tag = (el.tagName ?? '').toUpperCase();\n\tif (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n\treturn !!el.isContentEditable || el.getAttribute?.('contenteditable') === 'true';\n}\n\n// ---------------------------------------------------------------------------\n// Style panel helpers\n// ---------------------------------------------------------------------------\n\n/** Style shown in a style panel: the first selected path's, with `mixed` flags when paths differ. */\nexport interface VectorSelectionStyle {\n\tfill: VectorPaint;\n\tstroke: VectorPaint;\n\tstrokeWidth: number;\n\topacity: number;\n\tstrokeAlign: VectorStrokeAlign;\n\tstartArrow: VectorArrowhead | null;\n\tendArrow: VectorArrowhead | null;\n\tarrowAlign: VectorArrowAlign;\n\tstartArrowScale: number;\n\tendArrowScale: number;\n\t/** The first path's width profile (null when uniform) and the preset it matches. */\n\tstrokeWidthProfile: VectorWidthPoint[] | null;\n\twidthProfile: VectorWidthPreset | 'custom';\n\t/**\n\t * Live corners of the selected anchors (direct tool) or of every corner of the selected\n\t * paths: the first one's radius and kind, and how many corners there are (0: none to round).\n\t */\n\tcornerRadius: number;\n\tcornerKind: VectorCornerKind;\n\tcorners: number;\n\t/** Some selected path is open, so arrowheads apply. */\n\thasOpenPath: boolean;\n\tmixed: {\n\t\tfill: boolean;\n\t\tstroke: boolean;\n\t\tstrokeWidth: boolean;\n\t\topacity: boolean;\n\t\tstrokeAlign: boolean;\n\t\tstartArrow: boolean;\n\t\tendArrow: boolean;\n\t\tarrowAlign: boolean;\n\t\tstartArrowScale: boolean;\n\t\tendArrowScale: boolean;\n\t\twidthProfile: boolean;\n\t\tcornerRadius: boolean;\n\t\tcornerKind: boolean;\n\t};\n\t/** Ids of the paths the style applies to. */\n\tpathIds: string[];\n}\n\nexport function getVectorSelectionStyle(\n\tstate: Pick<VectorEditorState, 'document' | 'selection'> & Partial<Pick<VectorEditorState, 'selectedAnchors' | 'tool'>>\n): VectorSelectionStyle | null {\n\tconst paths: VectorPathNode[] = [];\n\tfor (const id of state.selection) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node) paths.push(...collect(node));\n\t}\n\tconst anchorMode = state.tool === 'direct' && !!state.selectedAnchors?.length;\n\tif (anchorMode) {\n\t\tfor (const r of state.selectedAnchors!) {\n\t\t\tif (paths.some((p) => p.id === r.nodeId)) continue;\n\t\t\tconst node = findVectorNode(state.document.nodes, r.nodeId);\n\t\t\tif (node?.type === 'path') paths.push(node);\n\t\t}\n\t}\n\tif (!paths.length) return null;\n\tconst first = paths[0];\n\tconst same = (get: (p: VectorPathNode) => unknown) => paths.every((p) => JSON.stringify(get(p) ?? null) === JSON.stringify(get(first) ?? null));\n\t// Corners: those of the selected anchors in the direct tool, else every corner of the paths.\n\tconst corners: { radius: number; kind: VectorCornerKind }[] = [];\n\tfor (const p of paths) {\n\t\tfor (const c of vectorCorners(p.subpaths)) {\n\t\t\tif (anchorMode && !state.selectedAnchors!.some((r) => r.nodeId === p.id && r.subpath === c.subpath && r.index === c.index)) continue;\n\t\t\tconst corner = p.subpaths[c.subpath].anchors[c.index].corner;\n\t\t\tcorners.push({ radius: corner?.radius ?? 0, kind: corner?.kind ?? 'round' });\n\t\t}\n\t}\n\tconst c0 = corners[0] ?? { radius: 0, kind: 'round' as const };\n\treturn {\n\t\tfill: first.fill ?? null,\n\t\tstroke: first.stroke ?? null,\n\t\tstrokeWidth: first.strokeWidth ?? 1,\n\t\topacity: first.opacity ?? 1,\n\t\tstrokeAlign: first.strokeAlign ?? 'center',\n\t\tstartArrow: first.startArrow ?? null,\n\t\tendArrow: first.endArrow ?? null,\n\t\tarrowAlign: first.arrowAlign ?? 'extend',\n\t\tstartArrowScale: first.startArrowScale ?? 1,\n\t\tendArrowScale: first.endArrowScale ?? 1,\n\t\tstrokeWidthProfile: profileOf(first),\n\t\twidthProfile: widthProfilePresetId(profileOf(first)),\n\t\tcornerRadius: c0.radius,\n\t\tcornerKind: c0.kind,\n\t\tcorners: corners.length,\n\t\thasOpenPath: paths.some((p) => p.subpaths.some((sp) => !sp.closed && sp.anchors.length > 1)),\n\t\tmixed: {\n\t\t\tfill: !same((p) => p.fill),\n\t\t\tstroke: !same((p) => p.stroke),\n\t\t\tstrokeWidth: !same((p) => p.strokeWidth ?? 1),\n\t\t\topacity: !same((p) => p.opacity ?? 1),\n\t\t\tstrokeAlign: !same((p) => p.strokeAlign ?? 'center'),\n\t\t\tstartArrow: !same((p) => p.startArrow ?? null),\n\t\t\tendArrow: !same((p) => p.endArrow ?? null),\n\t\t\tarrowAlign: !same((p) => p.arrowAlign ?? 'extend'),\n\t\t\tstartArrowScale: !same((p) => p.startArrowScale ?? 1),\n\t\t\tendArrowScale: !same((p) => p.endArrowScale ?? 1),\n\t\t\twidthProfile: !same(profileOf),\n\t\t\tcornerRadius: corners.some((c) => c.radius !== c0.radius),\n\t\t\tcornerKind: corners.some((c) => c.kind !== c0.kind)\n\t\t},\n\t\tpathIds: paths.map((p) => p.id)\n\t};\n}\n\nfunction profileOf(p: VectorPathNode): VectorWidthPoint[] | null {\n\tconst points = sanitizeWidthProfile(p.strokeWidthProfile);\n\treturn points.length && widthProfilePresetId(points) !== 'uniform' ? points : null;\n}\n\n/** Labels of the stroke alignments, corner kinds and arrowheads, for style panels. */\nexport const VECTOR_STROKE_ALIGN_LABELS: Readonly<Record<VectorStrokeAlign, string>> = { center: 'Center', inside: 'Inside', outside: 'Outside' };\nexport const VECTOR_CORNER_KIND_LABELS: Readonly<Record<VectorCornerKind, string>> = { round: 'Round', inverted: 'Inverted', chamfer: 'Chamfer' };\nexport const VECTOR_ARROWHEAD_LABELS: Readonly<Record<VectorArrowhead, string>> = {\n\ttriangle: 'Triangle',\n\tarrow: 'Arrow',\n\topen: 'Open arrow',\n\tcircle: 'Circle',\n\tsquare: 'Square',\n\tbar: 'Bar'\n};\n\n/** A paint as `#rrggbb` for `<input type=\"color\">`, or null for none, gradients and other CSS colours. */\nexport function vectorPaintToHex(paint: VectorPaint | undefined): string | null {\n\tif (typeof paint !== 'string') return null;\n\tconst m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(paint.trim());\n\tif (!m) return null;\n\tconst hex = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];\n\treturn `#${hex.toLowerCase()}`;\n}\n\n// ---------------------------------------------------------------------------\n// Gradient editor\n// ---------------------------------------------------------------------------\n\nexport const VECTOR_GRADIENT_TYPE_LABELS: Readonly<Record<VectorGradientType, string>> = { linear: 'Linear', radial: 'Radial', conic: 'Conic', reflected: 'Reflected', diamond: 'Diamond' };\nexport const VECTOR_GRADIENT_SPREAD_LABELS: Readonly<Record<VectorGradientSpread, string>> = { pad: 'Pad', reflect: 'Reflect', repeat: 'Repeat' };\nexport const VECTOR_GRADIENT_INTERPOLATION_LABELS: Readonly<Record<VectorGradientInterpolation, string>> = { srgb: 'sRGB', linear: 'Linear light', oklab: 'Oklab' };\nexport const VECTOR_STROKE_GRADIENT_MODE_LABELS: Readonly<Record<VectorStrokeGradientMode, string>> = { within: 'Within stroke', along: 'Along stroke', across: 'Across stroke' };\n\n/** What a gradient editor shows for the selection's `target` paint (see `getVectorGradientEditor`). */\nexport interface VectorGradientEditorData {\n\ttarget: 'fill' | 'stroke';\n\t/** The first selected path's paint is a gradient. */\n\tgradient: VectorGradient | null;\n\t/** The paint as a `#rrggbb` colour when it is one (what a new gradient starts from). */\n\tcolor: string | null;\n\t/** Sorted stops; `index` is what `setGradientStop` takes. */\n\tstops: (VectorGradientStop & { index: number; selected: boolean })[];\n\tselected: (VectorGradientStop & { index: number; last: boolean }) | null;\n\t/** A CSS `linear-gradient(to right, …)` of the ramp (midpoints and colour space expanded). */\n\tpreview: string | null;\n\ttype: VectorGradientType | null;\n\tspread: VectorGradientSpread;\n\tinterpolation: VectorGradientInterpolation;\n\tsmoothness: number;\n\tstrokeMode: VectorStrokeGradientMode;\n\t/** The selected paths' gradients differ. */\n\tmixed: boolean;\n}\n\n/** The gradient editor of the selection's fill or stroke (`state.gradientEdit.target`), or null with nothing selected. */\nexport function getVectorGradientEditor(state: Pick<VectorEditorState, 'document' | 'selection' | 'gradientEdit'>): VectorGradientEditorData | null {\n\tconst paths: VectorPathNode[] = [];\n\tfor (const id of state.selection) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node) paths.push(...collect(node));\n\t}\n\tif (!paths.length) return null;\n\tconst target = state.gradientEdit.target;\n\tconst paint = paths[0][target];\n\tconst gradient = isVectorGradient(paint) ? paint : null;\n\tconst sorted = gradient ? sortedVectorGradientStops(gradient) : [];\n\tconst stopIndex = state.gradientEdit.stop;\n\tconst stops = sorted.map((s, index) => ({ ...s, index, selected: index === stopIndex }));\n\tconst sel = stopIndex !== null && sorted[stopIndex] ? { ...sorted[stopIndex], index: stopIndex, last: stopIndex === sorted.length - 1 } : null;\n\tconst preview = gradient\n\t\t? `linear-gradient(to right, ${expandVectorGradientStops(gradient)\n\t\t\t\t.map((s) => {\n\t\t\t\t\tconst c = parseVectorColor(s.color);\n\t\t\t\t\tconst a = (c?.[3] ?? 1) * (s.opacity ?? 1);\n\t\t\t\t\tconst color = c ? `rgba(${Math.round(c[0] * 255)}, ${Math.round(c[1] * 255)}, ${Math.round(c[2] * 255)}, ${Math.round(a * 1000) / 1000})` : s.color;\n\t\t\t\t\treturn `${color} ${Math.round(s.offset * 10000) / 100}%`;\n\t\t\t\t})\n\t\t\t\t.join(', ')})`\n\t\t: null;\n\treturn {\n\t\ttarget,\n\t\tgradient,\n\t\tcolor: vectorPaintToHex(paint),\n\t\tstops,\n\t\tselected: sel,\n\t\tpreview,\n\t\ttype: gradient?.type ?? null,\n\t\tspread: gradient?.spread ?? 'pad',\n\t\tinterpolation: gradient?.interpolation ?? 'srgb',\n\t\tsmoothness: gradient?.smoothness ?? 0,\n\t\tstrokeMode: gradient?.strokeMode ?? 'within',\n\t\tmixed: paths.some((p) => JSON.stringify(p[target] ?? null) !== JSON.stringify(paint ?? null))\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Toolbar helpers\n// ---------------------------------------------------------------------------\n\n/** A path-editing button of the bundled toolbars. */\nexport interface VectorPathAction {\n\tid: 'join' | 'average' | 'cut' | 'clean' | 'smooth' | 'outline';\n\tlabel: string;\n\ttitle: string;\n\t/** Shortcut after Cmd / Ctrl, if any. */\n\tshortcut?: string;\n\t/** Whether it can run with `selected` nodes and `points` selected anchors (direct tool). */\n\tenabled: (selected: number, points: number) => boolean;\n\trun: (controller: VectorEditorController) => unknown;\n}\n\n/** Join, Average, Cut at Points, Remove Redundant Points, Smooth and Outline Stroke, as the toolbars show them. */\nexport const VECTOR_PATH_ACTIONS: readonly VectorPathAction[] = [\n\t{ id: 'join', label: '⋈', title: 'Join', shortcut: 'J', enabled: (s, p) => s + p > 0, run: (c) => c.joinPaths() },\n\t{ id: 'average', label: '⊹', title: 'Average Points', shortcut: 'Alt+J', enabled: (_s, p) => p > 1, run: (c) => c.averageAnchors('both') },\n\t{ id: 'cut', label: '✂·', title: 'Cut at Points', enabled: (_s, p) => p > 0, run: (c) => c.cutAtAnchors() },\n\t{ id: 'clean', label: '⌁', title: 'Remove Redundant Points', enabled: (s, p) => s + p > 0, run: (c) => c.removeRedundantPoints() },\n\t{ id: 'smooth', label: '∿', title: 'Smooth', enabled: (s, p) => s + p > 0, run: (c) => c.smoothPaths() },\n\t{ id: 'outline', label: '⊡', title: 'Outline Stroke', enabled: (s) => s > 0, run: (c) => c.outlineStroke() }\n];\n\n/** A Pathfinder button of the bundled toolbars. */\nexport interface VectorPathfinderAction {\n\tid: VectorPathfinderOperation;\n\tlabel: string;\n\ttitle: string;\n\t/** Paths (or groups) it needs selected. */\n\tmin: number;\n}\n\n/** Divide, Trim, Merge, Crop, Outline and Minus Back, as the toolbars show them. */\nexport const VECTOR_PATHFINDER_ACTIONS: readonly VectorPathfinderAction[] = [\n\t{ id: 'divide', label: '⊞', title: 'Divide', min: 1 },\n\t{ id: 'trim', label: '⧉', title: 'Trim', min: 2 },\n\t{ id: 'merge', label: '⧈', title: 'Merge', min: 2 },\n\t{ id: 'crop', label: '⌗', title: 'Crop', min: 2 },\n\t{ id: 'outline', label: '⬚', title: 'Outline', min: 1 },\n\t{ id: 'minusBack', label: '⊖', title: 'Minus Back', min: 2 }\n];\n\n/** The on / off path-editing settings the toolbars toggle. */\nexport const VECTOR_EDIT_TOGGLES: readonly { key: 'keepShapeOnDelete' | 'curvatureMoves' | 'recognizeShapes'; label: string; title: string }[] = [\n\t{ key: 'keepShapeOnDelete', label: 'Keep', title: 'Keep shape when deleting points' },\n\t{ key: 'curvatureMoves', label: 'Curv', title: 'Curvature point moves (Alt flips while dragging)' },\n\t{ key: 'recognizeShapes', label: 'Shapes', title: 'Turn pencil scribbles into shapes' }\n];\n\n\n// ---------------------------------------------------------------------------\n// Effects panel\n// ---------------------------------------------------------------------------\n\n/** One effect of the listed stack, with what a panel needs to edit it. */\nexport interface VectorEffectsPanelItem {\n\tid: string;\n\ttype: VectorEffectType;\n\tlabel: string;\n\tenabled: boolean;\n\tparams: Record<string, unknown>;\n\t/** The parameters to edit (none for an envelope: `getVectorEnvelopePanel` and the Envelope panels edit it). */\n\tspecs: readonly VectorEffectParamSpec[];\n}\n\n/** What an Effects panel shows for the selection. */\nexport interface VectorEffectsPanelData {\n\t/** The node whose stack is listed (when one node is selected), else null. */\n\tnodeId: string | null;\n\t/** Selected nodes an added effect goes to. */\n\tcount: number;\n\t/** The listed stack, applied top to bottom. */\n\teffects: VectorEffectsPanelItem[];\n\t/** Something selected is live (Expand Appearance applies). */\n\texpandable: boolean;\n}\n\n/** Effect types in menu order, with their names. */\nexport const VECTOR_EFFECT_MENU: readonly { type: VectorEffectType; label: string }[] = VECTOR_EFFECT_TYPES.map((type) => ({ type, label: VECTOR_EFFECT_LABELS[type] }));\n\n/** The Effects panel of the selection, or null when nothing that takes effects is selected. */\nexport function getVectorEffectsPanel(state: Pick<VectorEditorState, 'document' | 'selection'>): VectorEffectsPanelData | null {\n\tconst nodes = state.selection.map((id) => findVectorNode(state.document.nodes, id)).filter((n): n is VectorNode => !!n && !n.blendStep);\n\tif (!nodes.length) return null;\n\tconst one = nodes.length === 1 ? nodes[0] : null;\n\treturn {\n\t\tnodeId: one?.id ?? null,\n\t\tcount: nodes.length,\n\t\teffects: (one?.effects ?? []).map((e) => ({\n\t\t\tid: e.id,\n\t\t\ttype: e.type,\n\t\t\tlabel: VECTOR_EFFECT_LABELS[e.type] ?? e.type,\n\t\t\tenabled: e.enabled !== false,\n\t\t\tparams: e.params as unknown as Record<string, unknown>,\n\t\t\t// The Envelope panel (`getVectorEnvelopePanel`) edits an envelope's warp and mesh.\n\t\t\tspecs: e.type === 'envelope' ? [] : (VECTOR_EFFECT_PARAM_SPECS[e.type] ?? [])\n\t\t})),\n\t\texpandable: nodes.some(hasVectorAppearance)\n\t};\n}\n","import type { CommandSpec } from '../commands/registry.js';\nimport type { VectorEditorController, VectorShapeInput } from './controller.js';\nimport { vectorNodeBounds, vectorNodeRotation, vectorParentMatrix, vectorPathData, IDENTITY_MATRIX } from './geometry.js';\nimport type { VectorAlign, VectorAnchorRef, VectorArrange, VectorAverageAxis, VectorBooleanOperation, VectorCornerKind, VectorNode, VectorPathfinderOperation, VectorStyle, VectorTool } from './types.js';\nimport { VECTOR_ARROWHEADS, VECTOR_CORNER_KINDS, VECTOR_EFFECT_TYPES, VECTOR_PATHFINDER_OPERATIONS, VECTOR_TOOLS, type VectorEffect, type VectorEffectType, type VectorWidthPoint } from './types.js';\nimport { VECTOR_WIDTH_PRESET_IDS, type VectorTaperOptions, type VectorWaveOptions, type VectorWidthPreset } from './width.js';\nimport { resolveVectorBlendOptions, vectorBlendKeys } from './blendGroup.js';\nimport { VECTOR_BLEND_SPACINGS, VECTOR_GRADIENT_INTERPOLATIONS, VECTOR_GRADIENT_SPREADS, VECTOR_GRADIENT_TYPES, VECTOR_STROKE_GRADIENT_MODES, type VectorBlendOptions } from './types.js';\nimport { sanitizeVectorGradient, type VectorGradientPatch } from './gradient.js';\nimport { isValidVectorMesh, VECTOR_WARP_STYLES } from './warp.js';\nimport type { VectorEnvelopeParams } from './appearance.js';\n\nexport interface VectorCommandOptions {\n\t/** Id prefix (default `vector.`); use one per editor when several are registered. */\n\tprefix?: string;\n\t/** Palette group (default `Vector`). */\n\tgroup?: string;\n\t/** Command scope. Omit for global commands. */\n\tscope?: string;\n}\n\n/** A node as listed for agents. */\nexport interface VectorNodeListing {\n\tid: string;\n\ttype: 'path' | 'group';\n\tname?: string;\n\tdepth: number;\n\t/** Axis-aligned bounds in document units. */\n\tbounds: { x: number; y: number; width: number; height: number } | null;\n\t/** Rotation in degrees, clockwise (ancestors' rotations included). */\n\trotation: number;\n\tvisible: boolean;\n\tlocked: boolean;\n\tselected: boolean;\n\tfill?: unknown;\n\tstroke?: unknown;\n\tstrokeWidth?: number;\n\t/** SVG path data (paths only). */\n\td?: string;\n\tchildren?: number;\n\t/** A blend group's options (its steps are listed as children with `blendStep`). */\n\tblend?: { spacing: string; steps: number; distance: number; orientToSpine: boolean; linear: boolean; spine: boolean; keys: string[] };\n\t/** An in-between generated by a blend (locked; changes come from its keys). */\n\tblendStep?: boolean;\n\t/** The node's live path effects, applied in order. */\n\teffects?: VectorEffect[];\n\t/** A live boolean group's operation (its children are the operands). */\n\tliveBoolean?: VectorBooleanOperation;\n\t/** An operand's own operation in a live boolean group. */\n\tbooleanOperation?: VectorBooleanOperation;\n}\n\nconst EFFECT_PARAMS_DESCRIPTION =\n\t'Effect parameters (missing ones keep their value or default). trim: start, end (percent), offset (degrees), mode simultaneous|individual. roundCorners: radius. puckerBloat: amount (−100…100). twist: angle, center {x, y} (offset from the middle). zigzag: size, ridges, smooth. wiggle: size, detail, smooth, speed, correlation, phase, seed, time (seconds). offset: amount, join miter|round|bevel, miterLimit, copies, copyOffset. merge: mode merge|add|subtract|intersect|exclude. repeater: copies (fractions fade the last), offset, position {x, y}, anchor {x, y} (offset from the middle), rotation, scale {x, y} (percent), startOpacity, endOpacity (percent), composite below|above. envelope: style (a warp preset: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist, or mesh), bend, horizontal, vertical (percent, −100…100), orientation horizontal|vertical, rows, columns, mesh { us, vs, points } (node space; prefer vector.envelope).';\n\nconst fail = (message: string): never => {\n\tthrow new Error(message);\n};\n\nconst IDS = { type: 'array', items: { type: 'string' }, description: 'Node ids (default: the selection).' } as const;\n\nconst ANCHORS = {\n\ttype: 'array',\n\titems: {\n\t\ttype: 'object',\n\t\tproperties: { nodeId: { type: 'string' }, subpath: { type: 'integer', minimum: 0 }, index: { type: 'integer', minimum: 0 } },\n\t\trequired: ['nodeId', 'subpath', 'index']\n\t},\n\tdescription: 'Anchors as { nodeId, subpath, index } (default: the selected points).'\n} as const;\n\nconst POINTS = {\n\ttype: 'array',\n\titems: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2 },\n\tminItems: 1,\n\tdescription: 'Polyline [[x, y], …] in document units.'\n} as const;\n\nconst WIDTH_POINTS = {\n\ttype: ['array', 'null'],\n\titems: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tt: { type: 'number', minimum: 0, maximum: 1, description: 'Position along each subpath by length (0 start, 1 end).' },\n\t\t\tleft: { type: 'number', minimum: 0, description: 'Left side as a multiple of half the stroke width (1 = uniform).' },\n\t\t\tright: { type: 'number', minimum: 0, description: 'Right side (looking along the path, y down).' }\n\t\t},\n\t\trequired: ['t', 'left', 'right']\n\t},\n\tdescription: 'Variable-width profile points, interpolated smoothly (monotone cubic); two points at one `t` make a step. `null` or `[]` strokes at a uniform width.'\n} as const;\n\nconst BLEND_PROPS = {\n\tspacing: { type: 'string', enum: ['steps', 'distance', 'smoothColor'], description: 'How in-betweens are spaced (default steps).' },\n\tsteps: { type: 'integer', minimum: 1, maximum: 1000, description: 'In-betweens between each pair of keys (steps spacing; default 5).' },\n\tdistance: { type: 'number', exclusiveMinimum: 0, description: 'Distance between in-betweens along the spine (distance spacing; default 20).' },\n\torientToSpine: { type: 'boolean', description: 'Turn the in-betweens with a replaced spine.' },\n\tlinear: { type: 'boolean', description: 'Move anchors in straight lines instead of the rotation-aware morph.' }\n} as const;\n\nconst checkBlendOptions = (params: Partial<VectorBlendOptions> | undefined) => {\n\tif (params?.spacing !== undefined && !VECTOR_BLEND_SPACINGS.includes(params.spacing)) fail(`Unknown blend spacing \"${params.spacing}\".`);\n\tif (params?.steps !== undefined && !(Number.isFinite(params.steps) && params.steps >= 1)) fail('steps must be at least 1.');\n\tif (params?.distance !== undefined && !(Number.isFinite(params.distance) && params.distance > 0)) fail('distance must be positive.');\n};\n\nconst POINT = { type: 'object', properties: { x: { type: 'number' }, y: { type: 'number' } }, required: ['x', 'y'] } as const;\n\n/** Gradient fields shared by paints and `setGradient`. */\nconst GRADIENT_PROPS = {\n\ttype: { type: 'string', enum: VECTOR_GRADIENT_TYPES, description: 'linear, radial, conic (an angle sweep), reflected (linear mirrored about the start) or diamond.' },\n\tstops: {\n\t\ttype: 'array',\n\t\tminItems: 1,\n\t\titems: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\toffset: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\tcolor: { type: 'string', description: 'A CSS colour.' },\n\t\t\t\topacity: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\tmidpoint: { type: 'number', minimum: 0.05, maximum: 0.95, description: 'Where between this stop and the next the colours are half-mixed (default 0.5).' }\n\t\t\t},\n\t\t\trequired: ['offset', 'color']\n\t\t}\n\t},\n\tangle: { type: 'number', description: 'Shorthand direction in degrees (0 up, clockwise): linear / reflected direction across the box, conic start angle, diamond turn.' },\n\tcx: { type: 'number', description: 'Shorthand centre x of radial / conic / diamond gradients, a fraction of the box (default 0.5).' },\n\tcy: { type: 'number' },\n\tr: { type: 'number', description: 'Shorthand radius, a fraction of the box (default 0.5).' },\n\tstart: { ...POINT, description: 'Explicit start (centre of radial / conic / diamond), in `units`. Wins over the shorthand.' },\n\tend: { ...POINT, description: 'Explicit end of the main axis (the radius of radial / conic / diamond).' },\n\twidth: { ...POINT, description: 'End of the secondary axis (aspect and turn of radial / conic / diamond); default square to the main axis, as long.' },\n\tfocal: { ...POINT, description: 'Radial focal point (where t = 0), in `units`.' },\n\tfocalRadius: { type: 'number', minimum: 0, maximum: 0.99, description: 'Radial focal circle radius as a fraction of the radius (SVG fr).' },\n\tunits: { type: 'string', enum: ['objectBoundingBox', 'userSpaceOnUse'], description: 'Space of start / end / width / focal: fractions of the shape box (default) or the node\\'s own coordinates.' },\n\tspread: { type: 'string', enum: VECTOR_GRADIENT_SPREADS, description: 'What paints past the ends: pad (default), reflect or repeat.' },\n\tinterpolation: { type: 'string', enum: VECTOR_GRADIENT_INTERPOLATIONS, description: 'Colour mixing space: srgb (default), linear (light) or oklab.' },\n\tsmoothness: { type: 'number', minimum: 0, maximum: 1, description: 'Bends the ramp along a smooth spline through the stops (0 = straight).' },\n\tstrokeMode: { type: 'string', enum: VECTOR_STROKE_GRADIENT_MODES, description: 'On strokes: within (default, like a fill), along the path or across it.' }\n} as const;\n\nconst PAINT = {\n\tdescription:\n\t\t'A CSS colour, `null` for none, or a gradient object: `{ type: \"linear\" | \"radial\" | \"conic\" | \"reflected\" | \"diamond\", stops: [{ offset, color, opacity?, midpoint? }] }` plus the shorthand `angle` / `cx, cy, r` or explicit `start`, `end`, `width`, `focal`, `focalRadius`, `units`, and `spread`, `interpolation`, `smoothness`, `strokeMode` (see vector.setGradient).',\n\tanyOf: [{ type: 'string' }, { type: 'null' }, { type: 'object', properties: GRADIENT_PROPS, required: ['type', 'stops'] }]\n} as const;\n\nconst STYLE_PROPS = {\n\tfill: PAINT,\n\tstroke: PAINT,\n\tstrokeWidth: { type: 'number', minimum: 0 },\n\tstrokeLinecap: { type: 'string', enum: ['butt', 'round', 'square'] },\n\tstrokeLinejoin: { type: 'string', enum: ['miter', 'round', 'bevel'] },\n\tstrokeDasharray: { type: 'array', items: { type: 'number' } },\n\tfillRule: { type: 'string', enum: ['nonzero', 'evenodd'] },\n\tstrokeAlign: { type: 'string', enum: ['center', 'inside', 'outside'], description: 'Where the stroke sits on the outline (closed shapes only; open paths stroke centred).' },\n\tstartArrow: { type: ['string', 'null'], enum: [...VECTOR_ARROWHEADS, null], description: 'Head at the start of an open path, or null for none.' },\n\tendArrow: { type: ['string', 'null'], enum: [...VECTOR_ARROWHEADS, null], description: 'Head at the end of an open path, or null for none.' },\n\tarrowAlign: { type: 'string', enum: ['extend', 'tip'], description: '`extend`: the tip sits past the end point; `tip`: on it, the stroke shortened under the head.' },\n\tstartArrowScale: { type: 'number', exclusiveMinimum: 0, description: 'Start head size as a multiple of the stroke width (default 1).' },\n\tendArrowScale: { type: 'number', exclusiveMinimum: 0, description: 'End head size as a multiple of the stroke width (default 1).' },\n\tstrokeWidthProfile: WIDTH_POINTS\n} as const;\n\nconst pickStyle = (params: Record<string, unknown>): VectorStyle => {\n\tconst out: Record<string, unknown> = {};\n\tfor (const key of Object.keys(STYLE_PROPS)) if (params[key] !== undefined) out[key] = params[key];\n\tfor (const key of ['fill', 'stroke'] as const) {\n\t\tconst paint = out[key];\n\t\tif (paint && typeof paint === 'object') out[key] = sanitizeVectorGradient(paint) ?? fail(`${key} is not a valid gradient: give a type and at least one stop { offset, color }.`);\n\t}\n\treturn out as VectorStyle;\n};\n\nconst check = (result: { ok: boolean; message?: string }) => {\n\tif (!result.ok) fail(result.message ?? 'The command failed.');\n};\n\n/**\n * Palette and agent commands for a vector editor: list, select, add shapes and paths, style,\n * transform, align, arrange, group, boolean operations and SVG import / export. Register them\n * in a `CommandRegistry` and agents get them through `createCommandToolProvider`. Failures\n * throw sentences, which the registry returns as `{ ok: false, code: 'failed', message }`.\n */\nexport function createVectorCommands(controller: VectorEditorController, options: VectorCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'vector.';\n\tconst group = options.group ?? 'Vector';\n\tconst base = { group, ...(options.scope ? { scope: options.scope } : {}) };\n\tconst hasSelection = () => (controller.getState().selection.length ? true : 'Nothing is selected.');\n\tconst ids = (params: { ids?: string[] } | undefined) => {\n\t\tconst list = params?.ids ?? controller.getState().selection;\n\t\tfor (const id of list) if (!controller.getNode(id)) fail(`There is no node \"${id}\".`);\n\t\tif (!list.length) fail('Nothing is selected; pass ids.');\n\t\treturn list;\n\t};\n\tconst enabledFor = (_: unknown, params: { ids?: string[] } | undefined) => (params?.ids?.length ? true : hasSelection());\n\tconst anchorsOf = (refs: VectorAnchorRef[] | undefined): VectorAnchorRef[] => {\n\t\tif (!refs) return [...controller.getState().selectedAnchors];\n\t\tfor (const r of refs) {\n\t\t\tconst node = controller.getNode(r.nodeId);\n\t\t\tif (node?.type !== 'path' || !node.subpaths[r.subpath]?.anchors[r.index]) fail(`There is no anchor ${r.index} on subpath ${r.subpath} of \"${r.nodeId}\".`);\n\t\t}\n\t\treturn refs;\n\t};\n\n\tconst list = (): { width: number; height: number; nodes: VectorNodeListing[]; selection: readonly string[]; tool: VectorTool } => {\n\t\tconst state = controller.getState();\n\t\tconst out: VectorNodeListing[] = [];\n\t\tconst visit = (nodes: readonly VectorNode[], depth: number) => {\n\t\t\tfor (const n of nodes) {\n\t\t\t\tconst parent = vectorParentMatrix(state.document.nodes, n.id) ?? IDENTITY_MATRIX;\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tout.push({\n\t\t\t\t\tid: n.id,\n\t\t\t\t\ttype: n.type,\n\t\t\t\t\t...(n.name ? { name: n.name } : {}),\n\t\t\t\t\tdepth,\n\t\t\t\t\trotation: Math.round(vectorNodeRotation(n, parent) * 100) / 100,\n\t\t\t\t\tbounds: b && { x: Math.round(b.x * 100) / 100, y: Math.round(b.y * 100) / 100, width: Math.round(b.width * 100) / 100, height: Math.round(b.height * 100) / 100 },\n\t\t\t\t\tvisible: n.visible !== false,\n\t\t\t\t\tlocked: !!n.locked,\n\t\t\t\t\tselected: state.selection.includes(n.id),\n\t\t\t\t\t...(n.type === 'path'\n\t\t\t\t\t\t? { fill: n.fill ?? null, stroke: n.stroke ?? null, strokeWidth: n.strokeWidth ?? 1, d: vectorPathData(n, 2) }\n\t\t\t\t\t\t: { children: n.children.length }),\n\t\t\t\t\t...(n.type === 'group' && n.blend\n\t\t\t\t\t\t? { blend: { ...resolveVectorBlendOptions(n.blend), spine: !!n.blend.spine, keys: vectorBlendKeys(n).map((k) => k.id) } }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(n.blendStep ? { blendStep: true } : {}),\n\t\t\t\t\t...(n.effects?.length ? { effects: n.effects } : {}),\n\t\t\t\t\t...(n.type === 'group' && n.liveBoolean ? { liveBoolean: n.liveBoolean } : {}),\n\t\t\t\t\t...(n.booleanOperation ? { booleanOperation: n.booleanOperation } : {})\n\t\t\t\t});\n\t\t\t\tif (n.type === 'group') visit(n.children, depth + 1);\n\t\t\t}\n\t\t};\n\t\tvisit(state.document.nodes, 0);\n\t\treturn { width: state.document.width, height: state.document.height, nodes: out, selection: state.selection, tool: state.tool };\n\t};\n\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}list`,\n\t\t\tlabel: 'List Vector Nodes',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['layers', 'shapes', 'document', 'outline'],\n\t\t\tdescription: 'Lists every node (paths and groups, depth first) with bounds, style, path data and selection.',\n\t\t\trun: list\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}select`,\n\t\t\tlabel: 'Select Nodes',\n\t\t\tkeywords: ['pick', 'choose'],\n\t\t\tdescription: 'Selects nodes by id (empty list clears the selection).',\n\t\t\tparams: { type: 'object', properties: { ids: { type: 'array', items: { type: 'string' } }, add: { type: 'boolean' } }, required: ['ids'] },\n\t\t\trun: (_ctx: unknown, params: { ids: string[]; add?: boolean }) => {\n\t\t\t\tfor (const id of params.ids) if (!controller.getNode(id)) fail(`There is no node \"${id}\".`);\n\t\t\t\tif (!params.ids.length && !params.add) controller.clearSelection();\n\t\t\t\telse controller.select(params.ids, { add: params.add });\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addShape`,\n\t\t\tlabel: 'Add Shape…',\n\t\t\tkeywords: ['rectangle', 'ellipse', 'circle', 'polygon', 'star', 'line', 'draw'],\n\t\t\tdescription: 'Adds a rectangle, ellipse, polygon, star or line in document units, using the current default style unless overridden.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tkind: { type: 'string', enum: ['rect', 'ellipse', 'polygon', 'star', 'line'] },\n\t\t\t\t\tx: { type: 'number' },\n\t\t\t\t\ty: { type: 'number' },\n\t\t\t\t\twidth: { type: 'number', description: 'For a line: the x offset of its end.' },\n\t\t\t\t\theight: { type: 'number', description: 'For a line: the y offset of its end.' },\n\t\t\t\t\tcornerRadius: { type: 'number', minimum: 0, description: 'Live corner radius of a rect, polygon or star.' },\n\t\t\t\t\tcornerKind: { type: 'string', enum: VECTOR_CORNER_KINDS },\n\t\t\t\t\tsides: { type: 'integer', minimum: 3 },\n\t\t\t\t\tpoints: { type: 'integer', minimum: 3 },\n\t\t\t\t\tinnerRatio: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\tname: { type: 'string' },\n\t\t\t\t\t...STYLE_PROPS\n\t\t\t\t},\n\t\t\t\trequired: ['kind', 'x', 'y', 'width', 'height']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: VectorShapeInput) => ({ id: controller.addShape(params) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addPath`,\n\t\t\tlabel: 'Add Path…',\n\t\t\tkeywords: ['svg', 'path data', 'bezier', 'curve'],\n\t\t\tdescription: 'Adds a path from SVG path data (`d`), in document units.',\n\t\t\tparams: { type: 'object', properties: { d: { type: 'string' }, name: { type: 'string' }, ...STYLE_PROPS }, required: ['d'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { d: string; name?: string } & Record<string, unknown>) => {\n\t\t\t\tconst id = controller.addPath(params.d, { ...pickStyle(params), ...(params.name ? { name: params.name } : {}) });\n\t\t\t\tconst node = controller.getNode(id);\n\t\t\t\tif (node?.type === 'path' && !node.subpaths.length) {\n\t\t\t\t\tcontroller.undo();\n\t\t\t\t\tfail('The path data has no points.');\n\t\t\t\t}\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setStyle`,\n\t\t\tlabel: 'Set Style…',\n\t\t\tkeywords: ['fill', 'stroke', 'colour', 'color', 'gradient', 'width'],\n\t\t\tdescription: 'Sets fill, stroke and stroke settings of nodes (groups apply to every path inside).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, ...STYLE_PROPS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } & Record<string, unknown>) => {\n\t\t\t\tconst style = pickStyle(params);\n\t\t\t\tif (!Object.keys(style).length) fail('Pass at least one style property.');\n\t\t\t\tcheck(controller.setStyle(style, ids(params)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setGradient`,\n\t\t\tlabel: 'Gradient…',\n\t\t\tkeywords: ['gradient', 'linear', 'radial', 'conic', 'angle', 'reflected', 'diamond', 'stops', 'midpoint', 'oklab', 'spread', 'focal', 'along stroke', 'across stroke', 'reverse'],\n\t\t\tdescription:\n\t\t\t\t'Edits the gradient of the fill (default) or stroke of paths (groups apply to every path inside): any gradient field (missing ones keep their value; a colour becomes a gradient from it to white), `aspect` (secondary axis over main axis), `reverse` (flip the stops and midpoints), `focal` / `width` null to remove them. Midpoints, smoothness and oklab / linear interpolation export to SVG as extra stops; conic and diamond gradients as patterns.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, target: { type: 'string', enum: ['fill', 'stroke'] }, ...GRADIENT_PROPS, aspect: { type: 'number' }, reverse: { type: 'boolean' } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: ({ ids?: string[]; target?: 'fill' | 'stroke' } & VectorGradientPatch) | undefined) => {\n\t\t\t\tconst { ids: _i, target, ...patch } = params ?? {};\n\t\t\t\tif (patch.type !== undefined && !VECTOR_GRADIENT_TYPES.includes(patch.type)) fail(`Unknown gradient type \"${patch.type}\".`);\n\t\t\t\tif (patch.stops !== undefined && !(Array.isArray(patch.stops) && patch.stops.length)) fail('stops needs at least one { offset, color }.');\n\t\t\t\tcheck(controller.setGradient(patch, { ids: ids(params), target: target ?? 'fill' }));\n\t\t\t\tconst id = ids(params)[0];\n\t\t\t\tconst node = id ? controller.getNode(id) : undefined;\n\t\t\t\tconst path = node?.type === 'path' ? node : undefined;\n\t\t\t\treturn { ok: true, ...(path ? { gradient: path[target ?? 'fill'] } : {}) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setCorners`,\n\t\t\tlabel: 'Corner Radius…',\n\t\t\tkeywords: ['round', 'rounded', 'corners', 'radius', 'fillet', 'chamfer', 'live corners'],\n\t\t\tdescription:\n\t\t\t\t'Sets the live corner radius (and optionally `kind`: round, inverted or chamfer) of `anchors`, else the selected points (direct tool), else every corner of `ids` / the selection. Radius 0 makes corners sharp; radii shrink to fit short sides. The anchors stay editable.',\n\t\t\tparams: { type: 'object', properties: { radius: { type: 'number', minimum: 0 }, kind: { type: 'string', enum: VECTOR_CORNER_KINDS }, ids: IDS, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { radius?: number; kind?: VectorCornerKind; ids?: string[]; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tconst refs = params?.anchors ? anchorsOf(params.anchors) : undefined;\n\t\t\t\tconst target = { refs, ids: params?.ids ? ids(params) : undefined };\n\t\t\t\tif (params?.radius !== undefined) check(controller.setCornerRadius(params.radius, { ...target, kind: params.kind }));\n\t\t\t\telse if (params?.kind) check(controller.setCornerKind(params.kind, target));\n\t\t\t\telse fail('Pass `radius` and / or `kind`.');\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setWidthProfile`,\n\t\t\tlabel: 'Width Profile…',\n\t\t\tkeywords: ['variable width', 'taper', 'tapered', 'pressure', 'profile', 'brush', 'calligraphy', 'bulge', 'thick', 'thin'],\n\t\t\tdescription:\n\t\t\t\t'Gives the stroke of paths a variable width: a `preset` (`uniform` removes the profile), explicit `points` ({ t, left, right }: side scales along each subpath), or a parametric `taper` (startLength / endLength as fractions of the path, startWidth / endWidth 0–1, startEase / endEase 0–1) and / or `wave` (amount 0–1, cycles, phase in degrees). Profiled strokes draw as filled outlines; Outline Stroke bakes them.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tpreset: { type: 'string', enum: VECTOR_WIDTH_PRESET_IDS },\n\t\t\t\t\tpoints: WIDTH_POINTS,\n\t\t\t\t\ttaper: {\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tstartLength: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendLength: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tstartWidth: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendWidth: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tstartEase: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendEase: { type: 'number', minimum: 0, maximum: 1 }\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\twave: { type: 'object', properties: { amount: { type: 'number', minimum: 0, maximum: 1 }, cycles: { type: 'number', exclusiveMinimum: 0 }, phase: { type: 'number' } } }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (\n\t\t\t\t_ctx: unknown,\n\t\t\t\tparams: { ids?: string[]; preset?: VectorWidthPreset; points?: VectorWidthPoint[] | null; taper?: VectorTaperOptions; wave?: VectorWaveOptions } | undefined\n\t\t\t) => {\n\t\t\t\tconst target = { ids: ids(params) };\n\t\t\t\tif (params?.preset) check(controller.setWidthProfile(params.preset, target));\n\t\t\t\telse if (params?.points !== undefined) check(controller.setWidthProfile(params.points ?? null, target));\n\t\t\t\telse if (params?.taper || params?.wave) check(controller.setWidthProfile({ taper: params.taper, wave: params.wave }, target));\n\t\t\t\telse fail('Pass `preset`, `points`, `taper` or `wave`.');\n\t\t\t\tconst node = controller.getNode(target.ids[0]);\n\t\t\t\treturn { ok: true, points: node?.type === 'path' ? (node.strokeWidthProfile ?? []) : [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setWidthPoint`,\n\t\t\tlabel: 'Width Point…',\n\t\t\tkeywords: ['width point', 'variable width', 'stroke width at', 'taper', 'profile'],\n\t\t\tdescription:\n\t\t\t\t'Sets one width point of a path\\'s stroke profile numerically: `index` names an existing point (see `vector.setWidthProfile`\\'s result), leave it out to add one at `t`. `left` / `right` are side widths in document units (how far the stroke reaches on each side), `t` the position along each subpath (0–1); a point moved onto another\\'s `t` makes a step. Returns the profile.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tid: { type: 'string', description: 'The path.' },\n\t\t\t\t\tindex: { type: 'integer', minimum: 0 },\n\t\t\t\t\tt: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\tleft: { type: 'number', minimum: 0 },\n\t\t\t\t\tright: { type: 'number', minimum: 0 }\n\t\t\t\t},\n\t\t\t\trequired: ['id']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { id: string; index?: number; t?: number; left?: number; right?: number } | undefined) => {\n\t\t\t\tif (!params?.id) fail('Pass the path `id`.');\n\t\t\t\tcheck(controller.setWidthPoint({ nodeId: params!.id, index: params!.index ?? null }, { t: params!.t, left: params!.left, right: params!.right }));\n\t\t\t\tconst node = controller.getNode(params!.id);\n\t\t\t\treturn { ok: true, points: node?.type === 'path' ? (node.strokeWidthProfile ?? []) : [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}outlineStroke`,\n\t\t\tlabel: 'Outline Stroke',\n\t\t\tkeywords: ['expand', 'stroke to path', 'outline', 'convert stroke'],\n\t\t\tdescription: 'Turns the stroke of paths into filled shapes of the area it paints (alignment, caps, joins, dashes and arrowheads included). Returns the new ids.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst created = controller.outlineStroke({ ids: params?.ids ? ids(params) : undefined });\n\t\t\t\tif (!created.length) fail('No selected path has a stroke.');\n\t\t\t\treturn { ids: created };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}distort`,\n\t\t\tlabel: 'Free Distort…',\n\t\t\tkeywords: ['distort', 'perspective', 'free distort', 'corners', 'projective', 'keystone'],\n\t\t\tdescription:\n\t\t\t\t'Free Distort: moves the four corners of the selection box (clockwise from the top left, in the box’s own rotation) to `corners` in document units, distorting the nodes in perspective (straight lines stay straight; curves are followed within `tolerance`). The corners must make a convex quadrilateral. One undo step.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tcorners: { type: 'array', items: POINT, minItems: 4, maxItems: 4, description: 'New top-left, top-right, bottom-right and bottom-left corners.' },\n\t\t\t\t\ttolerance: { type: 'number', exclusiveMinimum: 0, description: 'How closely curves follow the distortion (document units, default 0.05).' }\n\t\t\t\t},\n\t\t\t\trequired: ['corners']\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; corners: { x: number; y: number }[]; tolerance?: number }) => {\n\t\t\t\tcheck(controller.distort(params.corners, { ids: ids(params), tolerance: params.tolerance }));\n\t\t\t\tconst frame = controller.getState().selectionFrame;\n\t\t\t\treturn { ok: true, bounds: frame ? { x: frame.x, y: frame.y, width: frame.width, height: frame.height } : null };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}skew`,\n\t\t\tlabel: 'Skew…',\n\t\t\tkeywords: ['skew', 'shear', 'slant', 'oblique'],\n\t\t\tdescription:\n\t\t\t\t'Skews nodes along the selection box’s axes: `ax` degrees horizontally (vertical lines lean right for positive angles) and `ay` degrees vertically, about the box centre or `origin`. One undo step.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tax: { type: 'number', minimum: -89.9, maximum: 89.9 },\n\t\t\t\t\tay: { type: 'number', minimum: -89.9, maximum: 89.9 },\n\t\t\t\t\torigin: POINT\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; ax?: number; ay?: number; origin?: { x: number; y: number } }) => {\n\t\t\t\tcheck(controller.skew(params.ax ?? 0, params.ay ?? 0, { ids: ids(params), origin: params.origin }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}envelope`,\n\t\t\tlabel: 'Envelope Distort…',\n\t\t\tkeywords: ['envelope', 'warp', 'mesh', 'arc', 'arch', 'bulge', 'flag', 'wave', 'fish', 'rise', 'fisheye', 'inflate', 'squeeze', 'twist', 'shell', 'bend', 'distort'],\n\t\t\tdescription:\n\t\t\t\t'Envelope distortion that stays editable (a live `envelope` effect). Give `preset` (with `bend`, `horizontal`, `vertical` in percent, −100…100, and `orientation`) to warp, or `mesh` ({ rows, columns } and optionally `points`, the control grid row by row in the node’s own space) for an editable mesh; a node that already has an envelope is changed. `topObject: true` uses the topmost selected closed path as the envelope of the others; `release: true` removes the envelope and gives back its shape as a path; `expand: true` bakes it (Expand Appearance). One undo step.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tpreset: { type: 'string', enum: VECTOR_WARP_STYLES },\n\t\t\t\t\tbend: { type: 'number', minimum: -100, maximum: 100 },\n\t\t\t\t\thorizontal: { type: 'number', minimum: -100, maximum: 100 },\n\t\t\t\t\tvertical: { type: 'number', minimum: -100, maximum: 100 },\n\t\t\t\t\torientation: { type: 'string', enum: ['horizontal', 'vertical'] },\n\t\t\t\t\tmesh: {\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\trows: { type: 'integer', minimum: 1, maximum: 16 },\n\t\t\t\t\t\t\tcolumns: { type: 'integer', minimum: 1, maximum: 16 },\n\t\t\t\t\t\t\tpoints: { type: 'array', items: POINT, description: '(3·columns + 1) × (3·rows + 1) control points, row by row (node space).' }\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\ttopObject: { type: 'boolean' },\n\t\t\t\t\trelease: { type: 'boolean' },\n\t\t\t\t\texpand: { type: 'boolean' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (\n\t\t\t\t_ctx: unknown,\n\t\t\t\tparams: {\n\t\t\t\t\tids?: string[];\n\t\t\t\t\tpreset?: string;\n\t\t\t\t\tbend?: number;\n\t\t\t\t\thorizontal?: number;\n\t\t\t\t\tvertical?: number;\n\t\t\t\t\torientation?: 'horizontal' | 'vertical';\n\t\t\t\t\tmesh?: { rows?: number; columns?: number; points?: { x: number; y: number }[] };\n\t\t\t\t\ttopObject?: boolean;\n\t\t\t\t\trelease?: boolean;\n\t\t\t\t\texpand?: boolean;\n\t\t\t\t}\n\t\t\t) => {\n\t\t\t\tconst target = ids(params);\n\t\t\t\tif (params.release) return { released: target, shapes: controller.releaseEnvelope({ ids: target }) };\n\t\t\t\tif (params.expand) return { expanded: controller.expandAppearance({ ids: target }) };\n\t\t\t\tif (params.topObject) {\n\t\t\t\t\tconst r = controller.makeEnvelopeWithTopObject({ ids: target, rows: params.mesh?.rows, columns: params.mesh?.columns });\n\t\t\t\t\tcheck(r);\n\t\t\t\t\treturn { nodeId: r.nodeId };\n\t\t\t\t}\n\t\t\t\tif (params.preset !== undefined && !(VECTOR_WARP_STYLES as readonly string[]).includes(params.preset)) fail(`Unknown warp preset \"${params.preset}\".`);\n\t\t\t\tconst patch: Partial<VectorEnvelopeParams> = {};\n\t\t\t\tif (params.preset) patch.style = params.preset as VectorEnvelopeParams['style'];\n\t\t\t\tfor (const k of ['bend', 'horizontal', 'vertical'] as const) if (params[k] !== undefined) patch[k] = params[k];\n\t\t\t\tif (params.orientation) patch.orientation = params.orientation;\n\t\t\t\tif (params.mesh) {\n\t\t\t\t\tif (params.preset) fail('Give either `preset` or `mesh`, not both.');\n\t\t\t\t\tpatch.style = 'mesh';\n\t\t\t\t\tconst columns = params.mesh.columns ?? 2;\n\t\t\t\t\tconst rows = params.mesh.rows ?? 2;\n\t\t\t\t\tpatch.columns = columns;\n\t\t\t\t\tpatch.rows = rows;\n\t\t\t\t\tif (params.mesh.points) {\n\t\t\t\t\t\tconst even = (n: number) => Array.from({ length: n + 1 }, (_, i) => i / n);\n\t\t\t\t\t\tconst mesh = { us: even(columns), vs: even(rows), points: params.mesh.points.map((p) => ({ x: p.x, y: p.y })) };\n\t\t\t\t\t\tif (!isValidVectorMesh(mesh)) fail(`A ${columns} × ${rows} mesh needs ${(3 * columns + 1) * (3 * rows + 1)} finite points.`);\n\t\t\t\t\t\tpatch.mesh = mesh;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst made = controller.envelope(patch, { ids: target });\n\t\t\t\tif (!made.length) fail('Nothing to envelope.');\n\t\t\t\treturn { envelopes: made };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}transform`,\n\t\t\tlabel: 'Transform…',\n\t\t\tkeywords: ['move', 'translate', 'scale', 'resize', 'rotate', 'flip'],\n\t\t\tdescription:\n\t\t\t\t'Moves (dx, dy), scales (sx, sy, along the selection box axes) and/or rotates (`rotate`: by degrees clockwise around the combined centre; `angle`: to an absolute rotation, each node around its own centre), in that order.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tdx: { type: 'number' },\n\t\t\t\t\tdy: { type: 'number' },\n\t\t\t\t\tsx: { type: 'number' },\n\t\t\t\t\tsy: { type: 'number' },\n\t\t\t\t\trotate: { type: 'number' },\n\t\t\t\t\tangle: { type: 'number' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; dx?: number; dy?: number; sx?: number; sy?: number; rotate?: number; angle?: number }) => {\n\t\t\t\tconst target = ids(params);\n\t\t\t\tif (params.dx || params.dy) check(controller.translate(params.dx ?? 0, params.dy ?? 0, { ids: target }));\n\t\t\t\tif (params.sx !== undefined || params.sy !== undefined) check(controller.scale(params.sx ?? 1, params.sy ?? params.sx ?? 1, { ids: target }));\n\t\t\t\tif (params.rotate) check(controller.rotate(params.rotate, { ids: target }));\n\t\t\t\tif (params.angle !== undefined) check(controller.setRotation(params.angle, { ids: target }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}delete`,\n\t\t\tlabel: 'Delete',\n\t\t\tkeywords: ['remove'],\n\t\t\tdescription: 'Deletes nodes.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tcheck(controller.removeNodes(ids(params)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}boolean`,\n\t\t\tlabel: 'Boolean Operation…',\n\t\t\tkeywords: ['union', 'unite', 'subtract', 'intersect', 'exclude', 'combine', 'pathfinder'],\n\t\t\tdescription:\n\t\t\t\t'Combines two or more paths with union, subtract (upper shapes from the lowest), intersect or exclude. With `live`, the shapes stay editable operands of a live boolean group instead (a lone live group gets the operation; its operands get their own).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\toperation: { type: 'string', enum: ['union', 'subtract', 'intersect', 'exclude'] },\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tlive: { type: 'boolean', description: 'Keep the operands editable in a live boolean group (default false: one new path).' }\n\t\t\t\t},\n\t\t\t\trequired: ['operation']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { operation: VectorBooleanOperation; ids?: string[]; live?: boolean }) => {\n\t\t\t\tconst id = controller.booleanOp(params.operation, { ids: ids(params), live: params.live });\n\t\t\t\tif (!id) fail(params.live ? 'Select two or more nodes with one parent, a live boolean group or its operands.' : 'Select at least two overlapping paths (the result was empty).');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addEffect`,\n\t\t\tlabel: 'Add Path Effect…',\n\t\t\tkeywords: ['effect', 'trim', 'round corners', 'pucker', 'bloat', 'twist', 'zig zag', 'wiggle', 'offset', 'merge', 'repeater', 'appearance', 'live'],\n\t\t\tdescription: 'Adds a live path effect to the bottom of the effect stack of nodes (paths or groups). Effects apply top to bottom; effects after a repeater act on its copies. Returns the new effect ids.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\ttype: { type: 'string', enum: VECTOR_EFFECT_TYPES },\n\t\t\t\t\tparams: { type: 'object', description: EFFECT_PARAMS_DESCRIPTION },\n\t\t\t\t\tindex: { type: 'integer', minimum: 0, description: 'Position in the stack (default: last).' },\n\t\t\t\t\tids: IDS\n\t\t\t\t},\n\t\t\t\trequired: ['type']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\tenabled: enabledFor,\n\t\t\trun: (_ctx: unknown, params: { type: VectorEffectType; params?: Record<string, unknown>; index?: number; ids?: string[] }) => {\n\t\t\t\tif (!VECTOR_EFFECT_TYPES.includes(params.type)) fail(`Unknown effect type \"${params.type}\".`);\n\t\t\t\tconst targets = ids(params);\n\t\t\t\tconst created = controller.addEffect(params.type, { ids: targets, params: params.params, index: params.index });\n\t\t\t\tif (!created.length) fail('Nothing to add the effect to.');\n\t\t\t\treturn { effects: targets.map((id, i) => ({ nodeId: id, effectId: created[i] })) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}updateEffect`,\n\t\t\tlabel: 'Edit Path Effect…',\n\t\t\tkeywords: ['effect', 'parameters', 'enable', 'disable', 'reorder'],\n\t\t\tdescription: 'Changes a path effect: its parameters, whether it is enabled, and its position in the stack.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tnodeId: { type: 'string' },\n\t\t\t\t\teffectId: { type: 'string' },\n\t\t\t\t\tparams: { type: 'object', description: EFFECT_PARAMS_DESCRIPTION },\n\t\t\t\t\tenabled: { type: 'boolean' },\n\t\t\t\t\tindex: { type: 'integer', minimum: 0, description: 'Move it to this position in the stack (0 applies first).' }\n\t\t\t\t},\n\t\t\t\trequired: ['nodeId', 'effectId']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId: string; effectId: string; params?: Record<string, unknown>; enabled?: boolean; index?: number }) => {\n\t\t\t\tif (params.params !== undefined || params.enabled !== undefined) check(controller.updateEffect(params.nodeId, params.effectId, { params: params.params, enabled: params.enabled }));\n\t\t\t\tif (params.index !== undefined) check(controller.moveEffect(params.nodeId, params.effectId, params.index));\n\t\t\t\treturn { effects: controller.getNode(params.nodeId)?.effects ?? [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeEffect`,\n\t\t\tlabel: 'Remove Path Effect',\n\t\t\tkeywords: ['effect', 'delete'],\n\t\t\tdescription: 'Removes a path effect from a node.',\n\t\t\tparams: { type: 'object', properties: { nodeId: { type: 'string' }, effectId: { type: 'string' } }, required: ['nodeId', 'effectId'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId: string; effectId: string }) => {\n\t\t\t\tcheck(controller.removeEffect(params.nodeId, params.effectId));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}expandAppearance`,\n\t\t\tlabel: 'Expand Appearance',\n\t\t\tkeywords: ['effects', 'bake', 'flatten', 'live boolean', 'expand'],\n\t\t\tdescription: 'Bakes the path effects and live booleans of nodes (and everything inside them) into plain paths.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tundoable: true,\n\t\t\tenabled: enabledFor,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst expanded = controller.expandAppearance({ ids: ids(params) });\n\t\t\t\tif (!expanded.length) fail('Nothing selected has path effects or a live boolean.');\n\t\t\t\treturn { ids: expanded };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}blend`,\n\t\t\tlabel: 'Make Blend…',\n\t\t\tkeywords: ['blend', 'morph', 'tween', 'interpolate', 'in-between', 'steps', 'transition'],\n\t\t\tdescription:\n\t\t\t\t'Blends two or more paths or groups (sharing a parent; bottom to top, or in the order given with keepOrder) into a live blend group: the in-betweens morph shape (anchors matched by arc length, the start and winding that twist least, rotation-aware so turning shapes turn) and paint (OKLab colours, gradients, stroke width, opacity, width profiles), and regenerate whenever a key changes. Spacing: `steps` (count between each pair of keys), `distance` (along the spine) or `smoothColor`. `starts` maps key ids to the anchor of their first subpath the blend starts from. Returns the blend id.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\t...BLEND_PROPS,\n\t\t\t\t\tkeepOrder: { type: 'boolean', description: 'Blend in the order of `ids` instead of stacking order.' },\n\t\t\t\t\tstarts: { type: 'object', additionalProperties: { type: 'integer', minimum: 0 }, description: 'Start anchor per key id.' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: (VectorBlendOptions & { ids?: string[]; keepOrder?: boolean; starts?: Record<string, number> }) | undefined) => {\n\t\t\t\tcheckBlendOptions(params);\n\t\t\t\tconst id = controller.blend({ ...params, ids: ids(params) });\n\t\t\t\tif (!id) fail('Select two or more shapes that share a parent.');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}blendOptions`,\n\t\t\tlabel: 'Blend Options…',\n\t\t\tkeywords: ['blend', 'steps', 'spacing', 'distance', 'smooth color', 'orientation', 'align to path'],\n\t\t\tdescription: 'Changes the spacing (steps, distance or smoothColor), step count, distance, orient-to-spine and linear morph of the given (or selected) blends; their steps regenerate.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, ...BLEND_PROPS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: (VectorBlendOptions & { ids?: string[] }) | undefined) => {\n\t\t\t\tcheckBlendOptions(params);\n\t\t\t\tconst r = controller.setBlendOptions(params ?? {}, { ids: params?.ids });\n\t\t\t\tif (!r.ok) fail(r.message);\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}expandBlend`,\n\t\t\tlabel: 'Expand Blend',\n\t\t\tkeywords: ['blend', 'expand', 'flatten', 'bake'],\n\t\t\tdescription: 'Expands the given (or selected) blends into plain groups of their keys and in-betweens (editable paths with fresh ids). Returns the group ids.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst groups = controller.expandBlend({ ids: params?.ids });\n\t\t\t\tif (!groups.length) fail('Select a blend to expand.');\n\t\t\t\treturn { ids: groups };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}releaseBlend`,\n\t\t\tlabel: 'Release Blend',\n\t\t\tkeywords: ['blend', 'release', 'undo blend'],\n\t\t\tdescription: 'Releases the given (or selected) blends: the in-betweens go and the keys (plus a replaced spine, as an unpainted path) take the blend\\'s place. Returns their ids.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst released = controller.releaseBlend({ ids: params?.ids });\n\t\t\t\tif (!released.length) fail('Select a blend to release.');\n\t\t\t\treturn { ids: released };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}replaceSpine`,\n\t\t\tlabel: 'Replace Spine',\n\t\t\tkeywords: ['blend', 'spine', 'path', 'follow', 'along path'],\n\t\t\tdescription: 'With one blend and one path given (or selected): the path becomes the blend\\'s spine (it is removed) and the keys move onto it, spread evenly by arc length; the in-betweens follow it.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst r = controller.replaceBlendSpine({ ids: params?.ids });\n\t\t\t\tif (!r.ok) fail(r.message);\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}pathfinder`,\n\t\t\tlabel: 'Pathfinder…',\n\t\t\tkeywords: ['divide', 'trim', 'merge', 'crop', 'outline', 'minus back', 'split', 'faces'],\n\t\t\tdescription:\n\t\t\t\t'Pathfinder over the given paths (bottom to top): divide (every face its own shape, painted like the top-most shape over it; open unfilled paths cut), trim (hidden parts removed), merge (trim, then touching parts of one fill joined), crop (the top shape crops the others), outline (outlines cut into open strokes where they meet) or minusBack (the top shape minus everything below). Results replace the paths, grouped when there are several.',\n\t\t\tparams: { type: 'object', properties: { operation: { type: 'string', enum: [...VECTOR_PATHFINDER_OPERATIONS] }, ids: IDS }, required: ['operation'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { operation: VectorPathfinderOperation; ids?: string[] }) => {\n\t\t\t\tif (!VECTOR_PATHFINDER_OPERATIONS.includes(params.operation)) fail(`Unknown Pathfinder operation \"${params.operation}\".`);\n\t\t\t\tconst created = controller.pathfinder(params.operation, { ids: ids(params) });\n\t\t\t\tif (!created.length) fail('Nothing came out: select paths that overlap (two or more, except for divide and outline).');\n\t\t\t\treturn { ids: created, selection: [...controller.getState().selection] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}shapeBuilderFaces`,\n\t\t\tlabel: 'List Shape Builder Faces',\n\t\t\tkeywords: ['shape builder', 'regions', 'faces', 'planar'],\n\t\t\tdescription: 'Lists the faces the given paths divide the plane into: path data, area, a point inside and the ids of the paths filling each (empty when only outlines enclose it).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => ({ faces: controller.getShapeBuilderFaces({ ids: ids(params) }) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}shapeBuilder`,\n\t\t\tlabel: 'Shape Builder',\n\t\t\tkeywords: ['merge faces', 'build shape', 'combine regions', 'delete region'],\n\t\t\tdescription:\n\t\t\t\t'Shape Builder gesture over the faces of the given paths: `points` is the pointer path in document units (one point is a click; [[x, y], …]; use the points from shapeBuilderFaces). Merges the faces it touches into one shape, or with `erase: true` deletes them, the pieces of unfilled open paths and the edges of other outlines (cut where paths meet) within `tolerance`; a deleted edge opens its path there, and edges bounding a deleted face go with it. Shapes covering those faces lose that area. Returns the counts of faces, line pieces and edges.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { points: POINTS, erase: { type: 'boolean' }, tolerance: { type: 'number', minimum: 0 }, ids: IDS },\n\t\t\t\trequired: ['points']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; erase?: boolean; tolerance?: number; ids?: string[] }) => {\n\t\t\t\tconst result = controller.shapeBuilder(params.points.map(([x, y]) => ({ x, y })), { ids: ids(params), erase: params.erase, tolerance: params.tolerance });\n\t\t\t\tcheck(result);\n\t\t\t\treturn { merged: result.merged, faces: result.faces, lines: result.lines, edges: result.edges };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}fillRegion`,\n\t\t\tlabel: 'Fill Region',\n\t\t\tkeywords: ['paint bucket', 'live paint', 'fill area', 'enclosed'],\n\t\t\tdescription:\n\t\t\t\t'Paint bucket: fills the area the visible outlines enclose around `point` (crossings split, nested shapes left as holes) with a new path in the current fill, below the selection or on top. `gap` closes gaps up to that size between loose ends.',\n\t\t\tparams: { type: 'object', properties: { point: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2, description: '[x, y] in document units.' }, gap: { type: 'number', minimum: 0 } }, required: ['point'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { point: [number, number]; gap?: number }) => {\n\t\t\t\tconst id = controller.fillRegion({ x: params.point[0], y: params.point[1] }, { gap: params.gap });\n\t\t\t\tif (!id) fail('No closed region surrounds that point.');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}align`,\n\t\t\tlabel: 'Align…',\n\t\t\tkeywords: ['left', 'right', 'center', 'top', 'bottom', 'middle'],\n\t\t\tdescription: 'Aligns nodes to their combined bounds, or to the artboard (`to: \"artboard\"`, or when only one node is given).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { edge: { type: 'string', enum: ['left', 'center', 'right', 'top', 'middle', 'bottom'] }, to: { type: 'string', enum: ['selection', 'artboard'] }, ids: IDS },\n\t\t\t\trequired: ['edge']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { edge: VectorAlign; to?: 'selection' | 'artboard'; ids?: string[] }) => {\n\t\t\t\tcheck(controller.align(params.edge, { ids: ids(params), to: params.to }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}distribute`,\n\t\t\tlabel: 'Distribute…',\n\t\t\tkeywords: ['space', 'evenly', 'gaps'],\n\t\t\tdescription: 'Spaces three or more nodes with equal gaps.',\n\t\t\tparams: { type: 'object', properties: { direction: { type: 'string', enum: ['horizontal', 'vertical'] }, ids: IDS }, required: ['direction'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { direction: 'horizontal' | 'vertical'; ids?: string[] }) => {\n\t\t\t\tcheck(controller.distribute(params.direction, { ids: ids(params) }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}arrange`,\n\t\t\tlabel: 'Arrange…',\n\t\t\tkeywords: ['order', 'front', 'back', 'forward', 'backward', 'z-index', 'stack'],\n\t\t\tdescription: 'Changes stacking order within each node’s parent.',\n\t\t\tparams: { type: 'object', properties: { order: { type: 'string', enum: ['front', 'forward', 'backward', 'back'] }, ids: IDS }, required: ['order'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { order: VectorArrange; ids?: string[] }) => {\n\t\t\t\tcheck(controller.arrange(params.order, { ids: ids(params) }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}group`,\n\t\t\tlabel: 'Group',\n\t\t\tshortcut: 'Mod+G',\n\t\t\tdescription: 'Groups nodes that share a parent.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, name: { type: 'string' } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; name?: string } | undefined) => {\n\t\t\t\tconst id = controller.group({ ids: ids(params), name: params?.name });\n\t\t\t\tif (!id) fail('Only nodes that share a parent can be grouped.');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}ungroup`,\n\t\t\tlabel: 'Ungroup',\n\t\t\tshortcut: 'Mod+Shift+G',\n\t\t\tdescription: 'Replaces groups with their children.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tcheck(controller.ungroup({ ids: ids(params) }));\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}deleteAnchors`,\n\t\t\tlabel: 'Delete Points',\n\t\t\tkeywords: ['remove', 'anchor', 'point', 'node'],\n\t\t\tdescription:\n\t\t\t\t'Deletes anchors. With `keepShape` (default: the editor setting, on) the neighbouring handles are refitted so the outline keeps its shape; off, the neighbours are joined as they are.',\n\t\t\tparams: { type: 'object', properties: { anchors: ANCHORS, keepShape: { type: 'boolean' } } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { anchors?: VectorAnchorRef[]; keepShape?: boolean } | undefined) => {\n\t\t\t\tcheck(controller.deleteAnchors(anchorsOf(params?.anchors), { keepShape: params?.keepShape }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}moveAnchor`,\n\t\t\tlabel: 'Move Point…',\n\t\t\tkeywords: ['anchor', 'drag', 'curvature'],\n\t\t\tdescription: 'Moves one anchor to (x, y) in document units. `curvature: true` bends its two segments like the Curvature tool instead of carrying its handles along.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { nodeId: { type: 'string' }, subpath: { type: 'integer', minimum: 0 }, index: { type: 'integer', minimum: 0 }, x: { type: 'number' }, y: { type: 'number' }, curvature: { type: 'boolean' } },\n\t\t\t\trequired: ['nodeId', 'subpath', 'index', 'x', 'y']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: VectorAnchorRef & { x: number; y: number; curvature?: boolean }) => {\n\t\t\t\tcheck(controller.moveAnchor({ nodeId: params.nodeId, subpath: params.subpath, index: params.index }, { x: params.x, y: params.y }, { curvature: params.curvature }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}bendSegment`,\n\t\t\tlabel: 'Bend Segment…',\n\t\t\tkeywords: ['curve', 'segment', 'drag'],\n\t\t\tdescription: 'Bends segment `segment` (from anchor `segment` to the next) so the curve passes through (x, y) at parameter `t` (default 0.5).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tnodeId: { type: 'string' },\n\t\t\t\t\tsubpath: { type: 'integer', minimum: 0 },\n\t\t\t\t\tsegment: { type: 'integer', minimum: 0 },\n\t\t\t\t\tx: { type: 'number' },\n\t\t\t\t\ty: { type: 'number' },\n\t\t\t\t\tt: { type: 'number', minimum: 0, maximum: 1 }\n\t\t\t\t},\n\t\t\t\trequired: ['nodeId', 'subpath', 'segment', 'x', 'y']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId: string; subpath: number; segment: number; x: number; y: number; t?: number }) => {\n\t\t\t\tcheck(controller.bendSegment({ nodeId: params.nodeId, subpath: params.subpath, segment: params.segment }, { x: params.x, y: params.y }, params.t));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}join`,\n\t\t\tlabel: 'Join',\n\t\t\tshortcut: 'Mod+J',\n\t\t\tkeywords: ['connect', 'close', 'merge', 'endpoints'],\n\t\t\tdescription: 'Joins the open subpaths of paths nearest endpoints first (ends within `tolerance` merge); a single open path is closed.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, tolerance: { type: 'number', minimum: 0 } } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; tolerance?: number } | undefined) => {\n\t\t\t\tcheck(controller.joinPaths({ ids: params?.ids ? ids(params) : undefined, tolerance: params?.tolerance }));\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}average`,\n\t\t\tlabel: 'Average Points…',\n\t\t\tshortcut: 'Mod+Alt+J',\n\t\t\tkeywords: ['align', 'points', 'anchors', 'collapse'],\n\t\t\tdescription: 'Moves anchors onto their average position: the same y (`horizontal`), the same x (`vertical`) or the same point (`both`, default).',\n\t\t\tparams: { type: 'object', properties: { axis: { type: 'string', enum: ['horizontal', 'vertical', 'both'] }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { axis?: VectorAverageAxis; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tcheck(controller.averageAnchors(params?.axis ?? 'both', anchorsOf(params?.anchors)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeRedundantPoints`,\n\t\t\tlabel: 'Remove Redundant Points',\n\t\t\tkeywords: ['simplify', 'clean up', 'anchors', 'collinear'],\n\t\t\tdescription: 'Drops anchors that can go without moving the outline more than `tolerance` document units (default 0.5).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, tolerance: { type: 'number', minimum: 0 } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; tolerance?: number } | undefined) => {\n\t\t\t\tcheck(controller.removeRedundantPoints({ ids: params?.ids ? ids(params) : undefined, tolerance: params?.tolerance }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}smooth`,\n\t\t\tlabel: 'Smooth Path',\n\t\t\tkeywords: ['round', 'soften', 'handles', 'curves'],\n\t\t\tdescription: 'Pulls the handles of paths (or of the selected points) towards smooth tangents by `amount` (0–1, default 1).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, amount: { type: 'number', minimum: 0, maximum: 1 }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; amount?: number; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tcheck(controller.smoothPaths({ ids: params?.ids ? ids(params) : undefined, amount: params?.amount, refs: params?.anchors }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}cut`,\n\t\t\tlabel: 'Cut Path (Scissors)…',\n\t\t\tkeywords: ['scissors', 'split', 'open', 'break'],\n\t\t\tdescription: 'Scissors: cuts path `nodeId` at the outline point nearest (x, y), or cuts at `anchors`. A closed path opens; an open one splits in two.',\n\t\t\tparams: { type: 'object', properties: { nodeId: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId?: string; x?: number; y?: number; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tif (params?.nodeId !== undefined) {\n\t\t\t\t\tif (!controller.getNode(params.nodeId)) fail(`There is no node \"${params.nodeId}\".`);\n\t\t\t\t\tif (params.x === undefined || params.y === undefined) fail('Pass x and y with nodeId.');\n\t\t\t\t\tconst created = controller.cutPathAt(params.nodeId, { x: params.x!, y: params.y! });\n\t\t\t\t\tif (!created) fail('Nothing to cut there (the end of an open path, or a locked path).');\n\t\t\t\t\treturn { ids: created };\n\t\t\t\t}\n\t\t\t\tcheck(controller.cutAtAnchors(anchorsOf(params?.anchors)));\n\t\t\t\treturn { ids: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}knife`,\n\t\t\tlabel: 'Knife…',\n\t\t\tkeywords: ['slice', 'cut', 'split', 'divide'],\n\t\t\tdescription: 'Cuts closed paths along a polyline wherever it crosses them edge to edge (no gap between pieces). Cuts `ids`, else the selection, else every path the line crosses.',\n\t\t\tparams: { type: 'object', properties: { points: { ...POINTS, minItems: 2 }, ids: IDS }, required: ['points'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; ids?: string[] }) => {\n\t\t\t\tconst created = controller.knife(params.points.map(([x, y]) => ({ x, y })), { ids: params.ids ? ids(params) : undefined });\n\t\t\t\tif (!created.length) fail('The knife did not cross any closed path from edge to edge.');\n\t\t\t\treturn { ids: created };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}erase`,\n\t\t\tlabel: 'Erase…',\n\t\t\tkeywords: ['eraser', 'rub out', 'remove'],\n\t\t\tdescription:\n\t\t\t\t'Erases a round stroke of diameter `size` (default: the eraser size setting) along a polyline: filled shapes lose the area, outlines are cut under it. Erases from `ids`, else the selection, else every path it reaches.',\n\t\t\tparams: { type: 'object', properties: { points: POINTS, size: { type: 'number', exclusiveMinimum: 0 }, ids: IDS }, required: ['points'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; size?: number; ids?: string[] }) => {\n\t\t\t\tconst changed = controller.erase(params.points.map(([x, y]) => ({ x, y })), { size: params.size, ids: params.ids ? ids(params) : undefined });\n\t\t\t\tif (!changed.length) fail('The eraser did not touch any path.');\n\t\t\t\treturn { ids: changed.filter((id) => controller.getNode(id)) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setEditing`,\n\t\t\tlabel: 'Path Editing Options…',\n\t\t\tkeywords: ['settings', 'curvature', 'pencil', 'smoothing', 'lazy mouse', 'shapes', 'eraser'],\n\t\t\tdescription:\n\t\t\t\t'Sets how editing behaves: `keepShapeOnDelete`, `curvatureMoves` (anchor drags bend like the Curvature tool), `pencilSmoothing` (lazy mouse, 0–1), `recognizeShapes` (pencil scribbles become lines, rectangles, ellipses, polygons), `eraserSize` and `pencilPressure` (`pen`: record pen pressure on pencil strokes as a width profile, `all`: any pointer reporting pressure, `off`).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tkeepShapeOnDelete: { type: 'boolean' },\n\t\t\t\t\tcurvatureMoves: { type: 'boolean' },\n\t\t\t\t\tpencilSmoothing: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\trecognizeShapes: { type: 'boolean' },\n\t\t\t\t\teraserSize: { type: 'number', exclusiveMinimum: 0 },\n\t\t\t\t\tpencilPressure: { type: 'string', enum: ['pen', 'all', 'off'] }\n\t\t\t\t}\n\t\t\t},\n\t\t\trun: (_ctx: unknown, params: Record<string, unknown> | undefined) => {\n\t\t\t\tconst patch: Record<string, unknown> = {};\n\t\t\t\tfor (const key of ['keepShapeOnDelete', 'curvatureMoves', 'pencilSmoothing', 'recognizeShapes', 'eraserSize', 'pencilPressure']) if (params?.[key] !== undefined) patch[key] = params[key];\n\t\t\t\tcontroller.setEditing(patch);\n\t\t\t\treturn { editing: controller.getState().editing };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setTool`,\n\t\t\tlabel: 'Choose Tool…',\n\t\t\tkeywords: ['pen', 'pencil', 'select', 'rectangle', 'ellipse'],\n\t\t\tdescription: 'Switches the canvas tool.',\n\t\t\tparams: { type: 'object', properties: { tool: { type: 'string', enum: [...VECTOR_TOOLS] } }, required: ['tool'] },\n\t\t\trun: (_ctx: unknown, params: { tool: VectorTool }) => {\n\t\t\t\tcontroller.setTool(params.tool);\n\t\t\t\treturn { tool: params.tool };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportSvg`,\n\t\t\tlabel: 'Export SVG',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['download', 'save', 'markup'],\n\t\t\tdescription: 'Returns the document as SVG markup.',\n\t\t\tparams: { type: 'object', properties: { precision: { type: 'integer', minimum: 0, maximum: 8 } } },\n\t\t\trun: (_ctx: unknown, params: { precision?: number } | undefined) => ({ svg: controller.toSvg({ precision: params?.precision }) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}importSvg`,\n\t\t\tlabel: 'Import SVG…',\n\t\t\tkeywords: ['open', 'load', 'paste', 'markup'],\n\t\t\tdescription: 'Adds the shapes of SVG markup on top of the document (or replaces it with `replace: true`).',\n\t\t\tparams: { type: 'object', properties: { svg: { type: 'string' }, replace: { type: 'boolean' } }, required: ['svg'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { svg: string; replace?: boolean }) => {\n\t\t\t\tcheck(params.replace ? controller.loadSvg(params.svg) : controller.importSvg(params.svg));\n\t\t\t\treturn { nodes: controller.getState().document.nodes.length, selection: controller.getState().selection };\n\t\t\t}\n\t\t}\n\t];\n}\n"]}
|