Skip to content

AI-native design editor. Open-source Figma alternative.

feat(vector): add vector curve editor with enhanced pen tool

Ilya Nikitinb1997e413f37
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 21cba7547..55f49b2d9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@
- Nested container navigation — each double-click goes one level deeper
- Dashed border around entered container for visual feedback
- Layer panel click syncs canvas scope automatically
+- Added a vector curve editor and improved drawing experience with the pen tool
+- Resume pen drawing from existing open path endpoints — click an endpoint to continue the curve
+- Close open paths by dragging one endpoint to the other
### Fixes
diff --git a/openspec/specs/pen-tool/spec.md b/openspec/specs/pen-tool/spec.md
index fe2714b97..6b7497a8a 100644
--- a/openspec/specs/pen-tool/spec.md
+++ b/openspec/specs/pen-tool/spec.md
@@ -1,52 +1,145 @@
# pen-tool Specification
## Purpose
-Pen tool for vector path creation using a vector network data model. Supports bezier curves with tangent handles, open/closed paths, and Figma-compatible vectorNetworkBlob binary encoding.
+Pen tool for vector path creation and vector geometry editing using the vector network model. Supports open/closed paths, interactive tangent composition modes, and editing existing curves.
+
## Requirements
-### Requirement: Pen tool with vector network model
-Pressing P SHALL activate the pen tool. Clicking places corner points, click+drag places curve points with bezier handles. The underlying data model SHALL use vector networks (not simple paths).
+### Requirement: Pen tool activation and vector network model
+Pressing `P` SHALL activate the Pen tool. Pen-created vectors SHALL use vector-network geometry (vertices, segments, tangents, regions), not flattened SVG path strings.
+
+#### Scenario: Activate pen tool
+- **WHEN** user presses `P`
+- **THEN** active tool becomes `PEN`
+
+#### Scenario: Create line segments
+- **WHEN** user clicks multiple points without drag
+- **THEN** segments are created with zero tangents (`tangentStart/tangentEnd = {0,0}`)
+
+#### Scenario: Create curve segment
+- **WHEN** user drags while placing a new point
+- **THEN** non-zero tangents are recorded for bezier curvature
+
+### Requirement: Open and closed path commit behavior
+Path close intent SHALL be detected near the first vertex, but final close commit SHALL happen on `mouseUp`, not `mouseDown`.
+
+#### Scenario: Close commit on mouseUp
+- **WHEN** cursor is within close threshold to first vertex and user presses + releases pointer
+- **THEN** the close segment is committed on release (`mouseUp`)
+
+#### Scenario: Open path commit
+- **WHEN** user presses `Escape` during Pen drawing
+- **THEN** current path is committed as open (no fill region loop)
+
+### Requirement: Closing handle drag behavior
+When closing a path, dragging SHALL allow editing the closing handle on the closing vertex (vertex `0`) before commit.
+
+#### Scenario: Closing preview while dragging
+- **WHEN** close intent is active and user drags
+- **THEN** preview renders closing segment (`last -> first`) with current handle values
+
+#### Scenario: Closing commit with drag tangent
+- **WHEN** close intent is active and pointer is released
+- **THEN** closing segment end tangent uses the active closing drag tangent on vertex `0`
+
+### Requirement: Pen tangent composition modes while drawing
+During Pen drag, composition modifiers SHALL work consistently:
+- default: Symmetric (`ANGLE_AND_LENGTH`)
+- `Cmd/Ctrl`: Continuous (`ANGLE`) direction lock to sister handle axis, length editable
+- `Alt/Option`: Corner (`NONE`) independent active handle, sister preserved
+
+#### Scenario: Default symmetric drag
+- **WHEN** user drags without modifiers
+- **THEN** opposite handle mirrors active handle symmetrically
+
+#### Scenario: Continuous drag with Cmd/Ctrl
+- **WHEN** user drags and holds `Cmd/Ctrl`
+- **THEN** active handle is constrained to sister axis and only length changes
+- **AND** vertex handle composition is set to `ANGLE`
+
+#### Scenario: Corner drag with Alt/Option
+- **WHEN** user drags and holds `Alt/Option`
+- **THEN** active handle is edited independently
+- **AND** sister handle remains fixed as reference
+- **AND** vertex handle composition is `NONE`
+
+#### Scenario: Modifier release during same drag
+- **WHEN** user changes modifier state mid-drag
+- **THEN** behavior switches immediately to target composition mode without restarting drag
+
+### Requirement: Closing-node default composition
+At close-intent drag on vertex `0`, default composition SHALL be `Corner` to avoid mutating the sister handle unless explicitly requested by modifier behavior.
+
+#### Scenario: Closing drag default keeps sister
+- **WHEN** user drags close handle without modifiers
+- **THEN** sister handle on vertex `0` keeps its prior value
+- **AND** composition remains `NONE`
+
+#### Scenario: Closing continuous uses frozen sister reference
+- **WHEN** user presses `Cmd/Ctrl` during closing drag
+- **THEN** sister handle on vertex `0` is preserved and used as continuous reference
+- **AND** it is never zeroed by modifier transition
+
+### Requirement: Entering node edit by double click
+Double-clicking a vector while in Select mode SHALL enter geometry edit mode for that node.
+
+#### Scenario: Enter node edit on vector
+- **WHEN** user double-clicks a vector node
+- **THEN** node edit state is initialized with absolute editable vertices/segments
+
+### Requirement: Node-edit visual/interaction isolation
+While in node-edit mode, base selection transform UI (selection bbox, resize/rotate cursor hit testing) SHALL be disabled for the edited node.
-#### Scenario: Place corner points
-- **WHEN** user clicks three positions with the pen tool
-- **THEN** a path with three straight-line segments is created
+#### Scenario: No transform cursor in node-edit
+- **WHEN** node-edit mode is active
+- **THEN** hovering former selection corners does not produce resize/rotate cursors
-#### Scenario: Place curve point
-- **WHEN** user clicks and drags with the pen tool
-- **THEN** a bezier curve point is created with tangent handles matching the drag direction and length
+### Requirement: Pen tool actions in node-edit mode
+With Pen active and node-edit mode open:
+- click on contour adds a vertex (segment split)
+- click on endpoint resumes drawing from endpoint
+- `Alt/Option` click on vertex removes vertex
-### Requirement: Open and closed paths
-Clicking the first point SHALL close the path. Pressing Escape SHALL commit an open path.
+#### Scenario: Add point on contour in node-edit
+- **WHEN** Pen is active in node-edit and user clicks contour
+- **THEN** nearest segment is split and a new anchor is inserted
-#### Scenario: Close path
-- **WHEN** user clicks on the first point of an in-progress path
-- **THEN** the path closes into a loop
+#### Scenario: Resume from endpoint
+- **WHEN** Pen is active in node-edit and user clicks endpoint
+- **THEN** node-edit exits and Pen resumes path creation from that endpoint
-#### Scenario: Open path
-- **WHEN** user presses Escape during pen tool drawing
-- **THEN** the current path is committed as an open path
+### Requirement: Handle drag composition in node-edit mode
+Handle drag in node-edit SHALL support composition modifiers:
+- `Alt/Option`: break mirroring (`Corner`)
+- `Cmd/Ctrl`: `Continuous` edit on same line as sister handle
+- `Shift`: lock tangent direction to pre-drag direction for `Continuous`/`Symmetric`, editing length only
-### Requirement: Vector network blob encoding
-Vector network data SHALL be encoded/decoded using the Figma vectorNetworkBlob binary format for .fig compatibility.
+#### Scenario: Shift lock in continuous/symmetric
+- **WHEN** handle drag is active on vertex with `ANGLE` or `ANGLE_AND_LENGTH` and `Shift` is held
+- **THEN** tangent direction remains equal to pre-drag axis
+- **AND** only tangent length changes
-#### Scenario: Encode vector data
-- **WHEN** a vector node is created with the pen tool
-- **THEN** the vector data can be encoded to the binary vectorNetworkBlob format
+### Requirement: Bend-handle direction targeting for vector web
+For `Cmd/Ctrl` + vertex drag bend mode, target handle SHALL be selected by incoming drag direction against segment-attachment direction at the vertex (tangent direction or neighbor fallback), not by nearest neighbor point distance.
-#### Scenario: Decode imported vector data
-- **WHEN** a .fig file containing vector nodes is imported
-- **THEN** the vectorNetworkBlob is decoded into editable vector network data
+#### Scenario: Multi-branch vertex target selection
+- **WHEN** vertex has 3+ connected segments and user starts bend drag
+- **THEN** target segment+tangent field is resolved by best directional alignment
+- **AND** resolution is locked for that drag session
-### Requirement: Open path rendering
-Open paths SHALL be rendered as open strokes, not closed and filled.
+### Requirement: Pen render styling consistency
+Committed vector style SHALL match drawing style conventions and preserve resumed style when editing/continuing existing vector paths.
-#### Scenario: Open path stroke
-- **WHEN** an open vector path has a stroke applied
-- **THEN** the path is rendered as an open stroke line, not as a closed filled shape
+#### Scenario: New open path style
+- **WHEN** user commits a newly drawn open path
+- **THEN** node gets stroke style consistent with live Pen rendering
-### Requirement: Preview line
-During pen tool drawing, a preview line SHALL connect the last placed point to the current cursor position. The preview SHALL NOT start from (0,0).
+#### Scenario: Resume existing path preserves style
+- **WHEN** user resumes Pen from an existing vector endpoint and commits
+- **THEN** fills/strokes from resumed node are preserved
-#### Scenario: Preview line from last point
-- **WHEN** user has placed one point and moves the cursor
-- **THEN** a preview line extends from the last placed point to the cursor position
+### Requirement: vectorNetwork binary compatibility
+Vector network data SHALL remain compatible with Figma-like `vectorNetworkBlob` encoding/decoding pipeline.
+#### Scenario: Encode/decode compatibility
+- **WHEN** vector is created/edited via Pen and saved/imported
+- **THEN** geometry round-trips through vector network binary codec without losing structure
diff --git a/openspec/specs/vector-edit/spec.md b/openspec/specs/vector-edit/spec.md
new file mode 100644
index 000000000..1a173c6c8
--- /dev/null
+++ b/openspec/specs/vector-edit/spec.md
@@ -0,0 +1,135 @@
+# vector-edit Specification
+
+## Purpose
+Geometry edit mode for VECTOR nodes: direct editing of anchors, segments, and tangents without invoking base transform interactions.
+
+## Requirements
+### Requirement: Enter curve edit mode
+Double-clicking a VECTOR node in Select mode SHALL enter geometry edit mode for that node.
+
+#### Scenario: Enter by double-click
+- **WHEN** user double-clicks a vector curve
+- **THEN** editor opens geometry edit mode for that vector
+- **AND** editable vertices/segments are initialized
+
+### Requirement: Edit mode scope
+Only one vector SHALL be actively edited at a time.
+
+#### Scenario: Enter another vector
+- **WHEN** user double-clicks a different vector while one vector is in edit mode
+- **THEN** previous edit session ends
+- **AND** new vector becomes the active edited vector
+
+### Requirement: Exit curve edit mode
+User SHALL be able to exit curve edit mode and return to normal selection interactions.
+
+#### Scenario: Exit with Escape
+- **WHEN** curve edit mode is active and user presses `Escape`
+- **THEN** curve edit mode ends
+
+#### Scenario: Exit by tool/context switch
+- **WHEN** curve edit mode is active and user switches to incompatible context (for example selects non-geometry transform workflow)
+- **THEN** curve edit mode ends cleanly
+
+### Requirement: Transform interaction isolation in edit mode
+While curve edit mode is active, base selection transform bbox interactions SHALL be disabled for the edited vector.
+
+#### Scenario: Hidden/non-interactive bbox corners
+- **WHEN** user hovers where resize/rotate corners would normally be
+- **THEN** transform cursors are not shown
+- **AND** resize/rotate handles are not hit-testable
+
+### Requirement: Vertex selection and direct drag
+Anchors in curve edit mode SHALL support direct manipulation by drag.
+
+#### Scenario: Drag an anchor
+- **WHEN** user drags an anchor point in curve edit mode
+- **THEN** anchor position updates by pointer delta
+- **AND** connected segments update in preview and final geometry
+
+### Requirement: Handle drag without modifiers
+Dragging a tangent handle without modifiers SHALL use the node's current composition rules.
+
+#### Scenario: Default handle drag
+- **WHEN** user drags a tangent with no modifier keys
+- **THEN** tangent updates according to current handle composition of the vertex
+
+### Requirement: Continuous override in curve edit mode
+Holding `Cmd/Ctrl` while dragging a tangent SHALL force Continuous behavior for the drag.
+
+#### Scenario: Cmd/Ctrl tangent drag
+- **WHEN** user drags a tangent while holding `Cmd/Ctrl`
+- **THEN** active tangent direction is constrained to the sister-handle axis
+- **AND** active tangent length changes with drag
+
+### Requirement: Corner override in curve edit mode
+Holding `Alt/Option` while dragging a tangent SHALL force independent handle editing.
+
+#### Scenario: Alt/Option tangent drag
+- **WHEN** user drags a tangent while holding `Alt/Option`
+- **THEN** active tangent changes independently
+- **AND** sister tangent remains unchanged
+
+### Requirement: Shift axis lock for Continuous/Symmetric
+Holding `Shift` during tangent drag on `Continuous` (`ANGLE`) or `Symmetric` (`ANGLE_AND_LENGTH`) vertices SHALL lock direction to pre-drag axis and allow length-only edits.
+
+#### Scenario: Shift lock with Continuous
+- **WHEN** user starts dragging a tangent on `ANGLE` vertex and then holds `Shift`
+- **THEN** tangent direction stays equal to pre-drag direction
+- **AND** only tangent length changes
+
+#### Scenario: Shift lock with Symmetric
+- **WHEN** user starts dragging a tangent on `ANGLE_AND_LENGTH` vertex and then holds `Shift`
+- **THEN** both tangents stay collinear on pre-drag axis
+- **AND** only lengths update per composition rules
+
+### Requirement: Modifier transitions during one drag
+Modifier changes (`Cmd/Ctrl`, `Alt/Option`, `Shift`) during an active drag SHALL be applied live without canceling drag.
+
+#### Scenario: Toggle modifiers mid-drag
+- **WHEN** user changes modifier keys while still dragging a tangent
+- **THEN** active composition behavior switches immediately
+- **AND** drag session continues from current pointer state
+
+### Requirement: Bend mode handle targeting on anchor drag
+For bend override (`Cmd/Ctrl` + anchor drag), edited tangent SHALL be determined by segment attachment direction at the anchor, not by nearest neighbor-point distance.
+
+#### Scenario: Direction-based target on 2-segment vertex
+- **WHEN** vertex has two attached segments and user starts bend drag with `Cmd/Ctrl`
+- **THEN** edited tangent is chosen by best directional alignment to drag direction
+
+#### Scenario: Direction-based target on multi-branch vertex
+- **WHEN** vertex has 3+ attached segments and user starts bend drag with `Cmd/Ctrl`
+- **THEN** edited tangent/segment is resolved by segment attachment direction
+- **AND** selected target supports vector-web branching topology
+
+### Requirement: Bend mode target lock
+Resolved bend target SHALL lock after initial determination for the current drag session.
+
+#### Scenario: Lock target after initial resolution
+- **WHEN** bend drag begins and target tangent is resolved
+- **THEN** only that tangent is edited for the remainder of the drag
+- **AND** non-target tangents keep original coordinates
+
+### Requirement: Pen interactions while already in curve edit mode
+With Pen active inside curve edit mode, contour insertion, endpoint resume, and point deletion SHALL be available.
+
+#### Scenario: Insert anchor on contour
+- **WHEN** Pen is active and user clicks a segment in curve edit mode
+- **THEN** segment is split and new anchor is inserted at hit position
+
+#### Scenario: Resume drawing from endpoint
+- **WHEN** Pen is active and user clicks an open-path endpoint in curve edit mode
+- **THEN** editor resumes path drawing from that endpoint
+
+#### Scenario: Delete anchor with Alt/Option click
+- **WHEN** Pen is active and user `Alt/Option`-clicks an anchor in curve edit mode
+- **THEN** anchor is removed and neighboring segments are reconnected if topology allows
+
+### Requirement: Visual preview correctness during curve edit
+Interactive preview in curve edit mode SHALL render active tangent feedback from anchor to active tangent endpoint.
+
+#### Scenario: Active tangent preview line
+- **WHEN** user drags an active tangent
+- **THEN** preview line is rendered from anchor to active tangent endpoint
+- **AND** preview does not render a misleading line between non-active handles
diff --git a/packages/core/src/bezier-math.ts b/packages/core/src/bezier-math.ts
new file mode 100644
index 000000000..d69ed5435
--- /dev/null
+++ b/packages/core/src/bezier-math.ts
@@ -0,0 +1,958 @@
+import type { VectorNetwork, VectorSegment, VectorVertex, VectorRegion } from './scene-graph'
+/* eslint-disable max-lines -- Bezier/network utilities kept together for shared geometry math */
+/**
+ * Pure-JS bezier math utilities for VectorNetwork manipulation.
+ * Replaces Paper.js dependency from the reference implementation.
+ */
+import type { Vector, Rect } from './types'
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export interface CubicPoints {
+ p0: Vector
+ cp1: Vector
+ cp2: Vector
+ p3: Vector
+}
+
+export interface NearestResult {
+ t: number
+ x: number
+ y: number
+ distance: number
+}
+
+export interface NetworkNearestResult extends NearestResult {
+ segmentIndex: number
+}
+
+// ---------------------------------------------------------------------------
+// De Casteljau evaluation
+// ---------------------------------------------------------------------------
+
+/** Evaluate a cubic bezier at parameter t (0..1). */
+export function evalCubic(
+ p0x: number,
+ p0y: number,
+ p1x: number,
+ p1y: number,
+ p2x: number,
+ p2y: number,
+ p3x: number,
+ p3y: number,
+ t: number
+): Vector {
+ const mt = 1 - t
+ const mt2 = mt * mt
+ const t2 = t * t
+ const a = mt2 * mt
+ const b = 3 * mt2 * t
+ const c = 3 * mt * t2
+ const d = t2 * t
+ return {
+ x: a * p0x + b * p1x + c * p2x + d * p3x,
+ y: a * p0y + b * p1y + c * p2y + d * p3y
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Curve splitting (De Casteljau subdivision)
+// ---------------------------------------------------------------------------
+
+/** Split a cubic bezier at parameter t, returning two sub-curves. */
+export function splitCubicAt(
+ p0: Vector,
+ cp1: Vector,
+ cp2: Vector,
+ p3: Vector,
+ t: number
+): { left: CubicPoints; right: CubicPoints } {
+ const mt = 1 - t
+
+ // Level 1
+ const m01x = mt * p0.x + t * cp1.x
+ const m01y = mt * p0.y + t * cp1.y
+ const m12x = mt * cp1.x + t * cp2.x
+ const m12y = mt * cp1.y + t * cp2.y
+ const m23x = mt * cp2.x + t * p3.x
+ const m23y = mt * cp2.y + t * p3.y
+
+ // Level 2
+ const m012x = mt * m01x + t * m12x
+ const m012y = mt * m01y + t * m12y
+ const m123x = mt * m12x + t * m23x
+ const m123y = mt * m12y + t * m23y
+
+ // Level 3 — the split point
+ const mx = mt * m012x + t * m123x
+ const my = mt * m012y + t * m123y
+
+ return {
+ left: {
+ p0: { x: p0.x, y: p0.y },
+ cp1: { x: m01x, y: m01y },
+ cp2: { x: m012x, y: m012y },
+ p3: { x: mx, y: my }
+ },
+ right: {
+ p0: { x: mx, y: my },
+ cp1: { x: m123x, y: m123y },
+ cp2: { x: m23x, y: m23y },
+ p3: { x: p3.x, y: p3.y }
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Segment ↔ absolute control points conversion
+// ---------------------------------------------------------------------------
+
+/** Convert a VectorSegment's relative tangents to absolute control points. */
+export function segmentToAbsolute(network: VectorNetwork, segmentIndex: number): CubicPoints {
+ const seg = network.segments[segmentIndex]
+ const v0 = network.vertices[seg.start]
+ const v1 = network.vertices[seg.end]
+ return {
+ p0: { x: v0.x, y: v0.y },
+ cp1: { x: v0.x + seg.tangentStart.x, y: v0.y + seg.tangentStart.y },
+ cp2: { x: v1.x + seg.tangentEnd.x, y: v1.y + seg.tangentEnd.y },
+ p3: { x: v1.x, y: v1.y }
+ }
+}
+
+/** Check if a segment is a straight line (both tangents zero). */
+export function isLineSegment(seg: VectorSegment): boolean {
+ return (
+ seg.tangentStart.x === 0 &&
+ seg.tangentStart.y === 0 &&
+ seg.tangentEnd.x === 0 &&
+ seg.tangentEnd.y === 0
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Accurate bezier bounds via cubic extrema
+// ---------------------------------------------------------------------------
+
+/**
+ * Find parameter values where the cubic derivative is zero (extrema) in one axis.
+ * Given cubic coefficients for one axis: B(t) = (1-t)^3*p0 + 3(1-t)^2*t*p1 + 3(1-t)*t^2*p2 + t^3*p3
+ * Derivative: B'(t) = 3[(1-t)^2(p1-p0) + 2(1-t)t(p2-p1) + t^2(p3-p2)]
+ * Expanding: at^2 + bt + c = 0 where:
+ * a = -p0 + 3p1 - 3p2 + p3
+ * b = 2(p0 - 2p1 + p2)
+ * c = -p0 + p1
+ */
+export function cubicExtrema(p0: number, p1: number, p2: number, p3: number): number[] {
+ const a = -p0 + 3 * p1 - 3 * p2 + p3
+ const b = 2 * (p0 - 2 * p1 + p2)
+ const c = -p0 + p1
+
+ const results: number[] = []
+ const EPS = 1e-12
+
+ if (Math.abs(a) < EPS) {
+ // Linear: bt + c = 0
+ if (Math.abs(b) > EPS) {
+ const t = -c / b
+ if (t > 0 && t < 1) results.push(t)
+ }
+ } else {
+ const disc = b * b - 4 * a * c
+ if (disc >= 0) {
+ const sq = Math.sqrt(disc)
+ const t1 = (-b + sq) / (2 * a)
+ const t2 = (-b - sq) / (2 * a)
+ if (t1 > 0 && t1 < 1) results.push(t1)
+ if (t2 > 0 && t2 < 1 && Math.abs(t2 - t1) > EPS) results.push(t2)
+ }
+ }
+
+ return results
+}
+
+/** Compute tight axis-aligned bounding box for a VectorNetwork. */
+export function computeAccurateBounds(network: VectorNetwork): Rect {
+ const { vertices, segments } = network
+ if (vertices.length === 0) return { x: 0, y: 0, width: 0, height: 0 }
+
+ let minX = Infinity,
+ minY = Infinity,
+ maxX = -Infinity,
+ maxY = -Infinity
+
+ const update = (x: number, y: number) => {
+ if (x < minX) minX = x
+ if (y < minY) minY = y
+ if (x > maxX) maxX = x
+ if (y > maxY) maxY = y
+ }
+
+ // Include all vertex positions
+ for (const v of vertices) update(v.x, v.y)
+
+ // For each segment, find curve extrema
+ for (let i = 0; i < segments.length; i++) {
+ const { p0, cp1, cp2, p3 } = segmentToAbsolute(network, i)
+
+ // X extrema
+ for (const t of cubicExtrema(p0.x, cp1.x, cp2.x, p3.x)) {
+ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)
+ update(pt.x, pt.y)
+ }
+
+ // Y extrema
+ for (const t of cubicExtrema(p0.y, cp1.y, cp2.y, p3.y)) {
+ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)
+ update(pt.x, pt.y)
+ }
+ }
+
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }
+}
+
+// ---------------------------------------------------------------------------
+// Nearest point on cubic bezier
+// ---------------------------------------------------------------------------
+
+/**
+ * Find the nearest point on a cubic bezier to a given point (px, py).
+ * Uses coarse sampling + iterative refinement.
+ */
+export function nearestPointOnCubic(
+ px: number,
+ py: number,
+ p0: Vector,
+ cp1: Vector,
+ cp2: Vector,
+ p3: Vector,
+ coarseSamples: number = 64
+): NearestResult {
+ let bestT = 0
+ let bestDist = Infinity
+
+ // Coarse sampling
+ for (let i = 0; i <= coarseSamples; i++) {
+ const t = i / coarseSamples
+ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)
+ const dx = pt.x - px
+ const dy = pt.y - py
+ const d = dx * dx + dy * dy
+ if (d < bestDist) {
+ bestDist = d
+ bestT = t
+ }
+ }
+
+ // Refinement — bisect around best sample, 5 iterations
+ let lo = Math.max(0, bestT - 1 / coarseSamples)
+ let hi = Math.min(1, bestT + 1 / coarseSamples)
+
+ for (let iter = 0; iter < 5; iter++) {
+ const step = (hi - lo) / 4
+ let localBestT = lo
+ let localBestDist = Infinity
+
+ for (let i = 0; i <= 4; i++) {
+ const t = lo + step * i
+ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)
+ const dx = pt.x - px
+ const dy = pt.y - py
+ const d = dx * dx + dy * dy
+ if (d < localBestDist) {
+ localBestDist = d
+ localBestT = t
+ }
+ }
+
+ bestT = localBestT
+ bestDist = localBestDist
+ lo = Math.max(0, bestT - step)
+ hi = Math.min(1, bestT + step)
+ }
+
+ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, bestT)
+ return { t: bestT, x: pt.x, y: pt.y, distance: Math.sqrt(bestDist) }
+}
+
+/** Find nearest point on a straight line segment. */
+function nearestPointOnLine(px: number, py: number, p0: Vector, p1: Vector): NearestResult {
+ const dx = p1.x - p0.x
+ const dy = p1.y - p0.y
+ const lenSq = dx * dx + dy * dy
+
+ let t: number
+ if (lenSq < 1e-12) {
+ t = 0
+ } else {
+ t = Math.max(0, Math.min(1, ((px - p0.x) * dx + (py - p0.y) * dy) / lenSq))
+ }
+
+ const x = p0.x + t * dx
+ const y = p0.y + t * dy
+ const ddx = x - px
+ const ddy = y - py
+ return { t, x, y, distance: Math.sqrt(ddx * ddx + ddy * ddy) }
+}
+
+/** Find nearest point across all segments in a VectorNetwork. */
+export function nearestPointOnNetwork(
+ px: number,
+ py: number,
+ network: VectorNetwork,
+ threshold: number
+): NetworkNearestResult | null {
+ let best: NetworkNearestResult | null = null
+
+ for (let i = 0; i < network.segments.length; i++) {
+ const seg = network.segments[i]
+ let result: NearestResult
+
+ if (isLineSegment(seg)) {
+ const v0 = network.vertices[seg.start]
+ const v1 = network.vertices[seg.end]
+ result = nearestPointOnLine(px, py, v0, v1)
+ } else {
+ const { p0, cp1, cp2, p3 } = segmentToAbsolute(network, i)
+ result = nearestPointOnCubic(px, py, p0, cp1, cp2, p3)
+ }
+
+ if (result.distance <= threshold && (!best || result.distance < best.distance)) {
+ best = { ...result, segmentIndex: i }
+ }
+ }
+
+ return best
+}
+
+// ---------------------------------------------------------------------------
+// Split segment within a VectorNetwork
+// ---------------------------------------------------------------------------
+
+/**
+ * Split a segment in a VectorNetwork at parameter t, inserting a new vertex.
+ * Returns a new VectorNetwork with updated vertices, segments, and regions.
+ */
+export function splitSegmentAt(
+ network: VectorNetwork,
+ segmentIndex: number,
+ t: number
+): { network: VectorNetwork; newVertexIndex: number } {
+ const seg = network.segments[segmentIndex]
+ const v0 = network.vertices[seg.start]
+ const v1 = network.vertices[seg.end]
+
+ // New vertex array (append new vertex at end)
+ const newVertexIndex = network.vertices.length
+ const newVertices = [...network.vertices]
+
+ // New segments array — replace the original with two new ones
+ const newSegments = [...network.segments]
+
+ if (isLineSegment(seg)) {
+ // Line split: simply interpolate
+ const mx = v0.x + t * (v1.x - v0.x)
+ const my = v0.y + t * (v1.y - v0.y)
+
+ newVertices.push({ x: mx, y: my, handleMirroring: 'NONE' })
+
+ const seg1: VectorSegment = {
+ start: seg.start,
+ end: newVertexIndex,
+ tangentStart: { x: 0, y: 0 },
+ tangentEnd: { x: 0, y: 0 }
+ }
+ const seg2: VectorSegment = {
+ start: newVertexIndex,
+ end: seg.end,
+ tangentStart: { x: 0, y: 0 },
+ tangentEnd: { x: 0, y: 0 }
+ }
+
+ // Replace original segment with first; insert second after
+ const newSegIdx2 = newSegments.length
+ newSegments[segmentIndex] = seg1
+ newSegments.push(seg2)
+
+ const regions = reindexRegionLoops(
+ network.regions,
+ segmentIndex,
+ [segmentIndex, newSegIdx2],
+ network.segments
+ )
+
+ return {
+ network: { vertices: newVertices, segments: newSegments, regions },
+ newVertexIndex
+ }
+ }
+
+ // Cubic split via De Casteljau
+ const { p0, cp1, cp2, p3 } = segmentToAbsolute(network, segmentIndex)
+ const { left, right } = splitCubicAt(p0, cp1, cp2, p3, t)
+
+ // New vertex at the split point
+ newVertices.push({ x: left.p3.x, y: left.p3.y, handleMirroring: 'ANGLE_AND_LENGTH' })
+
+ // Convert absolute control points back to relative tangent offsets
+ const seg1: VectorSegment = {
+ start: seg.start,
+ end: newVertexIndex,
+ tangentStart: { x: left.cp1.x - v0.x, y: left.cp1.y - v0.y },
+ tangentEnd: { x: left.cp2.x - left.p3.x, y: left.cp2.y - left.p3.y }
+ }
+ const seg2: VectorSegment = {
+ start: newVertexIndex,
+ end: seg.end,
+ tangentStart: { x: right.cp1.x - left.p3.x, y: right.cp1.y - left.p3.y },
+ tangentEnd: { x: right.cp2.x - v1.x, y: right.cp2.y - v1.y }
+ }
+
+ const newSegIdx2 = newSegments.length
+ newSegments[segmentIndex] = seg1
+ newSegments.push(seg2)
+
+ const regions = reindexRegionLoops(
+ network.regions,
+ segmentIndex,
+ [segmentIndex, newSegIdx2],
+ network.segments
+ )
+
+ return {
+ network: { vertices: newVertices, segments: newSegments, regions },
+ newVertexIndex
+ }
+}
+
+function buildMergedSegmentForRemovedVertex(
+ vertices: VectorVertex[],
+ segments: VectorSegment[],
+ connectedSegs: number[],
+ vertexIndex: number,
+ reindex: (idx: number) => number
+): VectorSegment {
+ const segA = segments[connectedSegs[0]]
+ const segB = segments[connectedSegs[1]]
+
+ const neighborA = segA.start === vertexIndex ? segA.end : segA.start
+ const neighborB = segB.start === vertexIndex ? segB.end : segB.start
+
+ const dirA =
+ segA.start === vertexIndex
+ ? { x: segA.tangentEnd.x, y: segA.tangentEnd.y }
+ : { x: segA.tangentStart.x, y: segA.tangentStart.y }
+
+ const dirB =
+ segB.start === vertexIndex
+ ? { x: segB.tangentEnd.x, y: segB.tangentEnd.y }
+ : { x: segB.tangentStart.x, y: segB.tangentStart.y }
+
+ const vA = vertices[neighborA]
+ const vR = vertices[vertexIndex]
+ const vB = vertices[neighborB]
+
+ const dA = Math.hypot(vR.x - vA.x, vR.y - vA.y)
+ const dB = Math.hypot(vB.x - vR.x, vB.y - vR.y)
+ const totalLen = dA + dB
+ const t = totalLen > 1e-6 ? dA / totalLen : 0.5
+ const mt = 1 - t
+
+ const scaleA = mt > 1e-6 ? 1 / mt : 1
+ const scaleB = t > 1e-6 ? 1 / t : 1
+ const scaledTS: Vector = { x: dirA.x * scaleA, y: dirA.y * scaleA }
+ const scaledTE: Vector = { x: dirB.x * scaleB, y: dirB.y * scaleB }
+
+ const ptScaled = evalCubic(
+ vA.x,
+ vA.y,
+ vA.x + scaledTS.x,
+ vA.y + scaledTS.y,
+ vB.x + scaledTE.x,
+ vB.y + scaledTE.y,
+ vB.x,
+ vB.y,
+ t
+ )
+ const scaledDev = Math.hypot(ptScaled.x - vR.x, ptScaled.y - vR.y)
+
+ const tangents =
+ scaledDev < totalLen * 0.05
+ ? { tangentStart: scaledTS, tangentEnd: scaledTE }
+ : solveMergedTangents(vA, vR, vB, dirA, dirB, mt, t)
+
+ return {
+ start: reindex(neighborA),
+ end: reindex(neighborB),
+ tangentStart: tangents.tangentStart,
+ tangentEnd: tangents.tangentEnd
+ }
+}
+
+function solveMergedTangents(
+ vA: Vector,
+ vR: Vector,
+ vB: Vector,
+ dirA: Vector,
+ dirB: Vector,
+ mt: number,
+ t: number
+): { tangentStart: Vector; tangentEnd: Vector } {
+ const b1 = 3 * mt * mt * t
+ const b2 = 3 * mt * t * t
+ const rhs = {
+ x: vR.x - (mt * mt * mt + b1) * vA.x - (t * t * t + b2) * vB.x,
+ y: vR.y - (mt * mt * mt + b1) * vA.y - (t * t * t + b2) * vB.y
+ }
+
+ const det = b1 * dirA.x * b2 * dirB.y - b1 * dirA.y * b2 * dirB.x
+ if (Math.abs(det) > 1e-9) {
+ const alpha = (rhs.x * b2 * dirB.y - rhs.y * b2 * dirB.x) / det
+ const beta = (b1 * dirA.x * rhs.y - b1 * dirA.y * rhs.x) / det
+ return {
+ tangentStart: { x: alpha * dirA.x, y: alpha * dirA.y },
+ tangentEnd: { x: beta * dirB.x, y: beta * dirB.y }
+ }
+ }
+
+ const toRA = { x: vR.x - vA.x, y: vR.y - vA.y }
+ const toRB = { x: vR.x - vB.x, y: vR.y - vB.y }
+ const inner = { x: b1 * toRA.x + b2 * toRB.x, y: b1 * toRA.y + b2 * toRB.y }
+ const c =
+ Math.abs(inner.x) > Math.abs(inner.y)
+ ? (inner.x !== 0 ? rhs.x / inner.x : 1)
+ : (inner.y !== 0 ? rhs.y / inner.y : 1)
+ return {
+ tangentStart: { x: c * toRA.x, y: c * toRA.y },
+ tangentEnd: { x: c * toRB.x, y: c * toRB.y }
+ }
+}
+
+function buildSegmentsAfterRemoval(
+ segments: VectorSegment[],
+ reindex: (idx: number) => number,
+ removedSet: Set<number>,
+ mergedSeg?: VectorSegment
+): { segments: VectorSegment[]; indexMap: Map<number, number | null> } {
+ const newSegments: VectorSegment[] = []
+ const segIndexMap = new Map<number, number | null>()
+ let mergedIdx = -1
+
+ for (let i = 0; i < segments.length; i++) {
+ if (!removedSet.has(i)) {
+ const s = segments[i]
+ segIndexMap.set(i, newSegments.length)
+ newSegments.push({
+ start: reindex(s.start),
+ end: reindex(s.end),
+ tangentStart: { ...s.tangentStart },
+ tangentEnd: { ...s.tangentEnd }
+ })
+ continue
+ }
+
+ if (!mergedSeg) {
+ segIndexMap.set(i, null)
+ continue
+ }
+ if (mergedIdx === -1) {
+ mergedIdx = newSegments.length
+ newSegments.push(mergedSeg)
+ }
+ segIndexMap.set(i, mergedIdx)
+ }
+
+ return { segments: newSegments, indexMap: segIndexMap }
+}
+
+// ---------------------------------------------------------------------------
+// Remove vertex from VectorNetwork
+// ---------------------------------------------------------------------------
+
+/**
+ * Remove a vertex from the network, merging adjacent segments if possible.
+ * Returns null if the vertex cannot be removed (e.g., 0 vertices remain).
+ */
+export function removeVertex(network: VectorNetwork, vertexIndex: number): VectorNetwork | null {
+ const { vertices, segments, regions } = network
+
+ // Find all segments connected to this vertex
+ const connectedSegs: number[] = []
+ for (let i = 0; i < segments.length; i++) {
+ if (segments[i].start === vertexIndex || segments[i].end === vertexIndex) {
+ connectedSegs.push(i)
+ }
+ }
+
+ if (vertices.length <= 1) return null
+
+ // Build new vertex list without the removed vertex
+ const newVertices = vertices.filter((_, i) => i !== vertexIndex)
+ const reindex = (idx: number): number => (idx > vertexIndex ? idx - 1 : idx)
+
+ if (connectedSegs.length === 2) {
+ const mergedSeg = buildMergedSegmentForRemovedVertex(
+ vertices,
+ segments,
+ connectedSegs,
+ vertexIndex,
+ reindex
+ )
+ const removedSet = new Set(connectedSegs)
+ const result = buildSegmentsAfterRemoval(segments, reindex, removedSet, mergedSeg)
+ const newRegions = remapRegions(regions, result.indexMap)
+ return { vertices: newVertices, segments: result.segments, regions: newRegions }
+ }
+
+ const removedSegSet = new Set(connectedSegs)
+ const result = buildSegmentsAfterRemoval(segments, reindex, removedSegSet)
+ const newRegions = remapRegions(regions, result.indexMap)
+ return { vertices: newVertices, segments: result.segments, regions: newRegions }
+}
+
+// ---------------------------------------------------------------------------
+// Delete vertex with all connected segments
+// ---------------------------------------------------------------------------
+
+/**
+ * Delete a vertex and ALL segments connected to it.
+ * Unlike removeVertex (which merges adjacent segments), this breaks the path.
+ * Returns null if the network would become empty.
+ */
+export function deleteVertex(network: VectorNetwork, vertexIndex: number): VectorNetwork | null {
+ const { vertices, segments } = network
+ if (vertices.length <= 1) return null
+
+ const connectedSet = new Set<number>()
+ for (let i = 0; i < segments.length; i++) {
+ if (segments[i].start === vertexIndex || segments[i].end === vertexIndex) {
+ connectedSet.add(i)
+ }
+ }
+
+ const newVertices = vertices.filter((_, i) => i !== vertexIndex)
+ const reindex = (idx: number): number => (idx > vertexIndex ? idx - 1 : idx)
+
+ const newSegments: VectorSegment[] = []
+ for (let i = 0; i < segments.length; i++) {
+ if (connectedSet.has(i)) continue
+ newSegments.push({
+ ...segments[i],
+ start: reindex(segments[i].start),
+ end: reindex(segments[i].end)
+ })
+ }
+
+ // Regions are invalidated when segments are removed
+ return { vertices: newVertices, segments: newSegments, regions: [] }
+}
+
+// Break network at vertex
+// ---------------------------------------------------------------------------
+
+/**
+ * Break the network at a vertex — duplicates the vertex so connected
+ * segments are split into two groups. For closed paths this "opens" them.
+ */
+export function breakAtVertex(network: VectorNetwork, vertexIndex: number): VectorNetwork {
+ const { vertices, segments } = network
+
+ // Find connected segments and split them into "incoming" and "outgoing"
+ const incoming: number[] = []
+ const outgoing: number[] = []
+
+ for (let i = 0; i < segments.length; i++) {
+ const s = segments[i]
+ if (s.end === vertexIndex) incoming.push(i)
+ else if (s.start === vertexIndex) outgoing.push(i)
+ }
+
+ // If vertex has connections in only one direction, nothing to break
+ if (incoming.length === 0 || outgoing.length === 0) return network
+
+ // Duplicate the vertex
+ const dupIndex = vertices.length
+ const newVertices = [...vertices, { ...vertices[vertexIndex] }]
+
+ // Redirect all outgoing segments to the duplicate
+ const newSegments = segments.map((s, i) => {
+ if (outgoing.includes(i)) {
+ return { ...s, start: dupIndex }
+ }
+ return { ...s }
+ })
+
+ // Clear tangent handles at the break point
+ for (const i of incoming) {
+ newSegments[i] = { ...newSegments[i], tangentEnd: { x: 0, y: 0 } }
+ }
+ for (const i of outgoing) {
+ newSegments[i] = { ...newSegments[i], tangentStart: { x: 0, y: 0 } }
+ }
+
+ // Remove all regions (breaking always opens the path)
+ return { vertices: newVertices, segments: newSegments, regions: [] }
+}
+
+// ---------------------------------------------------------------------------
+// Region loop helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Remap segment indices in all region loops.
+ * Map value of null means the segment was removed — the loop entry is dropped.
+ */
+function remapRegions(
+ regions: VectorRegion[],
+ indexMap: Map<number, number | null>
+): VectorRegion[] {
+ const result: VectorRegion[] = []
+
+ for (const region of regions) {
+ const newLoops: number[][] = []
+ for (const loop of region.loops) {
+ const newLoop: number[] = []
+ for (const idx of loop) {
+ const mapped = indexMap.get(idx)
+ if (mapped == null) continue
+ // Deduplicate: when two merged segments both map to the same index,
+ // only include it once (skip consecutive duplicates)
+ if (newLoop.length > 0 && newLoop[newLoop.length - 1] === mapped) continue
+ newLoop.push(mapped)
+ }
+ // Also check wrap-around: if last equals first, remove the trailing duplicate
+ if (newLoop.length > 1 && newLoop[0] === newLoop[newLoop.length - 1]) {
+ newLoop.pop()
+ }
+ if (newLoop.length >= 2) newLoops.push(newLoop)
+ }
+ if (newLoops.length > 0) {
+ result.push({ ...region, loops: newLoops })
+ }
+ }
+
+ return result
+}
+/**
+ * Replace a single segment index in all region loops with one or more new indices.
+ * Used after splitting a segment.
+ *
+ * When a segment is split into [seg1, seg2], seg1 goes original.start→mid and
+ * seg2 goes mid→original.end. If the loop traverses the original segment backward
+ * (end→start), the replacement must be [seg2, seg1] (reversed).
+ */
+function reindexRegionLoops(
+ regions: VectorRegion[],
+ oldSegIndex: number,
+ newSegIndices: number[],
+ segments?: VectorSegment[]
+): VectorRegion[] {
+ return regions.map((region) => ({
+ ...region,
+ loops: region.loops.map((loop) => {
+ const result: number[] = []
+ for (let i = 0; i < loop.length; i++) {
+ if (loop[i] !== oldSegIndex) {
+ result.push(loop[i])
+ continue
+ }
+
+ // Determine traversal direction by checking the adjacent segment
+ if (!segments || newSegIndices.length < 2) {
+ result.push(...newSegIndices)
+ continue
+ }
+
+ const origSeg = segments[oldSegIndex]
+ // Look at the NEXT segment in the loop to determine direction
+ const nextIdx = loop[(i + 1) % loop.length]
+ const nextSeg = segments[nextIdx]
+
+ // If the original segment's end connects to the next segment,
+ // the loop traverses forward → [seg1, seg2]
+ // Otherwise backward → [seg2, seg1]
+ const endConnectsToNext = origSeg.end === nextSeg.start || origSeg.end === nextSeg.end
+
+ if (endConnectsToNext) {
+ result.push(...newSegIndices)
+ } else {
+ // Backward traversal — reverse the replacement order
+ result.push(...[...newSegIndices].reverse())
+ }
+ }
+ return result
+ })
+ }))
+}
+
+// ---------------------------------------------------------------------------
+// Handle mirroring
+// ---------------------------------------------------------------------------
+
+/**
+ * Given a dragged handle vector (relative to vertex), compute the mirrored opposite handle.
+ */
+export function mirrorHandle(
+ handle: Vector,
+ mode: 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH',
+ oppositeLength?: number
+): Vector | null {
+ switch (mode) {
+ case 'NONE':
+ return null
+ case 'ANGLE_AND_LENGTH':
+ return { x: -handle.x, y: -handle.y }
+ case 'ANGLE': {
+ const len = oppositeLength ?? Math.hypot(handle.x, handle.y)
+ const hLen = Math.hypot(handle.x, handle.y)
+ if (hLen < 1e-9) return { x: 0, y: 0 }
+ const scale = len / hLen
+ return { x: -handle.x * scale, y: -handle.y * scale }
+ }
+ }
+ return null
+}
+
+/**
+ * Find the "opposite" handle for a vertex — i.e., if we're dragging a tangent on
+ * segmentIndex that touches vertexIndex, find the other segment touching the same vertex
+ * and return its index and which tangent field belongs to that vertex.
+ */
+export function findOppositeHandle(
+ network: VectorNetwork,
+ vertexIndex: number,
+ segmentIndex: number
+): { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null {
+ for (let i = 0; i < network.segments.length; i++) {
+ if (i === segmentIndex) continue
+ const s = network.segments[i]
+ if (s.start === vertexIndex) return { segmentIndex: i, tangentField: 'tangentStart' }
+ if (s.end === vertexIndex) return { segmentIndex: i, tangentField: 'tangentEnd' }
+ }
+ return null
+}
+
+/**
+ * Find all handles (tangent fields) connected to a vertex, along with neighbor info.
+ * Returns an array of { segmentIndex, tangentField, neighborVertexIndex } for each
+ * segment that touches the given vertex.
+ */
+export function findAllHandles(
+ network: VectorNetwork,
+ vertexIndex: number
+): { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd'; neighborIndex: number }[] {
+ const result: {
+ segmentIndex: number
+ tangentField: 'tangentStart' | 'tangentEnd'
+ neighborIndex: number
+ }[] = []
+ for (let i = 0; i < network.segments.length; i++) {
+ const s = network.segments[i]
+ if (s.start === vertexIndex) {
+ result.push({ segmentIndex: i, tangentField: 'tangentStart', neighborIndex: s.end })
+ }
+ if (s.end === vertexIndex) {
+ result.push({ segmentIndex: i, tangentField: 'tangentEnd', neighborIndex: s.start })
+ }
+ }
+ return result
+}
+
+// ---------------------------------------------------------------------------
+// Network connectivity
+// ---------------------------------------------------------------------------
+
+/**
+ * Find connected components in a VectorNetwork.
+ * Returns arrays of vertex indices for each component.
+ */
+export function findConnectedComponents(network: VectorNetwork): number[][] {
+ const n = network.vertices.length
+ if (n === 0) return []
+
+ const adj = new Map<number, Set<number>>()
+ for (const seg of network.segments) {
+ if (!adj.has(seg.start)) adj.set(seg.start, new Set())
+ if (!adj.has(seg.end)) adj.set(seg.end, new Set())
+ const from = adj.get(seg.start)
+ const to = adj.get(seg.end)
+ if (!from || !to) continue
+ from.add(seg.end)
+ to.add(seg.start)
+ }
+
+ const visited = new Set<number>()
+ const components: number[][] = []
+
+ for (let i = 0; i < n; i++) {
+ if (visited.has(i)) continue
+ const component: number[] = []
+ const stack = [i]
+ while (stack.length > 0) {
+ const v = stack.pop()
+ if (v === undefined) continue
+ if (visited.has(v)) continue
+ visited.add(v)
+ component.push(v)
+ const neighbors = adj.get(v)
+ if (neighbors) {
+ for (const nb of neighbors) {
+ if (!visited.has(nb)) stack.push(nb)
+ }
+ }
+ }
+ components.push(component)
+ }
+
+ return components
+}
+
+/**
+ * Extract a sub-network from a VectorNetwork given a set of vertex indices.
+ */
+export function extractSubNetwork(network: VectorNetwork, vertexIndices: number[]): VectorNetwork {
+ const indexSet = new Set(vertexIndices)
+ const oldToNew = new Map<number, number>()
+ const newVertices: VectorVertex[] = []
+
+ for (const idx of vertexIndices) {
+ oldToNew.set(idx, newVertices.length)
+ newVertices.push({ ...network.vertices[idx] })
+ }
+
+ const newSegments: VectorSegment[] = []
+ const segOldToNew = new Map<number, number>()
+
+ for (let i = 0; i < network.segments.length; i++) {
+ const s = network.segments[i]
+ if (indexSet.has(s.start) && indexSet.has(s.end)) {
+ segOldToNew.set(i, newSegments.length)
+ const start = oldToNew.get(s.start)
+ const end = oldToNew.get(s.end)
+ if (start === undefined || end === undefined) continue
+ newSegments.push({
+ start,
+ end,
+ tangentStart: { ...s.tangentStart },
+ tangentEnd: { ...s.tangentEnd }
+ })
+ }
+ }
+
+ // Remap regions
+ const newRegions: VectorRegion[] = []
+ for (const region of network.regions) {
+ const newLoops: number[][] = []
+ for (const loop of region.loops) {
+ const newLoop = loop
+ .map((i) => segOldToNew.get(i))
+ .filter((i): i is number => i !== undefined)
+ if (newLoop.length >= 2) newLoops.push(newLoop)
+ }
+ if (newLoops.length > 0) newRegions.push({ ...region, loops: newLoops })
+ }
+
+ return { vertices: newVertices, segments: newSegments, regions: newRegions }
+}
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 591126303..7953b3e85 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -27,8 +27,8 @@ export const RULER_MAJOR_TICK = 0.5
export const RULER_MINOR_TICK = 0.25
export const RULER_HIGHLIGHT_ALPHA = 0.3
-export const PEN_HANDLE_RADIUS = 3
-export const PEN_VERTEX_RADIUS = 4
+export const PEN_HANDLE_RADIUS = 2.5
+export const PEN_VERTEX_RADIUS = 3
export const PEN_CLOSE_RADIUS_BOOST = 2
export const PEN_PATH_STROKE_WIDTH = 2
export const PARENT_OUTLINE_ALPHA = 0.5
diff --git a/packages/core/src/editor/shapes.ts b/packages/core/src/editor/shapes.ts
index bbb85e121..57d1c2f9c 100644
--- a/packages/core/src/editor/shapes.ts
+++ b/packages/core/src/editor/shapes.ts
@@ -6,7 +6,15 @@ import {
} from '../constants'
import { computeVectorBounds } from '../vector'
-import type { Fill, NodeType, SceneNode, VectorNetwork, VectorRegion } from '../scene-graph'
+import type {
+ Fill,
+ NodeType,
+ SceneNode,
+ VectorNetwork,
+ VectorRegion,
+ VectorSegment
+} from '../scene-graph'
+import type { Vector } from '../types'
import type { EditorContext } from './types'
const BLACK_FILL: Fill = {
@@ -16,6 +24,14 @@ const BLACK_FILL: Fill = {
visible: true
}
+const PEN_DEFAULT_STROKE: SceneNode['strokes'][number] = {
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ weight: 2,
+ opacity: 1,
+ visible: true,
+ align: 'CENTER'
+}
+
const DEFAULT_FILLS: Record<string, Fill> = {
FRAME: DEFAULT_FRAME_FILL,
SECTION: SECTION_DEFAULT_FILL,
@@ -27,7 +43,39 @@ const DEFAULT_FILLS: Record<string, Fill> = {
TEXT: BLACK_FILL
}
+function projectTangentToAxis(active: Vector, opposite: Vector): Vector {
+ const axis = { x: -opposite.x, y: -opposite.y }
+ const axisLen = Math.hypot(axis.x, axis.y)
+ if (axisLen <= 1e-6) return active
+ const dir = { x: axis.x / axisLen, y: axis.y / axisLen }
+ const len = Math.max(0, active.x * dir.x + active.y * dir.y)
+ return { x: dir.x * len, y: dir.y * len }
+}
+
+function applyAnchorTangent(
+ tangent: Vector,
+ isClosing: boolean,
+ firstSeg: VectorSegment | undefined,
+ lastSeg: VectorSegment | undefined
+): void {
+ if (isClosing) {
+ if (!firstSeg) return
+ if (firstSeg.start === 0) firstSeg.tangentStart = { x: tangent.x, y: tangent.y }
+ else if (firstSeg.end === 0) firstSeg.tangentEnd = { x: tangent.x, y: tangent.y }
+ return
+ }
+ if (lastSeg) {
+ lastSeg.tangentEnd = { x: tangent.x, y: tangent.y }
+ }
+}
+
export function createShapeActions(ctx: EditorContext) {
+ interface PenDragOptions {
+ keepOpposite?: boolean
+ constrainToOpposite?: boolean
+ oppositeTangent?: Vector | null
+ }
+
function createShape(
type: NodeType,
x: number,
@@ -80,6 +128,8 @@ export function createShapeActions(ctx: EditorContext) {
vertices: [{ x, y }],
segments: [],
dragTangent: null,
+ oppositeDragTangent: null,
+ pendingClose: false,
closingToFirst: false
}
ctx.requestRender()
@@ -89,19 +139,6 @@ export function createShapeActions(ctx: EditorContext) {
const ps = ctx.state.penState
const prevIdx = ps.vertices.length - 1
- const first = ps.vertices[0]
- const dist = Math.hypot(x - first.x, y - first.y)
- if (ps.vertices.length > 2 && dist < 8) {
- ps.segments.push({
- start: prevIdx,
- end: 0,
- tangentStart: ps.dragTangent ?? { x: 0, y: 0 },
- tangentEnd: { x: 0, y: 0 }
- })
- penCommit(true)
- return
- }
-
ps.vertices.push({ x, y })
const newIdx = ps.vertices.length - 1
ps.segments.push({
@@ -111,17 +148,41 @@ export function createShapeActions(ctx: EditorContext) {
tangentEnd: { x: 0, y: 0 }
})
ps.dragTangent = null
+ ps.oppositeDragTangent = null
+ ps.pendingClose = false
ctx.requestRender()
}
- function penSetDragTangent(tx: number, ty: number) {
+ function penSetDragTangent(tx: number, ty: number, options?: PenDragOptions) {
if (!ctx.state.penState) return
- ctx.state.penState.dragTangent = { x: tx, y: ty }
-
const ps = ctx.state.penState
- if (ps.segments.length > 0) {
- const lastSeg = ps.segments[ps.segments.length - 1]
- lastSeg.tangentEnd = { x: -tx, y: -ty }
+ let active = { x: tx, y: ty }
+ const isClosing = !!ps.pendingClose && ps.vertices.length > 2
+ const anchorIndex = isClosing ? 0 : ps.vertices.length - 1
+ const lastSeg = ps.segments.length > 0 ? ps.segments[ps.segments.length - 1] : undefined
+ const firstSeg = ps.segments.length > 0 ? ps.segments[0] : undefined
+ const opposite = options?.oppositeTangent ?? ps.oppositeDragTangent ??
+ (lastSeg ? lastSeg.tangentEnd : { x: -tx, y: -ty })
+
+ if (options?.constrainToOpposite) {
+ active = projectTangentToAxis(active, opposite)
+ }
+
+ ps.dragTangent = active
+ const keepOpposite = options?.keepOpposite ?? isClosing
+ if (keepOpposite) {
+ ps.oppositeDragTangent = { x: opposite.x, y: opposite.y }
+ applyAnchorTangent(opposite, isClosing, firstSeg, lastSeg)
+ if (options?.constrainToOpposite) {
+ ps.vertices[anchorIndex].handleMirroring = 'ANGLE'
+ } else {
+ ps.vertices[anchorIndex].handleMirroring = 'NONE'
+ }
+ } else {
+ const symmetric = { x: -active.x, y: -active.y }
+ ps.oppositeDragTangent = symmetric
+ applyAnchorTangent(symmetric, isClosing, firstSeg, lastSeg)
+ ps.vertices[anchorIndex].handleMirroring = 'ANGLE_AND_LENGTH'
}
ctx.requestRender()
}
@@ -132,6 +193,12 @@ export function createShapeActions(ctx: EditorContext) {
ctx.requestRender()
}
+ function penSetPendingClose(closing: boolean) {
+ if (!ctx.state.penState) return
+ ctx.state.penState.pendingClose = closing
+ ctx.requestRepaint()
+ }
+
function penCommit(closed: boolean) {
const ps = ctx.state.penState
if (!ps || ps.vertices.length < 2) {
@@ -141,6 +208,16 @@ export function createShapeActions(ctx: EditorContext) {
return
}
+ if (closed && ps.pendingClose && ps.vertices.length > 2) {
+ const prevIdx = ps.vertices.length - 1
+ ps.segments.push({
+ start: prevIdx,
+ end: 0,
+ tangentStart: { x: 0, y: 0 },
+ tangentEnd: ps.dragTangent ?? { x: 0, y: 0 }
+ })
+ }
+
const regions: VectorRegion[] = closed
? [{ windingRule: 'NONZERO', loops: [ps.segments.map((_, i) => i)] }]
: []
@@ -165,22 +242,21 @@ export function createShapeActions(ctx: EditorContext) {
regions: network.regions
}
+ const penStyle = ps as typeof ps & {
+ resumedFills?: Fill[]
+ resumedStrokes?: SceneNode['strokes']
+ }
+ const fills = penStyle.resumedFills ? penStyle.resumedFills.map((f) => ({ ...f })) : []
+ const strokes = penStyle.resumedStrokes
+ ? penStyle.resumedStrokes.map((s) => ({ ...s }))
+ : [{ ...PEN_DEFAULT_STROKE }]
+
const nodeId = createShape('VECTOR', bounds.x, bounds.y, bounds.width, bounds.height)
ctx.graph.updateNode(nodeId, {
vectorNetwork: normalizedNetwork,
name: 'Vector',
- fills: closed ? [{ ...DEFAULT_SHAPE_FILL }] : [],
- strokes: closed
- ? []
- : [
- {
- color: { r: 0, g: 0, b: 0, a: 1 },
- weight: 2,
- opacity: 1,
- visible: true,
- align: 'CENTER' as const
- }
- ]
+ fills,
+ strokes
})
ctx.state.selectedIds = new Set([nodeId])
@@ -269,6 +345,7 @@ export function createShapeActions(ctx: EditorContext) {
penAddVertex,
penSetDragTangent,
penSetClosingToFirst,
+ penSetPendingClose,
penCommit,
penCancel,
adoptNodesIntoSection,
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 74ca14957..54eaa8c6c 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -74,6 +74,8 @@ export interface EditorState {
vertices: VectorVertex[]
segments: VectorSegment[]
dragTangent: Vector | null
+ oppositeDragTangent: Vector | null
+ pendingClose?: boolean
closingToFirst: boolean
} | null
penCursorX: number | null
diff --git a/packages/core/src/fig-export.ts b/packages/core/src/fig-export.ts
index 97e29b681..094e9643e 100644
--- a/packages/core/src/fig-export.ts
+++ b/packages/core/src/fig-export.ts
@@ -304,6 +304,13 @@ export function compressFigData(
return compressViaWorker(schemaDeflated, kiwiData, thumbnailPng, metaJson, imageEntries)
}
return Promise.resolve(
- compressFigDataSync(schemaDeflated, kiwiData, thumbnailPng, metaJson, imageEntries, figKiwiVersion)
+ compressFigDataSync(
+ schemaDeflated,
+ kiwiData,
+ thumbnailPng,
+ metaJson,
+ imageEntries,
+ figKiwiVersion
+ )
)
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 648cf0432..592775f8d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -173,8 +173,31 @@ export {
geometryBlobToPath,
decodeVectorNetworkBlob,
encodeVectorNetworkBlob,
+ buildStyleOverrideTable,
computeVectorBounds
} from './vector'
+export {
+ evalCubic,
+ splitCubicAt,
+ segmentToAbsolute,
+ isLineSegment,
+ cubicExtrema,
+ computeAccurateBounds,
+ nearestPointOnCubic,
+ nearestPointOnNetwork,
+ splitSegmentAt,
+ removeVertex,
+ breakAtVertex,
+ deleteVertex,
+ mirrorHandle,
+ findOppositeHandle,
+ findAllHandles,
+ findConnectedComponents,
+ extractSubNetwork,
+ type CubicPoints,
+ type NearestResult,
+ type NetworkNearestResult
+} from './bezier-math'
export { computeSelectionBounds, computeSnap, type SnapGuide } from './snap'
export { UndoManager, type UndoEntry } from './undo'
export { TextEditor, type TextCaret, type TextEditorState } from './text-editor'
diff --git a/packages/core/src/kiwi/kiwi-serialize.ts b/packages/core/src/kiwi/kiwi-serialize.ts
index 5b183e2c8..ba96ae076 100644
--- a/packages/core/src/kiwi/kiwi-serialize.ts
+++ b/packages/core/src/kiwi/kiwi-serialize.ts
@@ -3,7 +3,7 @@ export const FIG_KIWI_DEFAULT_VERSION = 101
import { deflateSync, inflateSync } from 'fflate'
import { getLoadedFontData, normalizeFontFamily, weightToStyle } from '../fonts'
-import { encodeVectorNetworkBlob } from '../vector'
+import { encodeVectorNetworkBlob, buildStyleOverrideTable } from '../vector'
import { stringToGuid, VARIABLE_BINDING_FIELDS } from './kiwi-convert'
import type { SceneGraph, SceneNode, CharacterStyleOverride } from '../scene-graph'
@@ -304,10 +304,10 @@ function resolveTextAutoResize(node: SceneNode, graph: SceneGraph): SceneNode['t
if (node.textAutoResize === 'NONE') return 'NONE'
const parent = node.parentId ? graph.getNode(node.parentId) : undefined
if (
- parent
- && parent.layoutMode !== 'NONE'
- && parent.layoutMode !== 'GRID'
- && node.layoutPositioning !== 'ABSOLUTE'
+ parent &&
+ parent.layoutMode !== 'NONE' &&
+ parent.layoutMode !== 'GRID' &&
+ node.layoutPositioning !== 'ABSOLUTE'
) {
return 'NONE'
}
@@ -367,12 +367,17 @@ function serializeLayoutProps(node: SceneNode, nc: KiwiNodeChange): void {
function serializeGeometry(node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Array[]): void {
if (node.vectorNetwork && node.type === 'VECTOR') {
+ const { table, mirroringToId } = buildStyleOverrideTable(node.vectorNetwork)
const blobIdx = blobs.length
- blobs.push(encodeVectorNetworkBlob(node.vectorNetwork))
- nc.vectorData = {
+ blobs.push(encodeVectorNetworkBlob(node.vectorNetwork, mirroringToId))
+ const vectorData: Record<string, unknown> = {
vectorNetworkBlob: blobIdx,
normalizedSize: { x: node.width, y: node.height }
}
+ if (table.length > 0) {
+ vectorData.styleOverrideTable = table
+ }
+ nc.vectorData = vectorData
}
if (node.fillGeometry.length > 0) {
nc.fillGeometry = node.fillGeometry.map((g) => {
@@ -418,10 +423,7 @@ function serializeVariableBindings(
if (entries.length > 0) nc.variableConsumptionMap = { entries }
}
-function computeExportTransform(
- node: SceneNode,
- graph: SceneGraph
-): Matrix {
+function computeExportTransform(node: SceneNode, graph: SceneGraph): Matrix {
const sx = node.flipX ? -1 : 1
const cos = Math.cos((node.rotation * Math.PI) / 180)
const sin = Math.sin((node.rotation * Math.PI) / 180)
@@ -429,15 +431,18 @@ function computeExportTransform(
// Auto-layout children should have (0,0) transform — Figma computes
// their positions from the layout engine at render time.
const parent = node.parentId ? graph.getNode(node.parentId) : undefined
- const isAutoLayoutChild = parent
- && parent.layoutMode !== 'NONE'
- && parent.layoutMode !== 'GRID'
- && node.layoutPositioning !== 'ABSOLUTE'
+ const isAutoLayoutChild =
+ parent &&
+ parent.layoutMode !== 'NONE' &&
+ parent.layoutMode !== 'GRID' &&
+ node.layoutPositioning !== 'ABSOLUTE'
return {
- m00: cos * sx, m01: -sin,
+ m00: cos * sx,
+ m01: -sin,
m02: isAutoLayoutChild ? 0 : node.x,
- m10: sin * sx, m11: cos,
+ m10: sin * sx,
+ m11: cos,
m12: isAutoLayoutChild ? 0 : node.y
}
}
@@ -477,7 +482,7 @@ export function sceneNodeToKiwi(
size: { x: node.width, y: node.height },
transform: computeExportTransform(node, graph),
strokeWeight: node.strokes.length > 0 ? node.strokes[0].weight : 1,
- strokeAlign: node.strokes.length > 0 ? node.strokes[0].align : 'INSIDE',
+ strokeAlign: node.strokes.length > 0 ? node.strokes[0].align : 'INSIDE'
}
if (node.independentStrokeWeights) {
diff --git a/packages/core/src/renderer/node-edit-overlay.ts b/packages/core/src/renderer/node-edit-overlay.ts
new file mode 100644
index 000000000..085052564
--- /dev/null
+++ b/packages/core/src/renderer/node-edit-overlay.ts
@@ -0,0 +1,459 @@
+import { computeAccurateBounds } from '../bezier-math'
+import { PEN_HANDLE_RADIUS, PEN_VERTEX_RADIUS } from '../constants'
+import { vectorNetworkToPath } from '../vector'
+
+import type { VectorVertex, VectorSegment, VectorRegion, SceneGraph } from '../scene-graph'
+import type { Vector } from '../types'
+import type { SkiaRenderer, RenderOverlays } from './renderer'
+import type { Canvas, Paint } from 'canvaskit-wasm'
+
+type ToScreenFn = (x: number, y: number) => Vector
+
+type HandleInfo =
+ | { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' }
+ | null
+ | undefined
+
+export interface NodeEditOverlayState {
+ nodeId: string
+ vertices: VectorVertex[]
+ segments: VectorSegment[]
+ regions: VectorRegion[]
+ selectedVertexIndices: Set<number>
+ selectedHandles?: Set<string>
+ hoveredHandleInfo?: HandleInfo
+}
+
+// Blue = rgb(59,130,246) ≈ 0.23, 0.51, 0.96
+// Light blue (hover) = rgb(96,165,250) ≈ 0.376, 0.647, 0.98
+const BLUE = [0.23, 0.51, 0.96] as const
+const LIGHT_BLUE = [0.376, 0.647, 0.98] as const
+
+/** Compute set of vertices whose handles should be visible: selected vertices + vertices with selected handles + their direct neighbors */
+function computeHandleVisibleVertices(
+ selectedVertexIndices: Set<number>,
+ selectedHandles: Set<string>,
+ segments: VectorSegment[]
+): Set<number> {
+ // Seed: selected vertices + vertices that own a selected handle
+ const seed = new Set(selectedVertexIndices)
+ for (const key of selectedHandles) {
+ const [siStr, tf] = key.split(':')
+ const seg = segments[Number(siStr)]
+ seed.add(tf === 'tangentStart' ? seg.start : seg.end)
+ }
+ // Expand: add only direct neighbors of seed vertices (no cascading)
+ const visible = new Set(seed)
+ for (const seg of segments) {
+ if (seed.has(seg.start)) visible.add(seg.end)
+ if (seed.has(seg.end)) visible.add(seg.start)
+ }
+ return visible
+}
+
+export function drawNodeEditOverlay(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ graph: SceneGraph,
+ editState: RenderOverlays['nodeEditState']
+): void {
+ if (!editState) return
+ const { segments, selectedVertexIndices } = editState
+ const vertices = editState.vertices
+ const regions = editState.regions
+
+ if (vertices.length === 0) return
+
+ ensureNodeEditPaints(r)
+
+ const toScreen: ToScreenFn = (x, y) => ({
+ x: x * r.zoom + r.panX,
+ y: y * r.zoom + r.panY
+ })
+
+ const selectedHandles = editState.selectedHandles ?? new Set<string>()
+ const hovered = editState.hoveredHandleInfo ?? null
+ const handleVisibleVertices = computeHandleVisibleVertices(
+ selectedVertexIndices,
+ selectedHandles,
+ segments
+ )
+
+ // Draw the node shape with its original fills/strokes/effects using live vertices
+ drawLiveShape(r, canvas, graph, editState.nodeId, vertices, segments, regions)
+
+ // Draw technical stroke outline over the shape
+ drawTechStroke(r, canvas, vertices, segments, regions)
+
+ // Draw tangent handle lines + diamonds for vertices with visible handles
+ drawEditHandles(
+ r,
+ canvas,
+ vertices,
+ segments,
+ handleVisibleVertices,
+ toScreen,
+ selectedHandles,
+ hovered
+ )
+
+ // Draw vertex circles
+ drawEditVertices(r, canvas, vertices, selectedVertexIndices, toScreen)
+}
+
+// ---------------------------------------------------------------------------
+// Live shape rendering with full styles
+// ---------------------------------------------------------------------------
+
+function drawLiveShape(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ graph: SceneGraph,
+ nodeId: string,
+ vertices: VectorVertex[],
+ segments: VectorSegment[],
+ regions: VectorRegion[]
+): void {
+ const node = graph.getNode(nodeId)
+ if (!node) return
+
+ // Compute bounds from live (absolute) vertices
+ const liveNetwork = { vertices, segments, regions }
+ const bounds = computeAccurateBounds(liveNetwork)
+
+ // Build a normalized VectorNetwork (relative to bounds origin)
+ const normalizedNetwork = {
+ vertices: vertices.map((v) => ({
+ ...v,
+ x: v.x - bounds.x,
+ y: v.y - bounds.y
+ })),
+ segments,
+ regions
+ }
+
+ // Temporarily patch the node so renderShapeUncached uses our live network
+ const origNetwork = node.vectorNetwork
+ const origX = node.x
+ const origY = node.y
+ const origW = node.width
+ const origH = node.height
+
+ node.vectorNetwork = normalizedNetwork
+ node.x = bounds.x
+ node.y = bounds.y
+ node.width = bounds.width
+ node.height = bounds.height
+
+ // Invalidate cached paths so they're rebuilt from our live network
+ r.vectorPathCache.delete(nodeId)
+ r.fillGeometryCache.delete(nodeId)
+ r.strokeGeometryCache.delete(nodeId)
+
+ // The overlay canvas is in screen space after panX/panY + zoom scaling.
+ // renderShapeUncached expects a canvas translated to the node's local origin.
+ canvas.save()
+ canvas.translate(bounds.x * r.zoom + r.panX, bounds.y * r.zoom + r.panY)
+ canvas.scale(r.zoom, r.zoom)
+
+ r.renderShapeUncached(canvas, node, graph)
+
+ canvas.restore()
+
+ // Restore the original node properties
+ node.vectorNetwork = origNetwork
+ node.x = origX
+ node.y = origY
+ node.width = origW
+ node.height = origH
+
+ // Invalidate caches again so the original renders correctly after exit
+ r.vectorPathCache.delete(nodeId)
+ r.fillGeometryCache.delete(nodeId)
+ r.strokeGeometryCache.delete(nodeId)
+}
+
+// ---------------------------------------------------------------------------
+// Lazy paint cache
+// ---------------------------------------------------------------------------
+
+const paintCache = new WeakMap<
+ SkiaRenderer,
+ {
+ handleLinePaint: Paint
+ handleLineSelectedPaint: Paint
+ handleLineHoverPaint: Paint
+ vertexStroke1px: Paint
+ vertexSelectedFill: Paint
+ handleSelectedFill: Paint
+ handleSelectedStroke: Paint
+ handleHoverFill: Paint
+ handleHoverStroke: Paint
+ techStrokePaint: Paint
+ }
+>()
+
+function ensureNodeEditPaints(r: SkiaRenderer) {
+ if (paintCache.has(r)) return
+ const ck = r.ck
+
+ // Default handle line — gray
+ const handleLinePaint = new ck.Paint()
+ handleLinePaint.setStyle(ck.PaintStyle.Stroke)
+ handleLinePaint.setStrokeWidth(1)
+ handleLinePaint.setColor(ck.Color4f(0.6, 0.6, 0.6, 1))
+ handleLinePaint.setAntiAlias(true)
+
+ // Selected handle line — blue
+ const handleLineSelectedPaint = new ck.Paint()
+ handleLineSelectedPaint.setStyle(ck.PaintStyle.Stroke)
+ handleLineSelectedPaint.setStrokeWidth(1)
+ handleLineSelectedPaint.setColor(ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1))
+ handleLineSelectedPaint.setAntiAlias(true)
+
+ // Hover handle line — light blue
+ const handleLineHoverPaint = new ck.Paint()
+ handleLineHoverPaint.setStyle(ck.PaintStyle.Stroke)
+ handleLineHoverPaint.setStrokeWidth(1)
+ handleLineHoverPaint.setColor(ck.Color4f(LIGHT_BLUE[0], LIGHT_BLUE[1], LIGHT_BLUE[2], 1))
+ handleLineHoverPaint.setAntiAlias(true)
+
+ // Vertex stroke — blue 1px
+ const vertexStroke1px = new ck.Paint()
+ vertexStroke1px.setStyle(ck.PaintStyle.Stroke)
+ vertexStroke1px.setStrokeWidth(1)
+ vertexStroke1px.setColor(ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1))
+ vertexStroke1px.setAntiAlias(true)
+
+ // Vertex selected fill — blue
+ const vertexSelectedFill = new ck.Paint()
+ vertexSelectedFill.setStyle(ck.PaintStyle.Fill)
+ vertexSelectedFill.setColor(ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1))
+ vertexSelectedFill.setAntiAlias(true)
+
+ // Selected handle diamond — blue fill
+ const handleSelectedFill = new ck.Paint()
+ handleSelectedFill.setStyle(ck.PaintStyle.Fill)
+ handleSelectedFill.setColor(ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1))
+ handleSelectedFill.setAntiAlias(true)
+
+ // Selected handle diamond — white outset stroke 3px
+ const handleSelectedStroke = new ck.Paint()
+ handleSelectedStroke.setStyle(ck.PaintStyle.Stroke)
+ handleSelectedStroke.setStrokeWidth(3)
+ handleSelectedStroke.setColor(ck.Color4f(1, 1, 1, 1))
+ handleSelectedStroke.setAntiAlias(true)
+
+ // Hover handle diamond — light blue fill
+ const handleHoverFill = new ck.Paint()
+ handleHoverFill.setStyle(ck.PaintStyle.Fill)
+ handleHoverFill.setColor(ck.Color4f(LIGHT_BLUE[0], LIGHT_BLUE[1], LIGHT_BLUE[2], 1))
+ handleHoverFill.setAntiAlias(true)
+
+ // Hover handle diamond — white outset stroke 3px
+ const handleHoverStroke = new ck.Paint()
+ handleHoverStroke.setStyle(ck.PaintStyle.Stroke)
+ handleHoverStroke.setStrokeWidth(3)
+ handleHoverStroke.setColor(ck.Color4f(1, 1, 1, 1))
+ handleHoverStroke.setAntiAlias(true)
+
+ // Technical stroke: rgb(178,178,178) = 0.698
+ const techStrokePaint = new ck.Paint()
+ techStrokePaint.setStyle(ck.PaintStyle.Stroke)
+ techStrokePaint.setStrokeWidth(1)
+ techStrokePaint.setColor(ck.Color4f(0.698, 0.698, 0.698, 1))
+ techStrokePaint.setAntiAlias(true)
+
+ paintCache.set(r, {
+ handleLinePaint,
+ handleLineSelectedPaint,
+ handleLineHoverPaint,
+ vertexStroke1px,
+ vertexSelectedFill,
+ handleSelectedFill,
+ handleSelectedStroke,
+ handleHoverFill,
+ handleHoverStroke,
+ techStrokePaint
+ })
+}
+
+function getNodeEditPaints(r: SkiaRenderer) {
+ const paints = paintCache.get(r)
+ if (!paints) {
+ throw new Error('Node edit paints are not initialized')
+ }
+ return paints
+}
+
+// ---------------------------------------------------------------------------
+// Technical stroke outline
+// ---------------------------------------------------------------------------
+
+function drawTechStroke(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ vertices: VectorVertex[],
+ segments: VectorSegment[],
+ regions: VectorRegion[]
+): void {
+ const { techStrokePaint } = getNodeEditPaints(r)
+ const network = { vertices, segments, regions }
+ const paths = vectorNetworkToPath(r.ck, network)
+
+ // Set stroke width to compensate for canvas scale so it's always 1px on screen
+ techStrokePaint.setStrokeWidth(1 / r.zoom)
+
+ canvas.save()
+ canvas.translate(r.panX, r.panY)
+ canvas.scale(r.zoom, r.zoom)
+
+ for (const p of paths) {
+ canvas.drawPath(p, techStrokePaint)
+ p.delete()
+ }
+
+ canvas.restore()
+}
+
+// ---------------------------------------------------------------------------
+// Handle lines + diamonds
+// ---------------------------------------------------------------------------
+
+function drawEditHandles(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ vertices: VectorVertex[],
+ segments: VectorSegment[],
+ handleVisibleVertices: Set<number>,
+ toScreen: ToScreenFn,
+ selectedHandles: Set<string>,
+ hovered: HandleInfo
+): void {
+ const paints = getNodeEditPaints(r)
+ for (let si = 0; si < segments.length; si++) {
+ const seg = segments[si]
+ drawSegmentHandle(
+ r,
+ canvas,
+ vertices,
+ seg,
+ si,
+ 'tangentStart',
+ handleVisibleVertices,
+ toScreen,
+ selectedHandles,
+ hovered,
+ paints
+ )
+ drawSegmentHandle(
+ r,
+ canvas,
+ vertices,
+ seg,
+ si,
+ 'tangentEnd',
+ handleVisibleVertices,
+ toScreen,
+ selectedHandles,
+ hovered,
+ paints
+ )
+ }
+}
+
+function drawSegmentHandle(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ vertices: VectorVertex[],
+ seg: VectorSegment,
+ segmentIndex: number,
+ tangentField: 'tangentStart' | 'tangentEnd',
+ handleVisibleVertices: Set<number>,
+ toScreen: ToScreenFn,
+ selectedHandles: Set<string>,
+ hovered: HandleInfo,
+ paints: ReturnType<typeof getNodeEditPaints>
+): void {
+ const vertexIndex = tangentField === 'tangentStart' ? seg.start : seg.end
+ if (!handleVisibleVertices.has(vertexIndex)) return
+
+ const tangent = seg[tangentField]
+ if (tangent.x === 0 && tangent.y === 0) return
+
+ const key = `${segmentIndex}:${tangentField}`
+ const isSel = selectedHandles.has(key)
+ const isHov =
+ !isSel &&
+ !!hovered &&
+ hovered.segmentIndex === segmentIndex &&
+ hovered.tangentField === tangentField
+
+ let linePaint = paints.handleLinePaint
+ if (isSel) linePaint = paints.handleLineSelectedPaint
+ else if (isHov) linePaint = paints.handleLineHoverPaint
+
+ const anchor = toScreen(vertices[vertexIndex].x, vertices[vertexIndex].y)
+ const cp = toScreen(vertices[vertexIndex].x + tangent.x, vertices[vertexIndex].y + tangent.y)
+ canvas.drawLine(anchor.x, anchor.y, cp.x, cp.y, linePaint)
+
+ if (isSel) {
+ drawHandleDiamond(r, canvas, cp.x, cp.y, paints.handleSelectedFill, paints.handleSelectedStroke)
+ return
+ }
+ if (isHov) {
+ drawHandleDiamond(r, canvas, cp.x, cp.y, paints.handleHoverFill, paints.handleHoverStroke)
+ return
+ }
+ drawHandleDiamond(r, canvas, cp.x, cp.y, r.penVertexFill, paints.vertexStroke1px)
+}
+
+function drawHandleDiamond(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ x: number,
+ y: number,
+ fillPaint: Paint,
+ strokePaint: Paint
+): void {
+ const s = PEN_HANDLE_RADIUS
+ const path = new r.ck.Path()
+ path.moveTo(x, y - s)
+ path.lineTo(x + s, y)
+ path.lineTo(x, y + s)
+ path.lineTo(x - s, y)
+ path.close()
+
+ // Draw stroke first (outset) then fill on top
+ canvas.drawPath(path, strokePaint)
+ canvas.drawPath(path, fillPaint)
+ path.delete()
+}
+
+// ---------------------------------------------------------------------------
+// Vertex circles
+// ---------------------------------------------------------------------------
+
+function drawEditVertices(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ vertices: VectorVertex[],
+ selectedVertexIndices: Set<number>,
+ toScreen: ToScreenFn
+): void {
+ const vertexFill = r.penVertexFill
+ const { vertexStroke1px, vertexSelectedFill } = getNodeEditPaints(r)
+
+ for (let i = 0; i < vertices.length; i++) {
+ const v = toScreen(vertices[i].x, vertices[i].y)
+ const radius = PEN_VERTEX_RADIUS
+
+ if (selectedVertexIndices.has(i)) {
+ canvas.drawCircle(v.x, v.y, radius, vertexSelectedFill)
+ canvas.drawCircle(v.x, v.y, radius, vertexStroke1px)
+ } else {
+ canvas.drawCircle(v.x, v.y, radius, vertexFill)
+ canvas.drawCircle(v.x, v.y, radius, vertexStroke1px)
+ }
+ }
+}
diff --git a/packages/core/src/renderer/overlays.ts b/packages/core/src/renderer/overlays.ts
index 3dd0eef73..5cc580514 100644
--- a/packages/core/src/renderer/overlays.ts
+++ b/packages/core/src/renderer/overlays.ts
@@ -97,12 +97,14 @@ export function drawSelection(
overlays: RenderOverlays
): void {
if (selectedIds.size === 0) return
+ const nodeEditId = overlays.nodeEditState?.nodeId ?? null
r.drawParentFrameOutlines(canvas, graph, selectedIds)
if (selectedIds.size === 1) {
const id = [...selectedIds][0]
if (overlays.editingTextId === id) return
+ if (nodeEditId === id) return
const node = graph.getNode(id)
if (!node) return
@@ -120,6 +122,7 @@ export function drawSelection(
}
for (const id of selectedIds) {
+ if (nodeEditId === id) continue
const node = graph.getNode(id)
if (!node) continue
@@ -135,8 +138,10 @@ export function drawSelection(
r.selectionPaint.setColor(r.selColor())
const nodes = [...selectedIds]
+ .filter((id) => id !== nodeEditId)
.map((id) => graph.getNode(id))
.filter((n): n is SceneNode => n !== undefined)
+ if (nodes.length === 0) return
r.drawGroupBounds(canvas, nodes, graph)
r.drawSelectionLabels(canvas, graph, selectedIds)
@@ -519,3 +524,4 @@ export function drawTextEditOverlay(
}
export { drawPenOverlay, drawRemoteCursors } from './pen-overlay'
+export { drawNodeEditOverlay } from './node-edit-overlay'
diff --git a/packages/core/src/renderer/pen-overlay.ts b/packages/core/src/renderer/pen-overlay.ts
index 37eb02048..a0669a030 100644
--- a/packages/core/src/renderer/pen-overlay.ts
+++ b/packages/core/src/renderer/pen-overlay.ts
@@ -7,14 +7,13 @@ import type { Canvas, Paint } from 'canvaskit-wasm'
type ToScreenFn = (x: number, y: number) => Vector
-function buildPenPath(
+/** Build a CanvasKit Path from pen state segments */
+function buildSegmentsPath(
r: SkiaRenderer,
- canvas: Canvas,
penState: NonNullable<RenderOverlays['penState']>,
toScreen: ToScreenFn
-): void {
- const { vertices, segments, dragTangent, cursorX, cursorY } = penState
-
+): InstanceType<typeof r.ck.Path> {
+ const { vertices, segments } = penState
const path = new r.ck.Path()
for (const seg of segments) {
const s = toScreen(vertices[seg.start].x, vertices[seg.start].y)
@@ -40,24 +39,71 @@ function buildPenPath(
path.cubicTo(cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y)
}
}
+ return path
+}
- if (vertices.length > 0 && cursorX != null && cursorY != null) {
+/** Build a Path for the preview line from last vertex to cursor */
+function buildCursorPath(
+ r: SkiaRenderer,
+ penState: NonNullable<RenderOverlays['penState']>,
+ toScreen: ToScreenFn
+): InstanceType<typeof r.ck.Path> | null {
+ const { vertices, dragTangent, cursorX, cursorY } = penState
+ if (vertices.length === 0) return null
+
+ if (penState.pendingClose && vertices.length > 2) {
+ const path = new r.ck.Path()
const last = toScreen(vertices[vertices.length - 1].x, vertices[vertices.length - 1].y)
- const cursor = toScreen(cursorX, cursorY)
+ const first = toScreen(vertices[0].x, vertices[0].y)
path.moveTo(last.x, last.y)
if (dragTangent) {
- const cp1 = toScreen(
- vertices[vertices.length - 1].x + dragTangent.x,
- vertices[vertices.length - 1].y + dragTangent.y
- )
- path.cubicTo(cp1.x, cp1.y, cursor.x, cursor.y, cursor.x, cursor.y)
+ // Closing preview: segment last -> first, active handle belongs to first vertex.
+ const cp2 = toScreen(vertices[0].x + dragTangent.x, vertices[0].y + dragTangent.y)
+ path.cubicTo(last.x, last.y, cp2.x, cp2.y, first.x, first.y)
} else {
- path.lineTo(cursor.x, cursor.y)
+ path.lineTo(first.x, first.y)
}
+ return path
}
- canvas.drawPath(path, r.penPathPaint)
- path.delete()
+ if (cursorX == null || cursorY == null) return null
+
+ const path = new r.ck.Path()
+ const last = toScreen(vertices[vertices.length - 1].x, vertices[vertices.length - 1].y)
+ const cursor = toScreen(cursorX, cursorY)
+ path.moveTo(last.x, last.y)
+ if (dragTangent) {
+ const cp1 = toScreen(
+ vertices[vertices.length - 1].x + dragTangent.x,
+ vertices[vertices.length - 1].y + dragTangent.y
+ )
+ path.cubicTo(cp1.x, cp1.y, cursor.x, cursor.y, cursor.x, cursor.y)
+ } else {
+ path.lineTo(cursor.x, cursor.y)
+ }
+ return path
+}
+
+function drawPenPaths(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ penState: NonNullable<RenderOverlays['penState']>,
+ toScreen: ToScreenFn
+): void {
+ // 1) Draw committed segments with live object style (black 2px)
+ const segPath = buildSegmentsPath(r, penState, toScreen)
+ canvas.drawPath(segPath, r.penLiveStrokePaint)
+
+ // 2) Draw grey 1px tech outline over committed segments
+ canvas.drawPath(segPath, r.penPathPaint)
+ segPath.delete()
+
+ // 3) Draw cursor preview line with tech outline only
+ const cursorPath = buildCursorPath(r, penState, toScreen)
+ if (cursorPath) {
+ canvas.drawPath(cursorPath, r.penPathPaint)
+ cursorPath.delete()
+ }
}
function drawPenHandlePoint(
@@ -98,10 +144,16 @@ function drawPenTangentHandles(
}
if (dragTangent && vertices.length > 0) {
- const last = vertices[vertices.length - 1]
- const cp1 = toScreen(last.x + dragTangent.x, last.y + dragTangent.y)
- const cp2 = toScreen(last.x - dragTangent.x, last.y - dragTangent.y)
- canvas.drawLine(cp2.x, cp2.y, cp1.x, cp1.y, handlePaint)
+ // During closing, handles are on vertex 0; otherwise on the last vertex
+ const anchor = penState.pendingClose ? vertices[0] : vertices[vertices.length - 1]
+ const anchorS = toScreen(anchor.x, anchor.y)
+ const cp1 = toScreen(anchor.x + dragTangent.x, anchor.y + dragTangent.y)
+ const opposite = penState.oppositeDragTangent ?? { x: -dragTangent.x, y: -dragTangent.y }
+ const cp2 = toScreen(anchor.x + opposite.x, anchor.y + opposite.y)
+ canvas.drawLine(anchorS.x, anchorS.y, cp1.x, cp1.y, handlePaint)
+ if (opposite.x !== 0 || opposite.y !== 0) {
+ canvas.drawLine(anchorS.x, anchorS.y, cp2.x, cp2.y, handlePaint)
+ }
drawPenHandlePoint(canvas, cp1.x, cp1.y, vertexFill, handlePaint)
drawPenHandlePoint(canvas, cp2.x, cp2.y, vertexFill, handlePaint)
}
@@ -123,7 +175,7 @@ export function drawPenOverlay(
y: y * r.zoom + r.panY
})
- buildPenPath(r, canvas, penState, toScreen)
+ drawPenPaths(r, canvas, penState, toScreen)
drawPenTangentHandles(canvas, penState, toScreen, r.penHandlePaint, vertexFill)
for (let i = 0; i < vertices.length; i++) {
diff --git a/packages/core/src/renderer/renderer.ts b/packages/core/src/renderer/renderer.ts
index f43c32656..cc8ce8c63 100644
--- a/packages/core/src/renderer/renderer.ts
+++ b/packages/core/src/renderer/renderer.ts
@@ -50,6 +50,7 @@ import {
drawSectionTitles as drawSectionTitlesFn,
drawComponentLabels as drawComponentLabelsFn
} from './labels'
+import { drawNodeEditOverlay as drawNodeEditOverlayFn } from './node-edit-overlay'
import {
drawHoverHighlight as drawHoverHighlightFn,
drawEnteredContainer as drawEnteredContainerFn,
@@ -107,10 +108,18 @@ import {
} from './text'
import type { EditorState } from '../editor/types'
-import type { SceneNode, SceneGraph, Fill, Stroke } from '../scene-graph'
+import type {
+ SceneNode,
+ SceneGraph,
+ Fill,
+ Stroke,
+ VectorVertex,
+ VectorRegion
+} from '../scene-graph'
import type { SnapGuide } from '../snap'
import type { TextEditor } from '../text-editor'
import type { Color, Rect, Vector } from '../types'
+import type { NodeEditOverlayState } from './node-edit-overlay'
import type {
Image as CKImage,
Path,
@@ -151,10 +160,27 @@ export interface RenderOverlays {
tangentEnd: Vector
}>
dragTangent: Vector | null
+ oppositeDragTangent?: Vector | null
closingToFirst: boolean
+ pendingClose?: boolean
cursorX?: number
cursorY?: number
} | null
+ nodeEditState?: {
+ nodeId: string
+ vertices: VectorVertex[]
+ segments: Array<{
+ start: number
+ end: number
+ tangentStart: Vector
+ tangentEnd: Vector
+ }>
+ regions: VectorRegion[]
+ selectedVertexIndices: Set<number>
+ /** Set of selected handles as "segIdx:tangentField" strings */
+ selectedHandles?: Set<string>
+ hoveredHandleInfo?: { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null
+ } | null
remoteCursors?: Array<{
name: string
color: Color
@@ -206,6 +232,7 @@ export class SkiaRenderer {
rulerBadgePaint: Paint
rulerLabelPaint: Paint
penPathPaint: Paint
+ penLiveStrokePaint: Paint
penHandlePaint: Paint
penVertexFill: Paint
penVertexStroke: Paint
@@ -361,12 +388,20 @@ export class SkiaRenderer {
this.rulerLabelPaint.setColor(ck.Color4f(1, 1, 1, 1))
this.rulerLabelPaint.setAntiAlias(true)
+ // Technical outline: 1px grey (same as node-edit techStroke)
this.penPathPaint = new ck.Paint()
this.penPathPaint.setStyle(ck.PaintStyle.Stroke)
- this.penPathPaint.setStrokeWidth(PEN_PATH_STROKE_WIDTH)
- this.penPathPaint.setColor(this.selColor())
+ this.penPathPaint.setStrokeWidth(1)
+ this.penPathPaint.setColor(ck.Color4f(0.698, 0.698, 0.698, 1))
this.penPathPaint.setAntiAlias(true)
+ // Live stroke preview: 2px black (actual object style)
+ this.penLiveStrokePaint = new ck.Paint()
+ this.penLiveStrokePaint.setStyle(ck.PaintStyle.Stroke)
+ this.penLiveStrokePaint.setStrokeWidth(PEN_PATH_STROKE_WIDTH)
+ this.penLiveStrokePaint.setColor(ck.Color4f(0, 0, 0, 1))
+ this.penLiveStrokePaint.setAntiAlias(true)
+
this.penHandlePaint = new ck.Paint()
this.penHandlePaint.setStyle(ck.PaintStyle.Stroke)
this.penHandlePaint.setStrokeWidth(1)
@@ -378,9 +413,10 @@ export class SkiaRenderer {
this.penVertexFill.setColor(ck.WHITE)
this.penVertexFill.setAntiAlias(true)
+ // Vertex circle outline: 1px blue
this.penVertexStroke = new ck.Paint()
this.penVertexStroke.setStyle(ck.PaintStyle.Stroke)
- this.penVertexStroke.setStrokeWidth(PEN_PATH_STROKE_WIDTH)
+ this.penVertexStroke.setStrokeWidth(1)
this.penVertexStroke.setColor(this.selColor())
this.penVertexStroke.setAntiAlias(true)
}
@@ -682,6 +718,9 @@ export class SkiaRenderer {
viewportHeight: number,
showRulers = true
): void {
+ const extendedState = state as EditorState & {
+ nodeEditState?: RenderOverlays['nodeEditState']
+ }
this.dpr = IS_BROWSER ? window.devicePixelRatio || 1 : 1
this.panX = state.panX
this.panY = state.panY
@@ -711,6 +750,7 @@ export class SkiaRenderer {
cursorY: state.penCursorY ?? undefined
} as RenderOverlays['penState'])
: null,
+ nodeEditState: extendedState.nodeEditState ?? null,
remoteCursors: state.remoteCursors
},
state.sceneVersion
@@ -741,7 +781,8 @@ export class SkiaRenderer {
const hasVolatileOverlays =
overlays.dropTargetId != null ||
overlays.rotationPreview != null ||
- overlays.editingTextId != null
+ overlays.editingTextId != null ||
+ overlays.nodeEditState != null
const canUsePicture =
!hasVolatileOverlays &&
@@ -797,7 +838,11 @@ export class SkiaRenderer {
canvas.save()
canvas.scale(this.dpr, this.dpr)
- this.drawHoverHighlight(canvas, graph, overlays.hoveredNodeId)
+ this.drawHoverHighlight(
+ canvas,
+ graph,
+ overlays.hoveredNodeId === overlays.nodeEditState?.nodeId ? null : overlays.hoveredNodeId
+ )
this.drawEnteredContainer(canvas, graph, overlays.enteredContainerId)
p.beginPhase('render:selection')
this.drawSelection(canvas, graph, selectedIds, overlays)
@@ -806,6 +851,7 @@ export class SkiaRenderer {
this.drawSnapGuides(canvas, overlays.snapGuides)
this.drawMarquee(canvas, overlays.marquee)
this.drawLayoutInsertIndicator(canvas, overlays.layoutInsertIndicator)
+ this.drawNodeEditOverlay(canvas, graph, overlays.nodeEditState)
this.drawPenOverlay(canvas, overlays.penState)
this.drawRemoteCursors(canvas, graph, overlays.remoteCursors)
p.beginPhase('render:rulers')
@@ -958,6 +1004,7 @@ export class SkiaRenderer {
this.rulerBadgePaint.delete()
this.rulerLabelPaint.delete()
this.penPathPaint.delete()
+ this.penLiveStrokePaint.delete()
this.penHandlePaint.delete()
this.penVertexFill.delete()
this.penVertexStroke.delete()
@@ -1053,6 +1100,14 @@ export class SkiaRenderer {
drawTextEditOverlayFn(this, canvas, node, editor)
}
+ private drawNodeEditOverlay(
+ canvas: Canvas,
+ graph: SceneGraph,
+ editState: RenderOverlays['nodeEditState']
+ ): void {
+ drawNodeEditOverlayFn(this, canvas, graph, editState as NodeEditOverlayState | null)
+ }
+
private drawPenOverlay(canvas: Canvas, penState: RenderOverlays['penState']): void {
drawPenOverlayFn(this, canvas, penState)
}
diff --git a/packages/core/src/renderer/scene.ts b/packages/core/src/renderer/scene.ts
index db6d13a7c..80f2646db 100644
--- a/packages/core/src/renderer/scene.ts
+++ b/packages/core/src/renderer/scene.ts
@@ -123,6 +123,9 @@ export function renderNode(
const node = graph.getNode(nodeId)
if (!node || !node.visible) return
+ // Hide the node being edited in node-edit mode (overlay draws it live)
+ if (overlays.nodeEditState?.nodeId === nodeId) return
+
r._nodeCount++
const absX = parentAbsX + node.x
diff --git a/packages/core/src/scene-graph.ts b/packages/core/src/scene-graph.ts
index 5c57e3296..91c02a6ed 100644
--- a/packages/core/src/scene-graph.ts
+++ b/packages/core/src/scene-graph.ts
@@ -371,9 +371,10 @@ function createDefaultNode(type: NodeType, overrides: Partial<SceneNode> = {}):
width: 100,
height: 100,
rotation: 0,
- fills: type === 'TEXT'
- ? [{ type: 'SOLID' as const, color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
- : [],
+ fills:
+ type === 'TEXT'
+ ? [{ type: 'SOLID' as const, color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ : [],
strokes: [],
effects: [],
opacity: 1,
diff --git a/packages/core/src/vector.ts b/packages/core/src/vector.ts
index e9bc20baa..c1bfdf058 100644
--- a/packages/core/src/vector.ts
+++ b/packages/core/src/vector.ts
@@ -1,3 +1,5 @@
+import { computeAccurateBounds } from './bezier-math'
+
import type {
HandleMirroring,
VectorNetwork,
@@ -106,7 +108,33 @@ export function decodeVectorNetworkBlob(
return { vertices, segments, regions }
}
-export function encodeVectorNetworkBlob(network: VectorNetwork): Uint8Array {
+/** Build a styleOverrideTable from vertex handleMirroring values.
+ * Returns a map from handleMirroring value to styleID, plus the table array. */
+export function buildStyleOverrideTable(network: VectorNetwork): {
+ table: StyleOverride[]
+ mirroringToId: Map<string, number>
+} {
+ const mirroringToId = new Map<string, number>()
+ const table: StyleOverride[] = []
+ let nextId = 1
+
+ for (const v of network.vertices) {
+ const hm = v.handleMirroring ?? 'NONE'
+ if (hm === 'NONE') continue
+ if (!mirroringToId.has(hm)) {
+ mirroringToId.set(hm, nextId)
+ table.push({ styleID: nextId, handleMirroring: hm })
+ nextId++
+ }
+ }
+
+ return { table, mirroringToId }
+}
+
+export function encodeVectorNetworkBlob(
+ network: VectorNetwork,
+ mirroringToId?: Map<string, number>
+): Uint8Array {
const { vertices, segments, regions } = network
let regionBytes = 0
@@ -130,8 +158,10 @@ export function encodeVectorNetworkBlob(network: VectorNetwork): Uint8Array {
o += 4
for (const v of vertices) {
- view.setUint32(o, 0, true)
- o += 4 // styleOverrideIdx (TODO: encode handleMirroring)
+ const hm = v.handleMirroring ?? 'NONE'
+ const styleIdx = (hm !== 'NONE' && mirroringToId?.get(hm)) || 0
+ view.setUint32(o, styleIdx, true)
+ o += 4
view.setFloat32(o, v.x, true)
o += 4
view.setFloat32(o, v.y, true)
@@ -338,38 +368,7 @@ function buildChains(segments: VectorSegment[], _vertexCount: number): number[][
}
export function computeVectorBounds(network: VectorNetwork): Rect {
- if (network.vertices.length === 0) {
- return { x: 0, y: 0, width: 0, height: 0 }
- }
-
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
-
- for (const v of network.vertices) {
- minX = Math.min(minX, v.x)
- minY = Math.min(minY, v.y)
- maxX = Math.max(maxX, v.x)
- maxY = Math.max(maxY, v.y)
- }
-
- // Also consider bezier control points for tighter bounds
- for (const seg of network.segments) {
- const start = network.vertices[seg.start]
- const end = network.vertices[seg.end]
- const cp1x = start.x + seg.tangentStart.x
- const cp1y = start.y + seg.tangentStart.y
- const cp2x = end.x + seg.tangentEnd.x
- const cp2y = end.y + seg.tangentEnd.y
-
- minX = Math.min(minX, cp1x, cp2x)
- minY = Math.min(minY, cp1y, cp2y)
- maxX = Math.max(maxX, cp1x, cp2x)
- maxY = Math.max(maxY, cp1y, cp2y)
- }
-
- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }
+ return computeAccurateBounds(network)
}
const CMD_CLOSE = 0
diff --git a/packages/docs/ru/user-guide/pen-tool.md b/packages/docs/ru/user-guide/pen-tool.md
index 31e5af2ad..95007e9e3 100644
--- a/packages/docs/ru/user-guide/pen-tool.md
+++ b/packages/docs/ru/user-guide/pen-tool.md
@@ -32,10 +32,10 @@ description: Рисование векторных контуров с крив
## Сочетания клавиш
-| Действие | Mac | Windows / Linux |
-|----------|-----|-----------------|
-| Инструмент «Перо» | <kbd>P</kbd> | <kbd>P</kbd> |
-| Зафиксировать открытый контур | <kbd>Escape</kbd> | Escape |
+| Действие | Mac | Windows / Linux |
+|----------|-----|-------------------|
+| Инструмент «Перо» | <kbd>P</kbd> | <kbd>P</kbd> |
+| Зафиксировать открытый контур | <kbd>Escape</kbd> | <kbd>Escape</kbd> |
## Советы
diff --git a/packages/docs/ru/user-guide/vector-edit.md b/packages/docs/ru/user-guide/vector-edit.md
new file mode 100644
index 000000000..aca413ee0
--- /dev/null
+++ b/packages/docs/ru/user-guide/vector-edit.md
@@ -0,0 +1,92 @@
+---
+title: Редактирование векторных объектов
+description: Как редактировать геометрию векторных контуров: узлы, рычаги Безье, модификаторы и работа с Пером в режиме редактирования.
+---
+
+# Редактирование векторных объектов
+
+Режим редактирования векторных объектов позволяет менять **геометрию** кривой: положение узлов, форму сегментов и рычаги Безье.
+В этом режиме вы работаете именно с контуром, а не с обычными трансформациями объекта.
+
+## Как войти в режим
+
+- Выберите векторный объект инструментом «Выделение».
+- Сделайте **двойной клик по кривой**.
+
+После этого включается режим редактирования геометрии выбранного вектора.
+
+## Как выйти из режима
+
+- Нажмите <kbd>Escape</kbd>.
+- Или переключитесь на другой контекст редактирования.
+
+## Что меняется в этом режиме
+
+- Обычный bounding box трансформаций для объекта отключается.
+- Доступно редактирование узлов, сегментов и рычагов.
+- Курсор и взаимодействия не переключаются на resize/rotate у углов bbox.
+
+## Базовые действия
+
+### Перемещение узла
+
+- Потяните опорную точку (узел) мышью.
+- Примыкающие сегменты и форма контура обновляются сразу в предпросмотре.
+
+### Редактирование рычага Безье
+
+- Потяните рычаг узла.
+- По умолчанию поведение определяется текущим типом композиции рычагов узла.
+
+## Модификаторы при перетаскивании рычага
+
+| Действие | Mac | Windows / Linux |
+|----------|-----|-----------------|
+| Continuous (Гладкие / Зависимые) | <kbd>Cmd</kbd> + drag | <kbd>Ctrl</kbd> + drag |
+| Corner (Независимые рычаги) | <kbd>Option</kbd> + drag | <kbd>Alt</kbd> + drag |
+| Фиксация направления (только длина) | <kbd>Shift</kbd> + drag | <kbd>Shift</kbd> + drag |
+
+### Continuous: <kbd>Cmd</kbd>/<kbd>Ctrl</kbd> + drag
+
+- Активный рычаг выстраивается по той же прямой, что и сестринский.
+- Меняется только длина активного рычага.
+- Удобно для плавного перехода без излома.
+
+### Corner: <kbd>Option</kbd>/<kbd>Alt</kbd> + drag
+
+- Активный рычаг редактируется независимо.
+- Сестринский рычаг не двигается.
+- Удобно для создания «ломаного» перехода.
+
+### Фиксация направления: <kbd>Shift</kbd> + drag
+
+Для узлов с композициями **Continuous** и **Symmetric**:
+
+- направление пары рычагов фиксируется в положении, которое было **до начала текущего перетаскивания**;
+- перетаскивание меняет только длину (или длины, в зависимости от композиции узла).
+
+## Переопределение изгиба через перетаскивание узла
+
+При перетаскивании узла с зажатым <kbd>Cmd</kbd>/<kbd>Ctrl</kbd> система выбирает редактируемый рычаг по **направлению примыкания сегмента** к узлу (а не просто по ближайшей соседней точке).
+Это работает и для узлов с несколькими примыкающими сегментами (vector web): после выбора целевой рычаг фиксируется на весь текущий drag.
+
+## Работа Пером внутри режима редактирования
+
+Если активирован инструмент «Перо»:
+
+- **Клик по сегменту** — добавляет новую опорную точку (разрезает сегмент).
+- **Клик по концевой точке** открытого контура — продолжает рисование от этой точки.
+- **Option/Alt + клик по узлу** — удаляет узел (если топология позволяет).
+
+Подробнее о создании контуров и замыкании: [Инструмент «Перо»](./pen-tool.md).
+
+## Практический сценарий
+
+1. Нарисуйте форму Пером.
+2. Двойным кликом войдите в «Редактирование векторных объектов».
+3. Подвиньте узлы, чтобы поправить силуэт.
+4. Потяните рычаги:
+ - с <kbd>Cmd</kbd>/<kbd>Ctrl</kbd> для плавного сопряжения,
+ - с <kbd>Option</kbd>/<kbd>Alt</kbd> для независимой правки,
+ - с <kbd>Shift</kbd> для изменения только длины.
+5. Нажмите <kbd>Escape</kbd>, чтобы выйти.
diff --git a/packages/docs/user-guide/vector-edit.md b/packages/docs/user-guide/vector-edit.md
new file mode 100644
index 000000000..86557a436
--- /dev/null
+++ b/packages/docs/user-guide/vector-edit.md
@@ -0,0 +1,92 @@
+---
+title: Vector Object Editing
+description: How to edit vector path geometry: anchors, bezier handles, modifiers, and Pen tool actions in edit mode.
+---
+
+# Vector Object Editing
+
+Vector Object Editing mode lets you change a curve's **geometry**: anchor positions, segment shape, and bezier handles.
+In this mode, you edit the path itself, not standard object transforms.
+
+## Entering the Mode
+
+- Select a vector object with the Select tool.
+- **Double-click the curve**.
+
+This activates geometry editing for the selected vector.
+
+## Exiting the Mode
+
+- Press <kbd>Escape</kbd>.
+- Or switch to another editing context.
+
+## What Changes in This Mode
+
+- The normal transform bounding box is disabled for the object.
+- Anchor, segment, and handle editing becomes available.
+- Cursor behavior does not switch to resize/rotate at bbox corners.
+
+## Basic Actions
+
+### Move an Anchor
+
+- Drag an anchor point.
+- Connected segments and path shape update live in preview.
+
+### Edit a Bezier Handle
+
+- Drag a handle on the anchor.
+- By default, behavior follows the anchor's current handle composition.
+
+## Handle Drag Modifiers
+
+| Action | Mac | Windows / Linux |
+|----------|-----|-----------------|
+| Continuous (Smooth / Continuous) | <kbd>Cmd</kbd> + drag | <kbd>Ctrl</kbd> + drag |
+| Corner (Independent handles) | <kbd>Option</kbd> + drag | <kbd>Alt</kbd> + drag |
+| Direction lock (length only) | <kbd>Shift</kbd> + drag | <kbd>Shift</kbd> + drag |
+
+### Continuous: <kbd>Cmd</kbd>/<kbd>Ctrl</kbd> + drag
+
+- The active handle is constrained to the same line as the sister handle.
+- Only the active handle length changes.
+- Use this for smooth transitions without a corner break.
+
+### Corner: <kbd>Option</kbd>/<kbd>Alt</kbd> + drag
+
+- The active handle is edited independently.
+- The sister handle stays in place.
+- Use this to create a sharp corner transition.
+
+### Direction Lock: <kbd>Shift</kbd> + drag
+
+For anchors with **Continuous** or **Symmetric** composition:
+
+- handle direction is locked to the value from **before the current drag started**;
+- dragging changes only handle length (or lengths, depending on composition).
+
+## Bend Override by Dragging an Anchor
+
+When you drag an anchor while holding <kbd>Cmd</kbd>/<kbd>Ctrl</kbd>, the editor selects the target handle by **segment attachment direction** at that anchor (not by nearest neighbor-point distance).
+This also works on multi-branch vector-web anchors: once resolved, the target handle stays locked for the current drag.
+
+## Using the Pen Tool in Edit Mode
+
+With the Pen tool active:
+
+- **Click a segment** to insert a new anchor (split segment).
+- **Click an open-path endpoint** to resume drawing from that point.
+- **Option/Alt + click an anchor** to delete it (when topology allows).
+
+For path creation and closing behavior, see [Pen Tool](./pen-tool.md).
+
+## Practical Workflow
+
+1. Draw a shape with the Pen tool.
+2. Double-click the curve to enter Vector Object Editing mode.
+3. Move anchors to refine the silhouette.
+4. Drag handles:
+ - with <kbd>Cmd</kbd>/<kbd>Ctrl</kbd> for smooth continuous transitions,
+ - with <kbd>Option</kbd>/<kbd>Alt</kbd> for independent edits,
+ - with <kbd>Shift</kbd> for length-only edits.
+5. Press <kbd>Escape</kbd> to exit.
diff --git a/packages/vue/src/Canvas/useCanvasInput.ts b/packages/vue/src/Canvas/useCanvasInput.ts
index 153d08a9d..4347e7d21 100644
--- a/packages/vue/src/Canvas/useCanvasInput.ts
+++ b/packages/vue/src/Canvas/useCanvasInput.ts
@@ -14,13 +14,18 @@ import { handleMoveMove, handleMoveUp } from '@open-pencil/vue/shared/input/move
import { setupPanZoom } from '@open-pencil/vue/shared/input/pan-zoom'
import { applyResize } from '@open-pencil/vue/shared/input/resize'
import {
+ handlePenNodeEditDown,
+ handleNodeEditMove,
handleSelectDown,
updateHoverCursor,
+ hitTestEditHandle,
+ isEndpoint,
+ NODE_HIT_THRESHOLD,
type HitTestFns
} from '@open-pencil/vue/shared/input/select'
import { TOOL_TO_NODE } from '@open-pencil/vue/shared/input/types'
-import type { SceneNode } from '@open-pencil/core'
+import type { SceneNode, Vector, VectorSegment } from '@open-pencil/core'
import type { Editor } from '@open-pencil/core/editor'
import type {
DragMarquee,
@@ -29,6 +34,29 @@ import type {
DragState
} from '@open-pencil/vue/shared/input/types'
+type NodeEditState = {
+ segments: VectorSegment[]
+ vertices: Vector[]
+ hoveredHandleInfo: {
+ segmentIndex: number
+ tangentField: 'tangentStart' | 'tangentEnd'
+ } | null
+}
+
+type NodeEditMethods = Partial<{
+ nodeEditBendHandle: (
+ vertexIndex: number,
+ dx: number,
+ dy: number,
+ independent: boolean,
+ targetSegmentIndex: number | null,
+ targetTangentField: 'tangentStart' | 'tangentEnd' | null
+ ) => void
+ nodeEditZeroVertexHandles: (vertexIndex: number) => void
+ nodeEditConnectEndpoints: (a: number, b: number) => void
+ enterNodeEditMode: (nodeId: string) => void
+}>
+
/**
* Wires pointer and mouse interaction to an OpenPencil canvas.
*
@@ -256,6 +284,66 @@ export function useCanvasInput(
editor.setMarquee({ x: minX, y: minY, width: maxX - minX, height: maxY - minY })
}
+ function resolveBendTargetHandle(
+ es: NodeEditState | null | undefined,
+ vertexIndex: number,
+ samples: Vector[]
+ ): { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null {
+ if (!es || samples.length === 0) return null
+ const vx = es.vertices[vertexIndex]?.x
+ const vy = es.vertices[vertexIndex]?.y
+ if (vx == null || vy == null) return null
+
+ const sampleVector = samples.reduce(
+ (acc, p) => ({ x: acc.x + (p.x - vx), y: acc.y + (p.y - vy) }),
+ { x: 0, y: 0 }
+ )
+ const sampleLen = Math.hypot(sampleVector.x, sampleVector.y)
+ if (sampleLen < 1e-6) return null
+ const sampleDir = { x: sampleVector.x / sampleLen, y: sampleVector.y / sampleLen }
+
+ let best: { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null = null
+ let bestDot = -Infinity
+ for (let i = 0; i < es.segments.length; i++) {
+ const seg = es.segments[i]
+ let tangentField: 'tangentStart' | 'tangentEnd'
+ let neighborIndex: number
+ let tangent: Vector
+ if (seg.start === vertexIndex) {
+ tangentField = 'tangentStart'
+ neighborIndex = seg.end
+ tangent = seg.tangentStart
+ } else if (seg.end === vertexIndex) {
+ tangentField = 'tangentEnd'
+ neighborIndex = seg.start
+ tangent = seg.tangentEnd
+ } else {
+ continue
+ }
+
+ const neighbor = es.vertices[neighborIndex]
+ if (!neighbor) continue
+
+ const tangentLen = Math.hypot(tangent.x, tangent.y)
+ const base =
+ tangentLen > 1e-6
+ ? tangent
+ : {
+ x: neighbor.x - vx,
+ y: neighbor.y - vy
+ }
+ const baseLen = Math.hypot(base.x, base.y)
+ if (baseLen < 1e-6) continue
+ const dir = { x: base.x / baseLen, y: base.y / baseLen }
+ const dot = dir.x * sampleDir.x + dir.y * sampleDir.y
+ if (dot > bestDot) {
+ bestDot = dot
+ best = { segmentIndex: i, tangentField }
+ }
+ }
+ return best
+ }
+
function onMouseDown(e: MouseEvent) {
editor.setHoveredNode(null)
const { sx, sy, cx, cy } = getCoords(e)
@@ -280,11 +368,6 @@ export function useCanvasInput(
return
}
- if (tool === 'SELECT' && e.altKey && !editor.state.selectedIds.size) {
- startPanDrag(e)
- return
- }
-
if (tool === 'SELECT') {
handleSelectDown(
e,
@@ -302,8 +385,42 @@ export function useCanvasInput(
}
if (tool === 'PEN') {
+ // In node edit mode with pen tool: click curve to add point, click vertex to remove
+ const nodeEditState = (
+ editor.state as Editor['state'] & { nodeEditState?: NodeEditState | null }
+ ).nodeEditState
+ if (nodeEditState) {
+ handlePenNodeEditDown(e, cx, cy, editor)
+ return
+ }
+
+ const penState = editor.state.penState
+ if (penState && penState.vertices.length > 2) {
+ const first = penState.vertices[0]
+ const dist = Math.hypot(cx - first.x, cy - first.y)
+ if (dist < PEN_CLOSE_THRESHOLD) {
+ editor.penSetPendingClose(true)
+ editor.penSetClosingToFirst(true)
+ drag.value = {
+ type: 'pen-drag',
+ startX: first.x,
+ startY: first.y,
+ modifierMode: 'default',
+ frozenOppositeTangent: null
+ } as DragState
+ return
+ }
+ }
+
+ editor.penSetPendingClose(false)
editor.penAddVertex(cx, cy)
- drag.value = { type: 'pen-drag', startX: cx, startY: cy } as DragState
+ drag.value = {
+ type: 'pen-drag',
+ startX: cx,
+ startY: cy,
+ modifierMode: 'default',
+ frozenOppositeTangent: null
+ } as DragState
return
}
@@ -327,6 +444,7 @@ export function useCanvasInput(
}
function onMouseMove(e: MouseEvent) {
+ const nodeEditEditor = editor as Editor & NodeEditMethods
if (onCursorMove) {
const { cx, cy } = getCoords(e)
onCursorMove(cx, cy)
@@ -345,6 +463,30 @@ export function useCanvasInput(
editor.requestRepaint()
}
+ // Track hovered handle in node edit mode
+ const nodeEditState = (
+ editor.state as Editor['state'] & { nodeEditState?: NodeEditState | null }
+ ).nodeEditState
+ if (!drag.value && nodeEditState) {
+ const { cx, cy } = getCoords(e)
+ const hit = hitTestEditHandle(editor, cx, cy)
+ const es = nodeEditState
+ const prev = es.hoveredHandleInfo
+ if (hit) {
+ if (
+ !prev ||
+ prev.segmentIndex !== hit.segmentIndex ||
+ prev.tangentField !== hit.tangentField
+ ) {
+ es.hoveredHandleInfo = { segmentIndex: hit.segmentIndex, tangentField: hit.tangentField }
+ editor.requestRepaint()
+ }
+ } else if (prev) {
+ es.hoveredHandleInfo = null
+ editor.requestRepaint()
+ }
+ }
+
if (!drag.value && editor.state.activeTool === 'SELECT') {
const { sx, sy, cx, cy } = getCoords(e)
cursorOverride.value = updateHoverCursor(sx, sy, cx, cy, editor, hitFns)
@@ -381,11 +523,97 @@ export function useCanvasInput(
const tx = cx - d.startX
const ty = cy - d.startY
if (Math.hypot(tx, ty) > 2) {
- editor.penSetDragTangent(tx, ty)
+ const penState = editor.state.penState
+ const firstSeg = penState?.segments[0]
+ const closingOpposite =
+ penState?.pendingClose && firstSeg
+ ? firstSeg.start === 0
+ ? firstSeg.tangentStart
+ : firstSeg.end === 0
+ ? firstSeg.tangentEnd
+ : null
+ : null
+ const mode = e.metaKey || e.ctrlKey ? 'continuous' : e.altKey ? 'independent' : 'default'
+ if (mode !== d.modifierMode) {
+ if (mode === 'default') {
+ d.frozenOppositeTangent = null
+ } else if (!d.frozenOppositeTangent) {
+ const lastSeg = penState?.segments[penState.segments.length - 1]
+ d.frozenOppositeTangent = lastSeg
+ ? closingOpposite
+ ? { ...closingOpposite }
+ : { ...lastSeg.tangentEnd }
+ : penState?.dragTangent
+ ? { x: -penState.dragTangent.x, y: -penState.dragTangent.y }
+ : { x: 0, y: 0 }
+ }
+ d.modifierMode = mode
+ }
+
+ if (mode === 'continuous') {
+ editor.penSetDragTangent(tx, ty, {
+ keepOpposite: true,
+ constrainToOpposite: true,
+ oppositeTangent: d.frozenOppositeTangent
+ })
+ } else if (mode === 'independent') {
+ editor.penSetDragTangent(tx, ty, {
+ keepOpposite: true,
+ oppositeTangent: d.frozenOppositeTangent
+ })
+ } else {
+ editor.penSetDragTangent(
+ tx,
+ ty,
+ penState?.pendingClose
+ ? {
+ keepOpposite: true,
+ oppositeTangent: closingOpposite
+ }
+ : undefined
+ )
+ }
}
return
}
+ if (d.type === 'edit-node' || d.type === 'edit-handle') {
+ handleNodeEditMove(d, cx, cy, editor, e.altKey, e.metaKey || e.ctrlKey, e.shiftKey)
+ return
+ }
+
+ if (d.type === 'bend-handle') {
+ const dx = cx - d.startX
+ const dy = cy - d.startY
+ if (Math.hypot(dx, dy) < 2) return
+ // Lock mode on first meaningful move — persists for the rest of the drag
+ if (d.lockedMode === null) {
+ d.lockedMode = e.altKey ? 'independent' : 'symmetric'
+ }
+ if (d.dragSamples.length < 3) {
+ d.dragSamples.push({ x: cx, y: cy })
+ }
+ if (d.targetSegmentIndex === null && d.dragSamples.length >= 3) {
+ const target = resolveBendTargetHandle(nodeEditState, d.vertexIndex, d.dragSamples)
+ if (target) {
+ d.targetSegmentIndex = target.segmentIndex
+ d.targetTangentField = target.tangentField
+ }
+ }
+ if (d.targetSegmentIndex === null || d.targetTangentField === null) {
+ return
+ }
+ nodeEditEditor.nodeEditBendHandle?.(
+ d.vertexIndex,
+ dx,
+ dy,
+ d.lockedMode === 'independent',
+ d.targetSegmentIndex,
+ d.targetTangentField
+ )
+ return
+ }
+
if (d.type === 'draw') {
handleDrawMove(d, cx, cy, e.shiftKey, editor)
return
@@ -395,15 +623,60 @@ export function useCanvasInput(
}
function onMouseUp() {
+ const nodeEditEditor = editor as Editor & NodeEditMethods
if (!drag.value) return
const d = drag.value
+ if (d.type === 'bend-handle') {
+ // If no drag happened (lockedMode never set), zero all handles on this vertex
+ if (d.lockedMode === null) {
+ nodeEditEditor.nodeEditZeroVertexHandles?.(d.vertexIndex)
+ }
+ drag.value = null
+ return
+ }
+ if (d.type === 'edit-node') {
+ // Check if a single endpoint was dragged onto another endpoint → connect
+ const es = (editor.state as Editor['state'] & { nodeEditState?: NodeEditState | null })
+ .nodeEditState
+ if (es && d.origPositions.size === 1) {
+ const [draggedIdx] = d.origPositions.keys()
+ if (isEndpoint(draggedIdx, es.segments)) {
+ const v = es.vertices[draggedIdx]
+ const iz = 1 / editor.state.zoom
+ for (let i = 0; i < es.vertices.length; i++) {
+ if (i === draggedIdx) continue
+ if (!isEndpoint(i, es.segments)) continue
+ const t = es.vertices[i]
+ if (Math.hypot(v.x - t.x, v.y - t.y) < NODE_HIT_THRESHOLD * iz) {
+ nodeEditEditor.nodeEditConnectEndpoints?.(draggedIdx, i)
+ drag.value = null
+ return
+ }
+ }
+ }
+ }
+ drag.value = null
+ return
+ }
+ if (d.type === 'edit-handle') {
+ drag.value = null
+ return
+ }
if (d.type === 'move') handleMoveUp(d, editor)
else if (d.type === 'text-select') {
drag.value = null
return
} else if (d.type === 'resize') editor.commitResize(d.nodeId, d.origRect)
else if (d.type === 'pen-drag') {
+ const penState = editor.state.penState as
+ | (typeof editor.state.penState & {
+ pendingClose?: boolean
+ })
+ | null
+ if (penState?.pendingClose) {
+ editor.penCommit(true)
+ }
drag.value = null
return
} else if (d.type === 'rotate') {
@@ -421,6 +694,7 @@ export function useCanvasInput(
}
function onDblClick(e: MouseEvent) {
+ const nodeEditEditor = editor as Editor & NodeEditMethods
if (editor.state.editingTextId) return
const { cx, cy } = getCoords(e)
@@ -459,6 +733,11 @@ export function useCanvasInput(
return
}
+ if (hit.type === 'VECTOR') {
+ nodeEditEditor.enterNodeEditMode?.(hit.id)
+ return
+ }
+
editor.select([hit.id])
}
diff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.ts
index 29c48b38c..d8dc07094 100644
--- a/packages/vue/src/shared/input/resize.ts
+++ b/packages/vue/src/shared/input/resize.ts
@@ -1,7 +1,7 @@
import { hitTestHandle } from './geometry'
import type { DragResize, HandlePosition } from './types'
-import type { Rect } from '@open-pencil/core'
+import type { Rect, SceneNode } from '@open-pencil/core'
import type { Editor } from '@open-pencil/core/editor'
export function constrainToAspectRatio(
@@ -75,12 +75,38 @@ export function applyResize(
height = -height
}
- editor.updateNode(d.nodeId, {
+ const newW = Math.round(Math.max(1, width))
+ const newH = Math.round(Math.max(1, height))
+ const changes: Partial<SceneNode> = {
x: Math.round(x),
y: Math.round(y),
- width: Math.round(Math.max(1, width)),
- height: Math.round(Math.max(1, height))
- })
+ width: newW,
+ height: newH
+ }
+
+ // Scale vectorNetwork vertices + tangents proportionally
+ if (d.origVectorNetwork && origRect.width > 0 && origRect.height > 0) {
+ const sx = newW / origRect.width
+ const sy = newH / origRect.height
+ if (sx !== 1 || sy !== 1) {
+ const vn = d.origVectorNetwork
+ changes.vectorNetwork = {
+ vertices: vn.vertices.map((v) => ({
+ ...v,
+ x: v.x * sx,
+ y: v.y * sy
+ })),
+ segments: vn.segments.map((s) => ({
+ ...s,
+ tangentStart: { x: s.tangentStart.x * sx, y: s.tangentStart.y * sy },
+ tangentEnd: { x: s.tangentEnd.x * sx, y: s.tangentEnd.y * sy }
+ })),
+ regions: vn.regions
+ }
+ }
+ }
+
+ editor.updateNode(d.nodeId, changes)
}
export function tryStartResize(
@@ -113,7 +139,8 @@ export function tryStartResize(
startX: cx,
startY: cy,
origRect: { x: node.x, y: node.y, width: node.width, height: node.height },
- nodeId: id
+ nodeId: id,
+ origVectorNetwork: node.vectorNetwork ? structuredClone(node.vectorNetwork) : null
}
}
}
diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.ts
index 5c740adfe..c3312ad77 100644
--- a/packages/vue/src/shared/input/select.ts
+++ b/packages/vue/src/shared/input/select.ts
@@ -7,10 +7,47 @@ import {
import { duplicateAndDrag, detectAutoLayoutParent } from './move'
import { tryStartResize } from './resize'
-import type { DragState } from './types'
-import type { SceneNode } from '@open-pencil/core'
+import type { DragEditHandle, DragEditNode, DragState } from './types'
+import type { SceneNode, Vector, VectorSegment, VectorVertex } from '@open-pencil/core'
import type { Editor } from '@open-pencil/core/editor'
+type NodeEditState = {
+ nodeId: string
+ vertices: VectorVertex[]
+ segments: VectorSegment[]
+ selectedVertexIndices: Set<number>
+ selectedHandles: Set<string>
+ hoveredHandleInfo: {
+ segmentIndex: number
+ tangentField: 'tangentStart' | 'tangentEnd'
+ } | null
+}
+
+type NodeEditEditor = Partial<{
+ nodeEditSelectVertex: (vertexIndex: number, addToSelection: boolean) => void
+ exitNodeEditMode: (commit: boolean) => void
+ nodeEditRemoveVertex: (vertexIndex: number) => void
+ penResumeFromEndpoint: (nodeId: string, endpointVertexIndex: number) => void
+ nodeEditAddVertex: (cx: number, cy: number) => void
+ nodeEditSetHandle: (
+ segmentIndex: number,
+ tangentField: 'tangentStart' | 'tangentEnd',
+ newTangent: Vector,
+ options?: {
+ breakMirroring?: boolean
+ continuous?: boolean
+ lockDirection?: boolean
+ }
+ ) => void
+}>
+
+function getNodeEditState(editor: Editor): NodeEditState | null {
+ return (
+ (editor.state as Editor['state'] & { nodeEditState?: NodeEditState | null }).nodeEditState ??
+ null
+ )
+}
+
export interface HitTestFns {
hitTestInScope: (cx: number, cy: number, deep: boolean) => SceneNode | null
isInsideContainerBounds: (cx: number, cy: number, containerId: string) => boolean
@@ -52,6 +89,263 @@ export function resolveHit(
return null
}
+// ---------------------------------------------------------------------------
+// Node edit mode handlers
+// ---------------------------------------------------------------------------
+
+export const NODE_HIT_THRESHOLD = 8
+const HANDLE_HIT_THRESHOLD_NE = 6
+
+/** Check if vertex is an endpoint (connected to exactly 1 segment) */
+export function isEndpoint(vertexIndex: number, segments: VectorSegment[]): boolean {
+ let count = 0
+ for (const seg of segments) {
+ if (seg.start === vertexIndex || seg.end === vertexIndex) count++
+ }
+ return count === 1
+}
+
+function hitTestEditVertex(editor: Editor, cx: number, cy: number): number | null {
+ const es = getNodeEditState(editor)
+ if (!es) return null
+ const iz = 1 / editor.state.zoom
+ for (let i = 0; i < es.vertices.length; i++) {
+ const v = es.vertices[i]
+ if (Math.hypot(cx - v.x, cy - v.y) < NODE_HIT_THRESHOLD * iz) return i
+ }
+ return null
+}
+
+/** Vertices whose handles are visible: selected vertices + vertices with selected handles + their direct neighbors */
+function getHandleVisibleVertices(editor: Editor): Set<number> {
+ const es = getNodeEditState(editor)
+ if (!es) return new Set()
+ // Seed: selected vertices + vertices that own a selected handle
+ const seed = new Set(es.selectedVertexIndices)
+ for (const key of es.selectedHandles) {
+ const [siStr, tf] = key.split(':')
+ const seg = es.segments[Number(siStr)]
+ seed.add(tf === 'tangentStart' ? seg.start : seg.end)
+ }
+ // Expand: add only direct neighbors of seed vertices (no cascading)
+ const visible = new Set(seed)
+ for (const seg of es.segments) {
+ if (seed.has(seg.start)) visible.add(seg.end)
+ if (seed.has(seg.end)) visible.add(seg.start)
+ }
+ return visible
+}
+
+export function hitTestEditHandle(
+ editor: Editor,
+ cx: number,
+ cy: number
+): {
+ segmentIndex: number
+ tangentField: 'tangentStart' | 'tangentEnd'
+ vertexIndex: number
+} | null {
+ const es = getNodeEditState(editor)
+ if (!es) return null
+ const iz = 1 / editor.state.zoom
+ const visible = getHandleVisibleVertices(editor)
+
+ for (let si = 0; si < es.segments.length; si++) {
+ const seg = es.segments[si]
+
+ if (visible.has(seg.start)) {
+ const ts = seg.tangentStart
+ if (ts.x !== 0 || ts.y !== 0) {
+ const hx = es.vertices[seg.start].x + ts.x
+ const hy = es.vertices[seg.start].y + ts.y
+ if (Math.hypot(cx - hx, cy - hy) < HANDLE_HIT_THRESHOLD_NE * iz) {
+ return { segmentIndex: si, tangentField: 'tangentStart', vertexIndex: seg.start }
+ }
+ }
+ }
+
+ if (visible.has(seg.end)) {
+ const te = seg.tangentEnd
+ if (te.x !== 0 || te.y !== 0) {
+ const hx = es.vertices[seg.end].x + te.x
+ const hy = es.vertices[seg.end].y + te.y
+ if (Math.hypot(cx - hx, cy - hy) < HANDLE_HIT_THRESHOLD_NE * iz) {
+ return { segmentIndex: si, tangentField: 'tangentEnd', vertexIndex: seg.end }
+ }
+ }
+ }
+ }
+ return null
+}
+
+function handleNodeEditDown(
+ e: MouseEvent,
+ cx: number,
+ cy: number,
+ editor: Editor,
+ setDrag: (d: DragState) => void
+) {
+ const es = getNodeEditState(editor)
+ if (!es) return
+ const nodeEditEditor = editor as Editor & NodeEditEditor
+
+ // Check handle hit first (only for vertices with visible handles)
+ const handleHit = hitTestEditHandle(editor, cx, cy)
+ if (handleHit) {
+ const key = `${handleHit.segmentIndex}:${handleHit.tangentField}`
+ if (e.shiftKey) {
+ // Shift+click: toggle handle in multi-selection
+ const next = new Set(es.selectedHandles)
+ if (next.has(key)) next.delete(key)
+ else next.add(key)
+ es.selectedHandles = next
+ } else {
+ // Click on handle: select only this handle, deselect everything else
+ es.selectedVertexIndices = new Set()
+ es.selectedHandles = new Set([key])
+ }
+ setDrag({
+ type: 'edit-handle',
+ segmentIndex: handleHit.segmentIndex,
+ tangentField: handleHit.tangentField,
+ vertexIndex: handleHit.vertexIndex,
+ startX: cx,
+ startY: cy,
+ initialTangent: (() => {
+ const seg = es.segments[handleHit.segmentIndex]
+ const tangent =
+ handleHit.tangentField === 'tangentStart' ? seg.tangentStart : seg.tangentEnd
+ return { x: tangent.x, y: tangent.y }
+ })()
+ })
+ return
+ }
+
+ // Check vertex hit
+ const vi = hitTestEditVertex(editor, cx, cy)
+ if (vi !== null) {
+ if (!e.shiftKey) es.selectedHandles = new Set()
+
+ // Cmd/Ctrl + vertex click → Bend mode (recreate handles from scratch)
+ if (e.metaKey || e.ctrlKey) {
+ nodeEditEditor.nodeEditSelectVertex?.(vi, false)
+ setDrag({
+ type: 'bend-handle',
+ vertexIndex: vi,
+ startX: es.vertices[vi].x,
+ startY: es.vertices[vi].y,
+ lockedMode: null,
+ dragSamples: [],
+ targetSegmentIndex: null,
+ targetTangentField: null
+ })
+ return
+ }
+
+ // If vertex is already selected and not Shift — keep selection, just start drag
+ if (es.selectedVertexIndices.has(vi) && !e.shiftKey) {
+ // Don't re-select — preserve multi-selection for dragging
+ } else {
+ nodeEditEditor.nodeEditSelectVertex?.(vi, e.shiftKey)
+ }
+
+ // Start drag
+ const origPositions = new Map<number, Vector>()
+ for (const idx of es.selectedVertexIndices) {
+ origPositions.set(idx, { x: es.vertices[idx].x, y: es.vertices[idx].y })
+ }
+ if (!origPositions.has(vi)) {
+ origPositions.set(vi, { x: es.vertices[vi].x, y: es.vertices[vi].y })
+ }
+
+ setDrag({
+ type: 'edit-node',
+ startX: cx,
+ startY: cy,
+ origPositions
+ })
+ return
+ }
+
+ // Click on empty space: exit node edit mode
+ nodeEditEditor.exitNodeEditMode?.(true)
+}
+
+export function handlePenNodeEditDown(e: MouseEvent, cx: number, cy: number, editor: Editor) {
+ const es = getNodeEditState(editor)
+ if (!es) return
+ const nodeEditEditor = editor as Editor & NodeEditEditor
+
+ const vi = hitTestEditVertex(editor, cx, cy)
+ if (vi !== null) {
+ // Alt+click on vertex → remove it (smooth merge of adjacent segments)
+ if (e.altKey) {
+ nodeEditEditor.nodeEditRemoveVertex?.(vi)
+ return
+ }
+ // Click on endpoint → continue drawing from this endpoint
+ if (isEndpoint(vi, es.segments)) {
+ const nodeId = es.nodeId
+ nodeEditEditor.exitNodeEditMode?.(true)
+ nodeEditEditor.penResumeFromEndpoint?.(nodeId, vi)
+ return
+ }
+ // Click on non-endpoint vertex → no action
+ return
+ }
+
+ // Click on curve contour → add new anchor point
+ nodeEditEditor.nodeEditAddVertex?.(cx, cy)
+}
+
+export function handleNodeEditMove(
+ d: DragEditNode | DragEditHandle,
+ cx: number,
+ cy: number,
+ editor: Editor,
+ breakMirroring?: boolean,
+ continuous?: boolean,
+ lockDirection?: boolean
+) {
+ const nodeEditEditor = editor as Editor & NodeEditEditor
+ if (d.type === 'edit-node') {
+ const dx = cx - d.startX
+ const dy = cy - d.startY
+ const es = getNodeEditState(editor)
+ if (!es) return
+
+ for (const [idx, orig] of d.origPositions) {
+ es.vertices[idx] = {
+ ...es.vertices[idx],
+ x: orig.x + dx,
+ y: orig.y + dy
+ }
+ }
+ editor.requestRepaint()
+ return
+ }
+ const es = getNodeEditState(editor)
+ if (!es) return
+ const vertex = es.vertices[d.vertexIndex]
+ let newTangent = { x: cx - vertex.x, y: cy - vertex.y }
+ const canLockDirection =
+ lockDirection &&
+ (vertex.handleMirroring === 'ANGLE' || vertex.handleMirroring === 'ANGLE_AND_LENGTH')
+ if (canLockDirection && d.initialTangent) {
+ const len = Math.hypot(d.initialTangent.x, d.initialTangent.y)
+ if (len > 1e-6) {
+ const dir = { x: d.initialTangent.x / len, y: d.initialTangent.y / len }
+ const projectedLen = Math.max(0, newTangent.x * dir.x + newTangent.y * dir.y)
+ newTangent = { x: dir.x * projectedLen, y: dir.y * projectedLen }
+ }
+ }
+ nodeEditEditor.nodeEditSetHandle?.(d.segmentIndex, d.tangentField, newTangent, {
+ breakMirroring,
+ continuous,
+ lockDirection
+ })
+}
+
export function handleSelectDown(
e: MouseEvent,
sx: number,
@@ -64,6 +358,12 @@ export function handleSelectDown(
handleTextEditClick: (cx: number, cy: number, shiftKey: boolean) => boolean,
setDrag: (d: DragState) => void
) {
+ // Node edit mode intercept
+ if (getNodeEditState(editor)) {
+ handleNodeEditDown(e, cx, cy, editor, setDrag)
+ return
+ }
+
if (editor.state.editingTextId && handleTextEditClick(cx, cy, e.shiftKey)) return
if (editor.state.editingTextId) editor.commitTextEdit()
@@ -123,6 +423,11 @@ export function updateHoverCursor(
editor: Editor,
fns: Pick<HitTestFns, 'hitTestInScope' | 'hitTestSectionTitle' | 'hitTestComponentLabel'>
): string | null {
+ if (getNodeEditState(editor)) {
+ editor.setHoveredNode(null)
+ return null
+ }
+
let cursor: string | null = null
for (const id of editor.state.selectedIds) {
@@ -174,7 +479,10 @@ export function updateHoverCursor(
fns.hitTestSectionTitle(cx, cy) ??
fns.hitTestComponentLabel(cx, cy) ??
fns.hitTestInScope(cx, cy, false)
- editor.setHoveredNode(hit && !editor.state.selectedIds.has(hit.id) ? hit.id : null)
+ const editNodeId = getNodeEditState(editor)?.nodeId
+ editor.setHoveredNode(
+ hit && !editor.state.selectedIds.has(hit.id) && hit.id !== editNodeId ? hit.id : null
+ )
return cursor
}
diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.ts
index 9f725ecd2..3dd73baee 100644
--- a/packages/vue/src/shared/input/types.ts
+++ b/packages/vue/src/shared/input/types.ts
@@ -1,4 +1,5 @@
-import type { NodeType, Rect } from '@open-pencil/core'
+import type { NodeType, Rect, VectorNetwork } from '@open-pencil/core'
+import type { Vector } from '@open-pencil/core'
import type { Tool } from '@open-pencil/core/editor'
export type HandlePosition = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'
@@ -37,6 +38,7 @@ export interface DragResize {
startY: number
origRect: Rect
nodeId: string
+ origVectorNetwork: VectorNetwork | null
}
export interface DragMarquee {
@@ -58,6 +60,8 @@ export interface DragPen {
type: 'pen-drag'
startX: number
startY: number
+ modifierMode: 'default' | 'continuous' | 'independent'
+ frozenOppositeTangent: Vector | null
}
export interface DragTextSelect {
@@ -66,6 +70,34 @@ export interface DragTextSelect {
startY: number
}
+export interface DragEditNode {
+ type: 'edit-node'
+ startX: number
+ startY: number
+ origPositions: Map<number, { x: number; y: number }>
+}
+
+export interface DragEditHandle {
+ type: 'edit-handle'
+ segmentIndex: number
+ tangentField: 'tangentStart' | 'tangentEnd'
+ vertexIndex: number
+ startX: number
+ startY: number
+ initialTangent: Vector | null
+}
+
+export interface DragBendHandle {
+ type: 'bend-handle'
+ vertexIndex: number
+ startX: number
+ startY: number
+ lockedMode: 'symmetric' | 'independent' | null
+ dragSamples: Vector[]
+ targetSegmentIndex: number | null
+ targetTangentField: 'tangentStart' | 'tangentEnd' | null
+}
+
export type DragState =
| DragDraw
| DragMove
@@ -75,6 +107,9 @@ export type DragState =
| DragRotate
| DragPen
| DragTextSelect
+ | DragEditNode
+ | DragEditHandle
+ | DragBendHandle
export const TOOL_TO_NODE: Partial<Record<Tool, NodeType>> = {
FRAME: 'FRAME',
diff --git a/src/composables/use-keyboard.ts b/src/composables/use-keyboard.ts
index 247018abd..c9d232af2 100644
--- a/src/composables/use-keyboard.ts
+++ b/src/composables/use-keyboard.ts
@@ -12,8 +12,15 @@ import {
import { openFileDialog } from './use-menu'
+import type { Tool } from '@open-pencil/core/editor'
import type { ComputedRef } from 'vue'
+type NodeEditKeyboardMethods = Partial<{
+ nodeEditDeleteSelected: () => void
+ nodeEditBreakAtVertex: () => void
+ exitNodeEditMode: (commit: boolean) => void
+}>
+
function isEditing(e: Event) {
return e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement
}
@@ -38,7 +45,7 @@ const PREVENT_MOD_ONLY = new Set([
'KeyG'
])
const PREVENT_SHIFT_ONLY = new Set(['Digit1', 'Digit2', 'KeyA'])
-const PREVENT_PLAIN_KEY = new Set(['[', ']'])
+const PREVENT_PLAIN_KEY = new Set(['BracketLeft', 'BracketRight'])
const PREVENT_DELETE_KEY = new Set(['Backspace', 'Delete'])
function shouldPreventDefault(e: KeyboardEvent, hasPenState: boolean): boolean {
@@ -59,6 +66,7 @@ function shouldPreventDefault(e: KeyboardEvent, hasPenState: boolean): boolean {
export function useKeyboard() {
const { activeTab } = useAIChat()
const store = useEditorStore()
+ const nodeEditStore = store as typeof store & NodeEditKeyboardMethods
const { isMobile } = useViewportKind()
const { runCommand } = useEditorCommands()
@@ -94,12 +102,20 @@ export function useKeyboard() {
if (html) store.pasteFromHTML(html, cursorPos)
})
- // Spacebar hold → temporary Hand tool (Figma-style canvas pan)
- let toolBeforeSpace: (typeof store.state.activeTool) | null = null
+ // Space hold-to-pan: temporarily switch to HAND while Space is held,
+ // without losing object/node selections
+ let toolBeforeSpace: Tool | null = null
useEventListener(window, 'keydown', (e: KeyboardEvent) => {
if (isEditing(e)) return
- if (e.code === 'Space' && !e.metaKey && !e.ctrlKey && !e.altKey && !e.repeat) {
+ if (
+ e.code === 'Space' &&
+ !e.metaKey &&
+ !e.ctrlKey &&
+ !e.altKey &&
+ !e.repeat &&
+ toolBeforeSpace === null
+ ) {
if (store.state.activeTool !== 'HAND') {
toolBeforeSpace = store.state.activeTool
store.setTool('HAND')
@@ -109,13 +125,12 @@ export function useKeyboard() {
})
useEventListener(window, 'keyup', (e: KeyboardEvent) => {
- if (e.code === 'Space' && toolBeforeSpace) {
+ if (e.code === 'Space' && toolBeforeSpace !== null) {
store.setTool(toolBeforeSpace)
toolBeforeSpace = null
e.preventDefault()
}
})
-
const keys = useMagicKeys({
passive: false,
onEventFired(e) {
@@ -124,8 +139,12 @@ export function useKeyboard() {
if (store.state.editingTextId) return
if (!e.metaKey && !e.ctrlKey && !e.altKey) {
- const tool = TOOL_SHORTCUTS[e.key.toLowerCase()]
+ // Space is handled by hold-to-pan above
+ if (e.code === 'Space') return
+ const tool = TOOL_SHORTCUTS[e.code]
if (tool) {
+ // Permanent tool switch cancels space-hold
+ toolBeforeSpace = null
store.setTool(tool)
return
}
@@ -214,28 +233,61 @@ export function useKeyboard() {
)
// --- Plain keys (no modifiers) ---
- function plain(key: string): ComputedRef<boolean> {
+ function plain(key: string, options?: { allowAlt?: boolean }): ComputedRef<boolean> {
+ const allowAlt = options?.allowAlt ?? false
return computed(
() =>
keys[key].value &&
!keys['meta'].value &&
!keys['control'].value &&
!keys['shift'].value &&
- !keys['alt'].value &&
+ (allowAlt || !keys['alt'].value) &&
!store.state.editingTextId
)
}
- whenever(plain('bracketright'), () => runCommand('selection.bringToFront'))
- whenever(plain('bracketleft'), () => runCommand('selection.sendToBack'))
- whenever(plain('backspace'), () => runCommand('selection.delete'))
- whenever(plain('delete'), () => runCommand('selection.delete'))
+ whenever(plain('bracketright'), () => store.bringToFront())
+ whenever(plain('bracketleft'), () => store.sendToBack())
+ whenever(plain('backspace'), () => {
+ if (
+ store.state.nodeEditState &&
+ (store.state.nodeEditState.selectedVertexIndices.size > 0 ||
+ store.state.nodeEditState.selectedHandles.size > 0)
+ ) {
+ nodeEditStore.nodeEditDeleteSelected()
+ return
+ }
+ runCommand('selection.delete')
+ })
+ whenever(plain('delete', { allowAlt: true }), () => {
+ if (
+ store.state.nodeEditState &&
+ (store.state.nodeEditState.selectedVertexIndices.size > 0 ||
+ store.state.nodeEditState.selectedHandles.size > 0)
+ ) {
+ if (keys['alt'].value) {
+ nodeEditStore.nodeEditBreakAtVertex()
+ } else {
+ nodeEditStore.nodeEditDeleteSelected()
+ }
+ return
+ }
+ runCommand('selection.delete')
+ })
whenever(plain('enter'), () => {
+ if (store.state.nodeEditState) {
+ nodeEditStore.exitNodeEditMode(true)
+ return
+ }
if (store.state.penState) store.penCommit(false)
})
whenever(plain('escape'), () => {
+ if (store.state.nodeEditState) {
+ nodeEditStore.exitNodeEditMode(true)
+ return
+ }
if (store.state.penState) {
- store.penCancel()
+ store.penCommit(false)
return
}
if (store.state.enteredContainerId) {
diff --git a/src/stores/editor.ts b/src/stores/editor.ts
index 0ffdd5bc2..adf5f6802 100644
--- a/src/stores/editor.ts
+++ b/src/stores/editor.ts
@@ -5,16 +5,38 @@ import { IS_TAURI } from '@/constants'
import { loadFont } from '@/engine/fonts'
import { toast } from '@/utils/toast'
import {
+ breakAtVertex,
+ computeAccurateBounds,
createDefaultEditorState,
createEditor,
+ deleteVertex,
exportFigFile,
+ findAllHandles,
+ findOppositeHandle,
+ mirrorHandle,
+ nearestPointOnNetwork,
readFigFile,
+ removeVertex,
renderNodesToImage,
renderNodesToSVG,
- SceneGraph
+ SceneGraph,
+ splitSegmentAt,
+ prefetchFigmaSchema
} from '@open-pencil/core'
-import type { EditorState, ExportFormat, SceneNode } from '@open-pencil/core'
+import type {
+ EditorState,
+ ExportFormat,
+ Fill,
+ Rect,
+ SceneNode,
+ Vector,
+ VectorNetwork,
+ VectorRegion,
+ VectorSegment,
+ VectorVertex,
+ Tool
+} from '@open-pencil/core'
export type { Tool } from '@open-pencil/core'
export type { EditorToolDef as ToolDef } from '@open-pencil/core'
@@ -24,7 +46,18 @@ export function createEditorStore(initialGraph?: SceneGraph) {
const graph = initialGraph ?? new SceneGraph()
const state = shallowReactive<
- EditorState & {
+ Omit<EditorState, 'penState'> & {
+ penState: {
+ vertices: VectorVertex[]
+ segments: VectorSegment[]
+ dragTangent: Vector | null
+ oppositeDragTangent: Vector | null
+ closingToFirst: boolean
+ pendingClose?: boolean
+ resumingNodeId?: string
+ resumedFills?: Fill[]
+ resumedStrokes?: SceneNode['strokes']
+ } | null
showUI: boolean
activeRibbonTab: 'panels' | 'code' | 'ai'
panelMode: 'layers' | 'design'
@@ -34,6 +67,26 @@ export function createEditorStore(initialGraph?: SceneGraph) {
autosaveEnabled: boolean
cursorCanvasX: number | null
cursorCanvasY: number | null
+ nodeEditState: {
+ nodeId: string
+ origNetwork: VectorNetwork
+ origBounds: Rect
+ vertices: VectorVertex[]
+ segments: VectorSegment[]
+ regions: VectorRegion[]
+ selectedVertexIndices: Set<number>
+ draggedHandleInfo: {
+ vertexIndex: number
+ handleType: 'tangentStart' | 'tangentEnd'
+ segmentIndex: number
+ } | null
+ /** Set of selected handles as "segIdx:tangentField" strings */
+ selectedHandles: Set<string>
+ hoveredHandleInfo: {
+ segmentIndex: number
+ tangentField: 'tangentStart' | 'tangentEnd'
+ } | null
+ } | null
}
>({
...createDefaultEditorState(graph.getPages()[0].id),
@@ -45,7 +98,8 @@ export function createEditorStore(initialGraph?: SceneGraph) {
clipboardHtml: '',
autosaveEnabled: false,
cursorCanvasX: null,
- cursorCanvasY: null
+ cursorCanvasY: null,
+ nodeEditState: null
})
const editor = createEditor({ graph, state, loadFont, skipInitialGraphSetup: !!initialGraph })
@@ -79,6 +133,23 @@ export function createEditorStore(initialGraph?: SceneGraph) {
let lastWriteTime = 0
let unwatchFile: (() => void) | null = null
+ void prefetchFigmaSchema()
+
+ function downloadBlob(data: Uint8Array, filename: string, mime: string) {
+ const blob = new Blob([data.buffer as ArrayBuffer], { type: mime })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ a.style.display = 'none'
+ document.body.appendChild(a)
+ a.click()
+ setTimeout(() => {
+ document.body.removeChild(a)
+ URL.revokeObjectURL(url)
+ }, 100)
+ }
+
const AUTOSAVE_DELAY = 3000
const debouncedAutosave = useDebounceFn(async () => {
@@ -142,23 +213,606 @@ export function createEditorStore(initialGraph?: SceneGraph) {
flashRafId = requestAnimationFrame(pumpFlashes)
}
- // ─── File I/O ─────────────────────────────────────────────────
+ // ─── Tool override (commit pen on tool switch) ────────────────
- function downloadBlob(data: Uint8Array, filename: string, mime: string) {
- const blob = new Blob([data.buffer as ArrayBuffer], { type: mime })
- const url = URL.createObjectURL(blob)
- const a = document.createElement('a')
- a.href = url
- a.download = filename
- a.style.display = 'none'
- document.body.appendChild(a)
- a.click()
- setTimeout(() => {
- document.body.removeChild(a)
- URL.revokeObjectURL(url)
- }, 100)
+ function setTool(tool: Tool) {
+ // If switching away from PEN while drawing, commit the open path
+ if (state.penState && tool !== 'PEN') {
+ editor.penCommit(false)
+ }
+ state.activeTool = tool
+ }
+
+ // ─── Pen resume (vector editor) ────────────────────────────────
+
+ function penResumeOnPath(nodeId: string) {
+ const node = graph.getNode(nodeId)
+ if (node?.type !== 'VECTOR' || !node.vectorNetwork) return
+
+ const vn = node.vectorNetwork
+
+ // Convert to absolute coords
+ const absVertices: VectorVertex[] = vn.vertices.map((v) => ({
+ ...v,
+ x: v.x + node.x,
+ y: v.y + node.y
+ }))
+
+ state.penState = {
+ vertices: absVertices,
+ segments: vn.segments.map((s) => ({
+ ...s,
+ tangentStart: { ...s.tangentStart },
+ tangentEnd: { ...s.tangentEnd }
+ })),
+ dragTangent: null,
+ oppositeDragTangent: null,
+ closingToFirst: false,
+ pendingClose: false,
+ resumingNodeId: nodeId,
+ resumedFills: [...node.fills],
+ resumedStrokes: [...node.strokes]
+ }
+
+ // Remove the original node (will be recreated on commit)
+ graph.deleteNode(nodeId)
+ state.selectedIds = new Set()
+ state.activeTool = 'PEN'
+ editor.requestRender()
+ }
+
+ /** Walk a chain from `start` and return the last vertex reached. */
+ function walkChainToEnd(segments: { start: number; end: number }[], start: number): number {
+ let current = start
+ const visited = new Set<number>([start])
+ for (;;) {
+ let found = false
+ for (const seg of segments) {
+ let next = -1
+ if (seg.start === current && !visited.has(seg.end)) next = seg.end
+ else if (seg.end === current && !visited.has(seg.start)) next = seg.start
+ if (next === -1) continue
+ visited.add(next)
+ current = next
+ found = true
+ break
+ }
+ if (!found) break
+ }
+ return current
+ }
+
+ /** Walk from `start` and return ordered vertices/segments (remapped to 0-based indices). */
+ function walkChainOrdered(
+ absVertices: VectorVertex[],
+ absSegments: VectorSegment[],
+ start: number
+ ): { orderedVertices: VectorVertex[]; orderedSegments: VectorSegment[] } {
+ const orderedVertices: VectorVertex[] = []
+ const orderedSegments: VectorSegment[] = []
+ const visited = new Set<number>()
+ let current = start
+
+ orderedVertices.push(absVertices[current])
+ visited.add(current)
+
+ for (;;) {
+ let foundSeg = false
+ for (const seg of absSegments) {
+ let next = -1
+ let isForward = false
+ if (seg.start === current && !visited.has(seg.end)) {
+ next = seg.end
+ isForward = true
+ } else if (seg.end === current && !visited.has(seg.start)) {
+ next = seg.start
+ isForward = false
+ }
+ if (next === -1) continue
+
+ const fromIdx = orderedVertices.length - 1
+ orderedVertices.push(absVertices[next])
+ const toIdx = orderedVertices.length - 1
+
+ orderedSegments.push({
+ start: fromIdx,
+ end: toIdx,
+ tangentStart: isForward ? { ...seg.tangentStart } : { ...seg.tangentEnd },
+ tangentEnd: isForward ? { ...seg.tangentEnd } : { ...seg.tangentStart }
+ })
+
+ visited.add(next)
+ current = next
+ foundSeg = true
+ break
+ }
+ if (!foundSeg) break
+ }
+ return { orderedVertices, orderedSegments }
+ }
+
+ /**
+ * Resume pen drawing from an endpoint of an existing VECTOR node.
+ * Reorders vertices/segments so the endpoint is the last vertex,
+ * then sets up penState for continuing the drawing.
+ */
+ function penResumeFromEndpoint(nodeId: string, endpointVertexIndex: number) {
+ const node = graph.getNode(nodeId)
+ if (node?.type !== 'VECTOR' || !node.vectorNetwork) return
+
+ const vn = node.vectorNetwork
+
+ // Convert to absolute coords
+ const absVertices: VectorVertex[] = vn.vertices.map((v) => ({
+ ...v,
+ x: v.x + node.x,
+ y: v.y + node.y
+ }))
+ const absSegments: VectorSegment[] = vn.segments.map((s) => ({
+ ...s,
+ tangentStart: { ...s.tangentStart },
+ tangentEnd: { ...s.tangentEnd }
+ }))
+
+ // Find the OTHER endpoint, then walk from it so the clicked one ends up last.
+ const otherEnd = walkChainToEnd(absSegments, endpointVertexIndex)
+ const { orderedVertices, orderedSegments } = walkChainOrdered(
+ absVertices,
+ absSegments,
+ otherEnd
+ )
+
+ state.penState = {
+ vertices: orderedVertices,
+ segments: orderedSegments,
+ dragTangent: null,
+ oppositeDragTangent: null,
+ closingToFirst: false,
+ pendingClose: false,
+ resumingNodeId: nodeId,
+ resumedFills: [...node.fills],
+ resumedStrokes: [...node.strokes]
+ }
+
+ graph.deleteNode(nodeId)
+ state.selectedIds = new Set()
+ state.activeTool = 'PEN'
+ editor.requestRender()
+ }
+
+ // ─── Node edit mode (vector geometry) ──────────────────────────
+
+ const NODE_EDIT_HIT_THRESHOLD = 8
+
+ function getNodeEditState() {
+ return state.nodeEditState
+ }
+
+ function setNodeEditNetwork(es: NonNullable<typeof state.nodeEditState>, network: VectorNetwork) {
+ es.vertices = network.vertices.map((v) => ({ ...v }))
+ es.segments = network.segments.map((s) => ({
+ ...s,
+ tangentStart: { ...s.tangentStart },
+ tangentEnd: { ...s.tangentEnd }
+ }))
+ es.regions = network.regions.map((r) => ({
+ windingRule: r.windingRule,
+ loops: r.loops.map((l) => [...l])
+ }))
+ }
+
+ function getLiveNetwork(es: NonNullable<typeof state.nodeEditState>): VectorNetwork {
+ return {
+ vertices: es.vertices.map((v) => ({ ...v })),
+ segments: es.segments.map((s) => ({
+ ...s,
+ tangentStart: { ...s.tangentStart },
+ tangentEnd: { ...s.tangentEnd }
+ })),
+ regions: es.regions.map((r) => ({
+ windingRule: r.windingRule,
+ loops: r.loops.map((l) => [...l])
+ }))
+ }
+ }
+
+ function applyNodeEditToNode(es: NonNullable<typeof state.nodeEditState>) {
+ const node = graph.getNode(es.nodeId)
+ if (node?.type !== 'VECTOR') return
+
+ const live = getLiveNetwork(es)
+ const bounds = computeAccurateBounds(live)
+ const relativeNetwork: VectorNetwork = {
+ vertices: live.vertices.map((v) => ({
+ ...v,
+ x: v.x - bounds.x,
+ y: v.y - bounds.y
+ })),
+ segments: live.segments,
+ regions: live.regions
+ }
+
+ graph.updateNode(node.id, {
+ x: bounds.x,
+ y: bounds.y,
+ width: bounds.width,
+ height: bounds.height,
+ vectorNetwork: relativeNetwork
+ })
+ editor.requestRender()
+ }
+
+ function enterNodeEditMode(nodeId: string) {
+ const node = graph.getNode(nodeId)
+ if (node?.type !== 'VECTOR' || !node.vectorNetwork) return
+
+ const absVertices = node.vectorNetwork.vertices.map((v) => ({
+ ...v,
+ x: v.x + node.x,
+ y: v.y + node.y
+ }))
+
+ state.nodeEditState = {
+ nodeId,
+ origNetwork: structuredClone(node.vectorNetwork),
+ origBounds: { x: node.x, y: node.y, width: node.width, height: node.height },
+ vertices: absVertices,
+ segments: node.vectorNetwork.segments.map((s) => ({
+ ...s,
+ tangentStart: { ...s.tangentStart },
+ tangentEnd: { ...s.tangentEnd }
+ })),
+ regions: node.vectorNetwork.regions.map((r) => ({
+ windingRule: r.windingRule,
+ loops: r.loops.map((l) => [...l])
+ })),
+ selectedVertexIndices: new Set(),
+ draggedHandleInfo: null,
+ selectedHandles: new Set(),
+ hoveredHandleInfo: null
+ }
+
+ state.selectedIds = new Set([nodeId])
+ editor.requestRender()
+ }
+
+ function exitNodeEditMode(commit: boolean) {
+ const es = getNodeEditState()
+ if (!es) return
+
+ const node = graph.getNode(es.nodeId)
+ if (node?.type !== 'VECTOR') {
+ state.nodeEditState = null
+ editor.requestRender()
+ return
+ }
+
+ if (commit) {
+ applyNodeEditToNode(es)
+ } else {
+ graph.updateNode(es.nodeId, {
+ x: es.origBounds.x,
+ y: es.origBounds.y,
+ width: es.origBounds.width,
+ height: es.origBounds.height,
+ vectorNetwork: structuredClone(es.origNetwork)
+ })
+ editor.requestRender()
+ }
+
+ state.nodeEditState = null
+ }
+
+ function nodeEditSelectVertex(vertexIndex: number, addToSelection: boolean) {
+ const es = getNodeEditState()
+ if (!es) return
+ if (addToSelection) {
+ const next = new Set(es.selectedVertexIndices)
+ if (next.has(vertexIndex)) next.delete(vertexIndex)
+ else next.add(vertexIndex)
+ es.selectedVertexIndices = next
+ } else {
+ es.selectedVertexIndices = new Set([vertexIndex])
+ }
+ editor.requestRepaint()
+ }
+
+ type HandleInfo = {
+ segmentIndex: number
+ tangentField: 'tangentStart' | 'tangentEnd'
+ neighborIndex: number
+ }
+
+ /** Resolve the base direction vector for a handle, falling back to neighbor direction. */
+ function handleBaseVector(tangent: Vector, neighbor: Vector, origin: Vector): Vector {
+ return Math.hypot(tangent.x, tangent.y) > 1e-6
+ ? tangent
+ : { x: neighbor.x - origin.x, y: neighbor.y - origin.y }
+ }
+
+ /** Among sibling handles, find the one most opposite to the active handle direction. */
+ function findSisterHandle(
+ es: NonNullable<typeof state.nodeEditState>,
+ siblings: HandleInfo[],
+ activeBase: Vector,
+ vertexIndex: number
+ ): HandleInfo {
+ let sister = siblings[0]
+ const activeBaseLen = Math.hypot(activeBase.x, activeBase.y)
+ if (activeBaseLen <= 1e-6) return sister
+
+ const activeDir = { x: activeBase.x / activeBaseLen, y: activeBase.y / activeBaseLen }
+ let bestDot = Infinity
+ for (const s of siblings) {
+ const sSeg = es.segments[s.segmentIndex]
+ const sVertex = es.vertices[vertexIndex]
+ const sNeighbor = es.vertices[s.neighborIndex]
+ const sBase = handleBaseVector(sSeg[s.tangentField], sNeighbor, sVertex)
+ const sLen = Math.hypot(sBase.x, sBase.y)
+ if (sLen < 1e-6) continue
+ const sDir = { x: sBase.x / sLen, y: sBase.y / sLen }
+ const dot = activeDir.x * sDir.x + activeDir.y * sDir.y
+ if (dot < bestDot) {
+ bestDot = dot
+ sister = s
+ }
+ }
+ return sister
+ }
+
+ /** Constrain a tangent to be continuous with the sister handle. Returns the constrained vector, or null if no constraint applied. */
+ function constrainContinuousTangent(
+ es: NonNullable<typeof state.nodeEditState>,
+ newTangent: Vector,
+ active: HandleInfo,
+ all: HandleInfo[],
+ seg: VectorSegment,
+ tangentField: 'tangentStart' | 'tangentEnd',
+ vertexIndex: number,
+ vertex: VectorVertex
+ ): Vector | null {
+ const siblings = all.filter(
+ (h) => !(h.segmentIndex === active.segmentIndex && h.tangentField === active.tangentField)
+ )
+ if (siblings.length === 0) return null
+
+ const activeNeighbor = es.vertices[active.neighborIndex]
+ const activeBase = handleBaseVector(seg[tangentField], activeNeighbor, vertex)
+ const sister = findSisterHandle(es, siblings, activeBase, vertexIndex)
+
+ const sisterSeg = es.segments[sister.segmentIndex]
+ const sisterNeighbor = es.vertices[sister.neighborIndex]
+ const sisterBase = handleBaseVector(sisterSeg[sister.tangentField], sisterNeighbor, vertex)
+ const sisterLen = Math.hypot(sisterBase.x, sisterBase.y)
+ if (sisterLen <= 1e-6) return null
+
+ const desiredDir = { x: -sisterBase.x / sisterLen, y: -sisterBase.y / sisterLen }
+ const len = Math.max(0, newTangent.x * desiredDir.x + newTangent.y * desiredDir.y)
+ vertex.handleMirroring = 'ANGLE'
+ return { x: desiredDir.x * len, y: desiredDir.y * len }
+ }
+
+ function nodeEditSetHandle(
+ segmentIndex: number,
+ tangentField: 'tangentStart' | 'tangentEnd',
+ newTangent: Vector,
+ options?: {
+ breakMirroring?: boolean
+ continuous?: boolean
+ lockDirection?: boolean
+ }
+ ) {
+ const es = getNodeEditState()
+ if (!es) return
+ const seg = es.segments[segmentIndex]
+
+ const breakMirroring = options?.breakMirroring ?? false
+ const continuous = options?.continuous ?? false
+ const lockDirection = options?.lockDirection ?? false
+ const vertexIndex = tangentField === 'tangentStart' ? seg.start : seg.end
+ const vertex = es.vertices[vertexIndex]
+ const live = getLiveNetwork(es)
+
+ const all = findAllHandles(live, vertexIndex)
+ const active = all.find(
+ (h) => h.segmentIndex === segmentIndex && h.tangentField === tangentField
+ )
+
+ let applied = { x: newTangent.x, y: newTangent.y }
+ if (continuous && active) {
+ applied =
+ constrainContinuousTangent(
+ es,
+ newTangent,
+ active,
+ all,
+ seg,
+ tangentField,
+ vertexIndex,
+ vertex
+ ) ?? applied
+ }
+
+ seg[tangentField] = applied
+ const mode = vertex.handleMirroring ?? 'NONE'
+ if (lockDirection && mode === 'NONE') {
+ seg[tangentField] = { x: newTangent.x, y: newTangent.y }
+ editor.requestRepaint()
+ return
+ }
+ if (breakMirroring) {
+ vertex.handleMirroring = 'NONE'
+ editor.requestRepaint()
+ return
+ }
+ if (mode === 'NONE') {
+ editor.requestRepaint()
+ return
+ }
+
+ const opposite = findOppositeHandle(live, vertexIndex, segmentIndex)
+ if (!opposite) {
+ editor.requestRepaint()
+ return
+ }
+
+ const oppositeSeg = es.segments[opposite.segmentIndex]
+ const oppositeCurrent = oppositeSeg[opposite.tangentField]
+ const oppositeLength =
+ mode === 'ANGLE' ? Math.hypot(oppositeCurrent.x, oppositeCurrent.y) : undefined
+ const mirrored = mirrorHandle(applied, mode, oppositeLength)
+ if (mirrored) {
+ oppositeSeg[opposite.tangentField] = mirrored
+ }
+ editor.requestRepaint()
+ }
+
+ function nodeEditBendHandle(
+ vertexIndex: number,
+ dx: number,
+ dy: number,
+ independent: boolean,
+ targetSegmentIndex: number | null,
+ targetTangentField: 'tangentStart' | 'tangentEnd' | null
+ ) {
+ const es = getNodeEditState()
+ if (!es) return
+ if (targetSegmentIndex == null || targetTangentField == null) return
+ const live = getLiveNetwork(es)
+ const handles = findAllHandles(live, vertexIndex)
+ if (handles.length === 0) return
+
+ const effectiveTargets = handles.filter(
+ (h) => h.segmentIndex === targetSegmentIndex && h.tangentField === targetTangentField
+ )
+ if (effectiveTargets.length === 0) return
+
+ const primary = { x: dx, y: dy }
+ const opposite = independent ? { x: dx, y: dy } : { x: -dx, y: -dy }
+
+ const first = effectiveTargets[0]
+ es.segments[first.segmentIndex][first.tangentField] = primary
+ for (let i = 1; i < effectiveTargets.length; i++) {
+ const h = effectiveTargets[i]
+ es.segments[h.segmentIndex][h.tangentField] = primary
+ }
+ if (!independent) {
+ for (const h of handles) {
+ if (effectiveTargets.includes(h)) continue
+ es.segments[h.segmentIndex][h.tangentField] = opposite
+ }
+ }
+
+ es.vertices[vertexIndex].handleMirroring = independent ? 'NONE' : 'ANGLE_AND_LENGTH'
+ editor.requestRepaint()
+ }
+
+ function nodeEditZeroVertexHandles(vertexIndex: number) {
+ const es = getNodeEditState()
+ if (!es) return
+ const live = getLiveNetwork(es)
+ const handles = findAllHandles(live, vertexIndex)
+ for (const h of handles) {
+ es.segments[h.segmentIndex][h.tangentField] = { x: 0, y: 0 }
+ }
+ es.vertices[vertexIndex].handleMirroring = 'NONE'
+ editor.requestRepaint()
}
+ function nodeEditConnectEndpoints(a: number, b: number) {
+ const es = getNodeEditState()
+ if (!es || a === b) return
+ if (a < 0 || b < 0 || a >= es.vertices.length || b >= es.vertices.length) return
+
+ const removeIndex = a
+ const keepIndex = b
+ const remap = (idx: number): number => {
+ if (idx === removeIndex) return keepIndex
+ return idx > removeIndex ? idx - 1 : idx
+ }
+
+ const nextVertices = es.vertices.filter((_, idx) => idx !== removeIndex)
+ const nextSegments = es.segments
+ .map((seg) => ({
+ ...seg,
+ tangentStart: { ...seg.tangentStart },
+ tangentEnd: { ...seg.tangentEnd },
+ start: remap(seg.start),
+ end: remap(seg.end)
+ }))
+ .filter((seg) => seg.start !== seg.end)
+
+ setNodeEditNetwork(es, { vertices: nextVertices, segments: nextSegments, regions: [] })
+ es.selectedVertexIndices = new Set([remap(keepIndex)])
+ es.selectedHandles = new Set()
+ editor.requestRender()
+ }
+
+ function nodeEditAddVertex(cx: number, cy: number) {
+ const es = getNodeEditState()
+ if (!es) return
+ const live = getLiveNetwork(es)
+ const nearest = nearestPointOnNetwork(cx, cy, live, NODE_EDIT_HIT_THRESHOLD / state.zoom)
+ if (!nearest) return
+ const split = splitSegmentAt(live, nearest.segmentIndex, nearest.t)
+ setNodeEditNetwork(es, split.network)
+ es.selectedVertexIndices = new Set([split.newVertexIndex])
+ es.selectedHandles = new Set()
+ editor.requestRender()
+ }
+
+ function nodeEditRemoveVertex(vertexIndex: number) {
+ const es = getNodeEditState()
+ if (!es) return
+ const live = getLiveNetwork(es)
+ const next = removeVertex(live, vertexIndex)
+ if (!next) return
+ setNodeEditNetwork(es, next)
+ es.selectedVertexIndices = new Set()
+ es.selectedHandles = new Set()
+ editor.requestRender()
+ }
+
+ function nodeEditDeleteSelected() {
+ const es = getNodeEditState()
+ if (!es) return
+ let live = getLiveNetwork(es)
+
+ for (const key of es.selectedHandles) {
+ const [siStr, tf] = key.split(':')
+ const si = Number(siStr)
+ const seg = live.segments[si]
+ if (tf === 'tangentStart') seg.tangentStart = { x: 0, y: 0 }
+ else seg.tangentEnd = { x: 0, y: 0 }
+ }
+
+ const verticesToDelete = [...es.selectedVertexIndices].sort((a, b) => b - a)
+ for (const vi of verticesToDelete) {
+ const next = deleteVertex(live, vi)
+ if (!next) break
+ live = next
+ }
+
+ setNodeEditNetwork(es, live)
+ es.selectedVertexIndices = new Set()
+ es.selectedHandles = new Set()
+ editor.requestRender()
+ }
+
+ function nodeEditBreakAtVertex() {
+ const es = getNodeEditState()
+ if (!es || es.selectedVertexIndices.size === 0) return
+ const [vertexIndex] = es.selectedVertexIndices
+ const live = getLiveNetwork(es)
+ const next = breakAtVertex(live, vertexIndex)
+ setNodeEditNetwork(es, next)
+ es.selectedHandles = new Set()
+ es.selectedVertexIndices = new Set([vertexIndex])
+ editor.requestRender()
+ }
+
+ // ─── File I/O ──────────────────────────────────────────────────
+
function yieldToUI(): Promise<void> {
return new Promise((r) => requestAnimationFrame(() => r()))
}
@@ -502,13 +1156,26 @@ export function createEditorStore(initialGraph?: SceneGraph) {
selectedNode,
layerTree,
- // App-specific methods
+ // App-specific overrides and additions
flashNodes,
aiMarkActive,
aiMarkDone,
aiFlashDone,
aiClearAll,
- toggleProfiler,
+ setTool,
+ penResumeOnPath,
+ penResumeFromEndpoint,
+ enterNodeEditMode,
+ exitNodeEditMode,
+ nodeEditSelectVertex,
+ nodeEditSetHandle,
+ nodeEditBendHandle,
+ nodeEditZeroVertexHandles,
+ nodeEditConnectEndpoints,
+ nodeEditAddVertex,
+ nodeEditRemoveVertex,
+ nodeEditDeleteSelected,
+ nodeEditBreakAtVertex,
openFigFile,
saveFigFile,
saveFigFileAs,
@@ -516,7 +1183,8 @@ export function createEditorStore(initialGraph?: SceneGraph) {
exportSelection,
mobileCopy,
mobileCut,
- mobilePaste
+ mobilePaste,
+ toggleProfiler
}
Object.defineProperties(store, {
diff --git a/tests/engine/vector.test.ts b/tests/engine/vector.test.ts
index feb4b9081..48ee4000e 100644
--- a/tests/engine/vector.test.ts
+++ b/tests/engine/vector.test.ts
@@ -158,7 +158,7 @@ describe('computeVectorBounds', () => {
expect(bounds).toEqual({ x: 0, y: 0, width: 100, height: 50 })
})
- test('bezier control points extend bounds', () => {
+ test('bezier curve extrema extend bounds', () => {
const bounds = computeVectorBounds({
vertices: [
{ x: 0, y: 0, handleMirroring: 'NONE' },
@@ -169,7 +169,8 @@ describe('computeVectorBounds', () => {
],
regions: []
})
- expect(bounds.y).toBe(-50)
- expect(bounds.height).toBe(100)
+ // Curve extrema at t=(3±√3)/6, not at control points
+ expect(bounds.y).toBeCloseTo(-14.4338, 3)
+ expect(bounds.height).toBeCloseTo(28.8675, 3)
})
})