Skip to content

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

fix: continue a pen path in the layer it came from (#1149)

rcoenen8346d799f3d6
diff --git a/changes/1149/added.md b/changes/1149/added.md
new file mode 100644
index 000000000..004e45761
--- /dev/null
+++ b/changes/1149/added.md
@@ -0,0 +1 @@
+- The pen lines each new point up with the path's own points, as in Figma: within 4 pixels it snaps to their x or y and draws a red guide with a cross on every point it passes through, a point it would land on shows a cross inside its circle, and the point the next segment starts from is solid, with a blue segment to the cursor. In vector edit mode, a pen click away from the path starts a new piece of the same layer there.
diff --git a/changes/1149/fixed.md b/changes/1149/fixed.md
new file mode 100644
index 000000000..cfc15354f
--- /dev/null
+++ b/changes/1149/fixed.md
@@ -0,0 +1 @@
+- Continuing a vector's path with the pen grows that same layer, which keeps its name, position, parent and style. Undo returns it to its earlier path, where before the original was deleted and a new layer was made.
diff --git a/packages/core/src/canvas/overlays/feedback.ts b/packages/core/src/canvas/overlays/feedback.ts
index 490873ff0..597725b5d 100644
--- a/packages/core/src/canvas/overlays/feedback.ts
+++ b/packages/core/src/canvas/overlays/feedback.ts
@@ -14,7 +14,10 @@ import {
FLASH_OVERSHOOT,
FLASH_RELEASE_MS,
LAYOUT_INDICATOR_STROKE,
- MARQUEE_FILL_ALPHA
+ MARQUEE_FILL_ALPHA,
+ VERTEX_SNAP_COLOR,
+ VERTEX_SNAP_GUIDE_ALPHA,
+ VERTEX_SNAP_MARK_RADIUS
} from '#core/constants'
import { createSceneGeometry, type RotationPreview } from '#core/geometry'
@@ -24,20 +27,48 @@ export function drawSnapGuides(r: SkiaRenderer, canvas: Canvas, guides?: SnapGui
if (!guides || guides.length === 0) return
for (const guide of guides) {
+ const paint = guide.marks ? vertexSnapPaint(r, VERTEX_SNAP_GUIDE_ALPHA) : r.snapPaint
if (guide.axis === 'x') {
const x = guide.position * r.zoom + r.panX
const y1 = guide.from * r.zoom + r.panY
const y2 = guide.to * r.zoom + r.panY
- canvas.drawLine(x, y1, x, y2, r.snapPaint)
+ canvas.drawLine(x, y1, x, y2, paint)
} else {
const y = guide.position * r.zoom + r.panY
const x1 = guide.from * r.zoom + r.panX
const x2 = guide.to * r.zoom + r.panX
- canvas.drawLine(x1, y, x2, y, r.snapPaint)
+ canvas.drawLine(x1, y, x2, y, paint)
}
}
}
+/**
+ * The crosses on the vertices a guide lines up, drawn over the path's points as Figma does, so a
+ * point the pen would land on shows its cross inside its circle.
+ */
+export function drawSnapMarks(r: SkiaRenderer, canvas: Canvas, guides?: SnapGuide[]): void {
+ if (!guides) return
+ const paint = vertexSnapPaint(r, 1)
+ const arm = VERTEX_SNAP_MARK_RADIUS
+ for (const guide of guides) {
+ for (const mark of guide.marks ?? []) {
+ const along = guide.axis === 'x' ? guide.position : mark
+ const across = guide.axis === 'x' ? mark : guide.position
+ const x = along * r.zoom + r.panX
+ const y = across * r.zoom + r.panY
+ canvas.drawLine(x - arm, y - arm, x + arm, y + arm, paint)
+ canvas.drawLine(x - arm, y + arm, x + arm, y - arm, paint)
+ }
+ }
+}
+
+function vertexSnapPaint(r: SkiaRenderer, alpha: number) {
+ const { r: red, g, b } = VERTEX_SNAP_COLOR
+ r.auxStroke.setStrokeWidth(1)
+ r.auxStroke.setColor(r.ck.Color4f(red, g, b, alpha))
+ return r.auxStroke
+}
+
export function drawMarquee(r: SkiaRenderer, canvas: Canvas, marquee?: Rect | null): void {
if (!marquee || marquee.width <= 0 || marquee.height <= 0) return
diff --git a/packages/core/src/canvas/overlays/index.ts b/packages/core/src/canvas/overlays/index.ts
index b344ee4b8..627925621 100644
--- a/packages/core/src/canvas/overlays/index.ts
+++ b/packages/core/src/canvas/overlays/index.ts
@@ -10,7 +10,13 @@ export {
getRotatedCorners
} from './selection'
export { drawAutoLayoutHover } from './auto-layout-hover'
-export { drawFlashes, drawLayoutInsertIndicator, drawMarquee, drawSnapGuides } from './feedback'
+export {
+ drawFlashes,
+ drawLayoutInsertIndicator,
+ drawMarquee,
+ drawSnapGuides,
+ drawSnapMarks
+} from './feedback'
export { drawMeasurements } from './measurement'
export { drawTextEditOverlay } from './text-edit'
export { drawSelectionLabels } from '#core/canvas/labels/selection'
diff --git a/packages/core/src/canvas/pen-overlay.ts b/packages/core/src/canvas/pen-overlay.ts
index 6c1851748..932f8ba17 100644
--- a/packages/core/src/canvas/pen-overlay.ts
+++ b/packages/core/src/canvas/pen-overlay.ts
@@ -2,7 +2,12 @@ import type { Canvas, Paint } from 'canvaskit-wasm'
import type { Vector } from '@open-pencil/scene-graph/primitives'
-import { PEN_HANDLE_RADIUS, PEN_VERTEX_RADIUS, PEN_CLOSE_RADIUS_BOOST } from '#core/constants'
+import {
+ PEN_ANCHOR_RADIUS,
+ PEN_CLOSE_RADIUS_BOOST,
+ PEN_HANDLE_RADIUS,
+ PEN_VERTEX_RADIUS
+} from '#core/constants'
import type { SkiaRenderer, RenderOverlays } from './renderer'
@@ -99,10 +104,10 @@ function drawPenPaths(
canvas.drawPath(segPath, r.penPathPaint)
segPath.delete()
- // 3) Draw cursor preview line with tech outline only
+ // 3) Draw the segment to the cursor in the selection color, as Figma previews the next segment
const cursorPath = buildCursorPath(r, penState, toScreen)
if (cursorPath) {
- canvas.drawPath(cursorPath, r.penPathPaint)
+ canvas.drawPath(cursorPath, r.penVertexStroke)
cursorPath.delete()
}
}
@@ -200,8 +205,15 @@ export function drawPenOverlay(
drawPenPaths(r, canvas, penState, toScreen)
drawPenTangentHandles(canvas, penState, toScreen, r.penHandlePaint, vertexFill)
+ // The point the next segment starts from is solid, as in Figma; the others stay hollow.
+ const anchor = penState.pendingClose ? -1 : vertices.length - 1
for (let i = 0; i < vertices.length; i++) {
const v = toScreen(vertices[i].x, vertices[i].y)
+ if (i === anchor) {
+ r.auxFill.setColor(r.selColor())
+ canvas.drawCircle(v.x, v.y, PEN_ANCHOR_RADIUS, r.auxFill)
+ continue
+ }
const radius =
i === 0 && penState.closingToFirst
? PEN_VERTEX_RADIUS + PEN_CLOSE_RADIUS_BOOST
@@ -209,4 +221,11 @@ export function drawPenOverlay(
canvas.drawCircle(v.x, v.y, radius, vertexFill)
canvas.drawCircle(v.x, v.y, radius, vertexStroke)
}
+
+ // Where the next click puts a point; a snapped cursor shows its cross inside this ring.
+ const { cursorX, cursorY } = penState
+ if (cursorX != null && cursorY != null && !penState.pendingClose && !penState.closingToFirst) {
+ const cursor = toScreen(cursorX, cursorY)
+ canvas.drawCircle(cursor.x, cursor.y, PEN_VERTEX_RADIUS, vertexStroke)
+ }
}
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 07467c2fc..749ec1a0d 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -302,6 +302,7 @@ export class SkiaRenderer {
declare getRotatedCorners: (node: SceneNode, abs: Vector) => Vector[]
declare drawHandle: (canvas: Canvas, x: number, y: number) => void
declare drawSnapGuides: (canvas: Canvas, guides?: SnapGuide[]) => void
+ declare drawSnapMarks: (canvas: Canvas, guides?: SnapGuide[]) => void
declare drawMarquee: (canvas: Canvas, marquee?: Rect | null) => void
declare drawFlashes: (canvas: Canvas, graph: SceneGraph) => void
declare drawLayoutInsertIndicator: (
diff --git a/packages/core/src/canvas/renderer/methods.ts b/packages/core/src/canvas/renderer/methods.ts
index 6c73cd199..7e9c5d303 100644
--- a/packages/core/src/canvas/renderer/methods.ts
+++ b/packages/core/src/canvas/renderer/methods.ts
@@ -117,6 +117,10 @@ const rendererMethods: ThisType<SkiaRenderer> = {
Overlays.drawSnapGuides(this, canvas, guides)
},
+ drawSnapMarks(canvas: Canvas, guides?: SnapGuide[]): void {
+ Overlays.drawSnapMarks(this, canvas, guides)
+ },
+
drawMarquee(canvas: Canvas, marquee?: Rect | null): void {
Overlays.drawMarquee(this, canvas, marquee)
},
diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.ts
index 82b7c76da..db634c9de 100644
--- a/packages/core/src/canvas/renderer/overlay-pass.ts
+++ b/packages/core/src/canvas/renderer/overlay-pass.ts
@@ -146,6 +146,7 @@ export function drawOverlayPass(
r.drawNodeEditOverlay(canvas, graph, overlays.nodeEditState)
r.drawPenOverlay(canvas, overlays.penState)
r.drawPencilOverlay(canvas, overlays.pencilState)
+ r.drawSnapMarks(canvas, overlays.snapGuides)
updateIssueMarkers(r, graph, overlays)
drawIssueMarkers(r, canvas, r.issueMarkers, overlays.designIssues?.hoveredMarkerKey)
r.drawPresenceCursors(canvas, graph, overlays.presenceCursors)
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 27f982966..e1d3180a8 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -21,6 +21,10 @@ export const COMPONENT_COLOR = { r: 0.592, g: 0.278, b: 1, a: 1 } satisfies Colo
export const SLOT_COLOR = { r: 0.949, g: 0.294, b: 0.737, a: 1 } satisfies Color
export const SLOT_EMPTY_FILL_ALPHA = 0.08
export const SNAP_COLOR = { r: 1.0, g: 0.0, b: 0.56, a: 1 } satisfies Color
+/** Guides through path vertices and their crosses, measured from Figma's pen and vector edit mode. */
+export const VERTEX_SNAP_COLOR = { r: 0.81, g: 0.3, b: 0.18, a: 1 } satisfies Color
+export const VERTEX_SNAP_GUIDE_ALPHA = 0.6
+export const VERTEX_SNAP_MARK_RADIUS = 2.5
export const MEASUREMENT_COLOR = { r: 0.949, g: 0.282, b: 0.133, a: 1 } satisfies Color
export const MEASUREMENT_PILL_PADDING_X = 5
export const MEASUREMENT_PILL_HEIGHT = 18
@@ -44,6 +48,7 @@ export const RULER_HIGHLIGHT_ALPHA = 0.3
export const PEN_HANDLE_RADIUS = 2.5
export const PEN_VERTEX_RADIUS = 3
+export const PEN_ANCHOR_RADIUS = 4
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/create.ts b/packages/core/src/editor/create.ts
index 1894490ce..233561339 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -202,7 +202,10 @@ export function createEditor(options?: EditorOptions) {
const previous = state.activeTool
state.activeTool = tool
if (tool !== 'SELECT') state.measurementMode = 'off'
- if (previous !== tool) emitEditorEvent('tool:changed', tool, previous)
+ if (previous === tool) return
+ // Guides the pen showed for its next point do not belong to the next tool.
+ if (previous === 'PEN') state.snapGuides = []
+ emitEditorEvent('tool:changed', tool, previous)
}
const graphReads = createGraphReadActions(() => _graph)
@@ -273,7 +276,6 @@ export function createEditor(options?: EditorOptions) {
const pages = createPageActions(ctx, shaderFrames)
const guides = createGuideActions(ctx)
const designIssues = createDesignIssueActions(ctx)
- const shapes = createShapeActions(ctx)
const structure = createStructureActions(ctx)
const components = createComponentActions(ctx)
const clipboard = createClipboardActions(ctx)
@@ -281,6 +283,7 @@ export function createEditor(options?: EditorOptions) {
const undoActions = createUndoActions(ctx)
const text = createTextActions(ctx)
const nodes = createNodeActions(ctx)
+ const shapes = createShapeActions(ctx, nodes.updateNodeWithUndo)
const clipboardProperties = createClipboardPropertiesActions(
ctx,
nodes.updateNodeWithUndo,
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index a1a2672cc..cc27e4300 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -62,6 +62,7 @@ export type {
EditorSharedState,
EditorViewState,
FigmaClipboardImageResolver,
+ ResumedPath,
ShapeHandleHover,
GradientEdit,
Tool
diff --git a/packages/core/src/editor/shapes.ts b/packages/core/src/editor/shapes.ts
index 28ffed515..145a519ae 100644
--- a/packages/core/src/editor/shapes.ts
+++ b/packages/core/src/editor/shapes.ts
@@ -4,7 +4,7 @@ import { prepareSlotEdits } from './components/slots'
import { adoptCoveredLayers } from './shapes/adopt'
import { newLayerDefaults } from './shapes/defaults'
import { createFramePresetActions } from './shapes/frame-presets'
-import { createPenActions } from './shapes/pen'
+import { createPenActions, type UpdateNodeWithUndo } from './shapes/pen'
import { createPencilActions } from './shapes/pencil'
import { defaultNodeName, nextNumberedName } from './structure/rename'
import type { EditorContext } from './types'
@@ -21,7 +21,7 @@ const NUMBERED_WHEN_DRAWN: ReadonlySet<NodeType> = new Set([
'STAR'
])
-export function createShapeActions(ctx: EditorContext) {
+export function createShapeActions(ctx: EditorContext, updateNodeWithUndo: UpdateNodeWithUndo) {
function drawnLayerName(type: NodeType, parentId: string): string {
const base = defaultNodeName(type)
return NUMBERED_WHEN_DRAWN.has(type) ? nextNumberedName(ctx.graph, parentId, base) : base
@@ -71,7 +71,7 @@ export function createShapeActions(ctx: EditorContext) {
return id
}
- const penActions = createPenActions(ctx, createShape)
+ const penActions = createPenActions(ctx, createShape, updateNodeWithUndo)
const pencilActions = createPencilActions(ctx, createShape)
const framePresetActions = createFramePresetActions(ctx, createShape)
diff --git a/packages/core/src/editor/shapes/pen.ts b/packages/core/src/editor/shapes/pen.ts
index c37296576..076e80484 100644
--- a/packages/core/src/editor/shapes/pen.ts
+++ b/packages/core/src/editor/shapes/pen.ts
@@ -1,9 +1,17 @@
-import type { SceneNode, VectorRegion, VectorSegment } from '@open-pencil/scene-graph'
+import {
+ cloneVectorNetwork,
+ type SceneNode,
+ type VectorNetwork,
+ type VectorRegion,
+ type VectorSegment,
+ type VectorVertex
+} from '@open-pencil/scene-graph'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import { BLACK } from '#core/constants'
import { createVectorFromNetwork, type CreateShape } from '#core/editor/shapes/vector'
-import type { EditorContext } from '#core/editor/types'
+import type { EditorContext, ResumedPath } from '#core/editor/types'
+import { vectorChangesFromPagePath } from '#core/vector'
export interface PenDragOptions {
keepOpposite?: boolean
@@ -11,6 +19,8 @@ export interface PenDragOptions {
oppositeTangent?: Vector | null
}
+export type UpdateNodeWithUndo = (id: string, changes: Partial<SceneNode>, label?: string) => void
+
const PEN_DEFAULT_STROKE: SceneNode['strokes'][number] = {
type: 'SOLID',
color: BLACK,
@@ -46,7 +56,53 @@ function applyAnchorTangent(
}
}
-export function createPenActions(ctx: EditorContext, createShape: CreateShape) {
+/**
+ * The network a continued path commits: the one it came from, with the pen's chain written back
+ * over the part it walked and the new points and segments added, so branches the pen didn't walk
+ * stay as they were. A closed chain becomes a new region.
+ */
+function continuedNetwork(
+ resumed: ResumedPath,
+ vertices: VectorVertex[],
+ segments: VectorSegment[],
+ closed: boolean
+): VectorNetwork {
+ const network = cloneVectorNetwork(resumed.network)
+ const vertexIndex = vertices.map((vertex, i) => {
+ const index = resumed.vertices.at(i)
+ if (index === undefined) return network.vertices.push({ ...vertex }) - 1
+ network.vertices[index] = { ...vertex }
+ return index
+ })
+ const segmentIndex = segments.map((segment, i) => {
+ const walked = resumed.segments.at(i)
+ if (!walked) {
+ return (
+ network.segments.push({
+ start: vertexIndex[segment.start],
+ end: vertexIndex[segment.end],
+ tangentStart: { ...segment.tangentStart },
+ tangentEnd: { ...segment.tangentEnd }
+ }) - 1
+ )
+ }
+ const target = network.segments[walked.index]
+ const [tangentStart, tangentEnd] = walked.reversed
+ ? [segment.tangentEnd, segment.tangentStart]
+ : [segment.tangentStart, segment.tangentEnd]
+ target.tangentStart = { ...tangentStart }
+ target.tangentEnd = { ...tangentEnd }
+ return walked.index
+ })
+ if (closed) network.regions.push({ windingRule: 'NONZERO', loops: [segmentIndex] })
+ return network
+}
+
+export function createPenActions(
+ ctx: EditorContext,
+ createShape: CreateShape,
+ updateNodeWithUndo: UpdateNodeWithUndo
+) {
function penAddVertex(x: number, y: number) {
if (!ctx.state.penState) {
ctx.state.penState = {
@@ -159,6 +215,15 @@ export function createPenActions(ctx: EditorContext, createShape: CreateShape) {
? [{ windingRule: 'NONZERO', loops: [ps.segments.map((_, i) => i)] }]
: []
+ const resumed = ps.resumingNodeId ? ctx.graph.getNode(ps.resumingNodeId) : undefined
+ const network: VectorNetwork = ps.resumedPath
+ ? continuedNetwork(ps.resumedPath, ps.vertices, ps.segments, closed)
+ : { vertices: ps.vertices, segments: ps.segments, regions }
+ if (resumed?.type === 'VECTOR' && commitIntoLayer(resumed, network)) {
+ finishPath()
+ return
+ }
+
const fills = ps.resumedFills ? ps.resumedFills.map((f) => ({ ...f })) : []
const strokes = ps.resumedStrokes
? ps.resumedStrokes.map((s) => ({ ...s }))
@@ -171,7 +236,32 @@ export function createPenActions(ctx: EditorContext, createShape: CreateShape) {
{ name: 'Vector', fills, strokes }
)
ctx.setSelectedIds(new Set([nodeId]))
+ finishPath()
+ }
+
+ /**
+ * Gives the layer a continued path came from its new points, as Figma does, rather than making
+ * another layer: the layer keeps its name, place and style, and one undo puts its path back.
+ */
+ function commitIntoLayer(node: SceneNode, network: VectorNetwork): boolean {
+ // The pen only adds points and segments to a continued path, so equal counts mean nothing
+ // was drawn: the layer stays as it was, with no undo step.
+ const before = node.vectorNetwork
+ const unchanged =
+ before &&
+ before.vertices.length === network.vertices.length &&
+ before.segments.length === network.segments.length &&
+ before.regions.length === network.regions.length
+ if (!unchanged) {
+ const changes = vectorChangesFromPagePath(ctx.graph, node, network)
+ if (!changes) return false
+ updateNodeWithUndo(node.id, changes, 'Edit vector')
+ }
+ ctx.setSelectedIds(new Set([node.id]))
+ return true
+ }
+ function finishPath() {
ctx.state.penState = null
ctx.state.penCursorX = null
ctx.state.penCursorY = null
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 81440a94e..fa47716b9 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -5,6 +5,7 @@ import type {
SceneGraph,
SceneGraphEvents,
SceneNode,
+ VectorNetwork,
VectorSegment,
VectorVertex
} from '@open-pencil/scene-graph'
@@ -101,6 +102,18 @@ export interface EditorSharedState {
canvasVersion: number
}
+/**
+ * The path a pen continues, in page coordinates, and where the pen's chain sits in it. The pen
+ * walks one chain out of the network; committing writes the chain back and keeps the rest.
+ */
+export interface ResumedPath {
+ network: VectorNetwork
+ /** Each chain vertex's index in `network`. */
+ vertices: number[]
+ /** Each chain segment's index in `network`, and whether the chain runs it from end to start. */
+ segments: Array<{ index: number; reversed: boolean }>
+}
+
export interface PencilState {
points: Vector[]
/** The point Shift was pressed at; the stroke runs straight from it while Shift is held. */
@@ -138,6 +151,7 @@ export interface EditorViewState {
pendingClose?: boolean
closingToFirst: boolean
resumingNodeId?: string
+ resumedPath?: ResumedPath
resumedFills?: SceneNode['fills']
resumedStrokes?: SceneNode['strokes']
} | null
diff --git a/packages/core/src/vector/index.ts b/packages/core/src/vector/index.ts
index af86a8018..2cdb85b55 100644
--- a/packages/core/src/vector/index.ts
+++ b/packages/core/src/vector/index.ts
@@ -27,6 +27,7 @@ import { addLoopToPath, addOpenSegmentsToPath } from './path-helpers'
export { vectorNetworkToCenterlinePath, fitCircleArc, isClosedThinCrescent } from './centerline'
export { regenerateFillGeometry } from './fill-geometry'
export { addStrokeRunToPath, strokeRuns, type StrokeRun } from './path-helpers'
+export { vectorChangesFromPagePath, type VectorPathChanges } from './placement'
/**
* Fill types go on the detached `Path`: CanvasKit 0.41's `PathBuilder.setFillType` returns an
diff --git a/packages/core/src/vector/placement.ts b/packages/core/src/vector/placement.ts
new file mode 100644
index 000000000..f70654a96
--- /dev/null
+++ b/packages/core/src/vector/placement.ts
@@ -0,0 +1,55 @@
+import {
+ transformVectorNetwork,
+ type SceneGraph,
+ type SceneNode,
+ type VectorNetwork
+} from '@open-pencil/scene-graph'
+import { getNodeLocalMatrix, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import Matrix from '@open-pencil/scene-graph/matrix'
+
+import { computeAccurateBounds } from './curve-math'
+import { regenerateFillGeometry } from './fill-geometry'
+
+export type VectorPathChanges = Pick<
+ SceneNode,
+ 'x' | 'y' | 'width' | 'height' | 'vectorNetwork' | 'fillGeometry' | 'strokeGeometry'
+>
+
+/**
+ * What gives a vector layer a path drawn in page coordinates while keeping its rotation and flips:
+ * the path moves into the layer's own frame, the layer's box fits it, and the fill geometry
+ * follows. Null when the layer's transform cannot be inverted.
+ */
+export function vectorChangesFromPagePath(
+ graph: SceneGraph,
+ node: SceneNode,
+ pagePath: VectorNetwork
+): VectorPathChanges | null {
+ const inverse = Matrix.invert(getWorldMatrix(node, graph))
+ if (!inverse) return null
+ const localNetwork = transformVectorNetwork(inverse, pagePath)
+ const bounds = computeAccurateBounds(localNetwork)
+ const relativeNetwork: VectorNetwork = {
+ vertices: localNetwork.vertices.map((v) => ({ ...v, x: v.x - bounds.x, y: v.y - bounds.y })),
+ segments: localNetwork.segments,
+ regions: localNetwork.regions
+ }
+ // The layer rotates and flips about its center, so with those kept the new x and y follow from
+ // where the new geometry's center lands in the parent, through the old local matrix: the
+ // geometry itself has not moved.
+ const center = Matrix.mapPoint(getNodeLocalMatrix(node), {
+ x: bounds.x + bounds.width / 2,
+ y: bounds.y + bounds.height / 2
+ })
+ return {
+ x: center.x - bounds.width / 2,
+ y: center.y - bounds.height / 2,
+ width: bounds.width,
+ height: bounds.height,
+ vectorNetwork: relativeNetwork,
+ // Fills draw from fillGeometry blobs when present, so rebuild them from the new path.
+ fillGeometry: regenerateFillGeometry(relativeNetwork, node.fillGeometry),
+ // Imported stroke outlines no longer match; strokes come from the path instead.
+ strokeGeometry: []
+ }
+}
diff --git a/packages/core/tests/editor/pen-resume.test.ts b/packages/core/tests/editor/pen-resume.test.ts
new file mode 100644
index 000000000..c17c8614d
--- /dev/null
+++ b/packages/core/tests/editor/pen-resume.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+/** A 100-wide open path in a frame at (200, 100), named "Path". */
+function setup() {
+ editor = createEditor()
+ const page = editor.state.currentPageId
+ const frame = editor.graph.createNode('FRAME', page, { x: 200, y: 100, width: 300, height: 300 })
+ const path = editor.graph.createNode('VECTOR', frame.id, {
+ name: 'Path',
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 0,
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ })
+ return { frame: frame.id, path: path.id }
+}
+
+/** Continues the path from its end, in page coordinates, as resuming from an endpoint does. */
+function resume(id: string) {
+ const node = getNodeOrThrow(editor.graph, id)
+ editor.state.penState = {
+ vertices: [
+ { x: 200, y: 100 },
+ { x: 300, y: 100 }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ dragTangent: null,
+ oppositeDragTangent: null,
+ closingToFirst: false,
+ pendingClose: false,
+ resumingNodeId: id,
+ resumedFills: [...node.fills],
+ resumedStrokes: [...node.strokes]
+ }
+}
+
+describe('continuing a pen path', () => {
+ test('grows the same layer, where it is, and one undo puts its path back', () => {
+ const { frame, path } = setup()
+ resume(path)
+ editor.penAddVertex(300, 150)
+ editor.penCommit(false)
+
+ expect(getNodeOrThrow(editor.graph, frame).childIds).toEqual([path])
+ const grown = getNodeOrThrow(editor.graph, path)
+ expect(grown.name).toBe('Path')
+ expect(grown.vectorNetwork?.segments).toHaveLength(2)
+ expect({ x: grown.x, y: grown.y, width: grown.width, height: grown.height }).toEqual({
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 50
+ })
+ expect([...editor.state.selectedIds]).toEqual([path])
+
+ editor.undo.undo()
+ expect(getNodeOrThrow(editor.graph, path).vectorNetwork?.segments).toHaveLength(1)
+ editor.undo.redo()
+ expect(getNodeOrThrow(editor.graph, path).vectorNetwork?.segments).toHaveLength(2)
+ })
+
+ test('committing without a new point leaves the layer and the undo history alone', () => {
+ const { path } = setup()
+ const before = getNodeOrThrow(editor.graph, path).vectorNetwork
+ resume(path)
+ editor.penCommit(false)
+ expect(getNodeOrThrow(editor.graph, path).vectorNetwork).toBe(before)
+ expect(editor.undo.canUndo).toBe(false)
+ })
+
+ test('makes a new layer when the one it came from is gone', () => {
+ const { frame, path } = setup()
+ resume(path)
+ editor.graph.deleteNode(path)
+ editor.penAddVertex(300, 150)
+ editor.penCommit(false)
+ expect(getNodeOrThrow(editor.graph, frame).childIds).toEqual([])
+ const [created] = editor.state.selectedIds
+ expect(getNodeOrThrow(editor.graph, created).vectorNetwork?.segments).toHaveLength(2)
+ })
+})
diff --git a/packages/scene-graph/src/snap.ts b/packages/scene-graph/src/snap.ts
index 9e3b83312..c7e285acd 100644
--- a/packages/scene-graph/src/snap.ts
+++ b/packages/scene-graph/src/snap.ts
@@ -9,6 +9,8 @@ export interface SnapGuide {
position: number
from: number
to: number
+ /** Points along the guide that lined up, marked with a cross: a guide through path vertices. */
+ marks?: number[]
}
export interface SnapResult {
diff --git a/packages/vue/src/canvas/pen/input.ts b/packages/vue/src/canvas/pen/input.ts
index 6fd2f1db4..ac3d21126 100644
--- a/packages/vue/src/canvas/pen/input.ts
+++ b/packages/vue/src/canvas/pen/input.ts
@@ -6,6 +6,7 @@ import type { Vector } from '@open-pencil/scene-graph/primitives'
import { createPenDrag, handlePenDragMove } from '#vue/canvas/pen/drag'
import { PEN_CURSOR } from '#vue/editor/tool-cursor'
+import { resolveVertexSnap } from '#vue/shared/input/snap'
import type { DragState } from '#vue/shared/input/types'
import { handlePenNodeEditDown } from '#vue/shared/input/vector'
@@ -17,8 +18,19 @@ function nearFirstVertex(cx: number, cy: number, first: Vector, editor: Editor)
return Math.hypot(cx - first.x, cy - first.y) < PEN_CLOSE_THRESHOLD / zoom
}
+/**
+ * The vertices the pen's next point lines up with, which in Figma are only the path's own: the
+ * path being drawn with the one it continues, or the path being edited before the pen picks it up.
+ */
+function penSnapVertices(editor: Editor): readonly Vector[] {
+ const penState = editor.state.penState
+ if (!penState) return editor.state.nodeEditState?.vertices ?? []
+ const resumed = penState.resumedPath?.network.vertices ?? []
+ return [...resumed, ...penState.vertices]
+}
+
export function startPenInput(
- e: MouseEvent,
+ e: Pick<MouseEvent, 'altKey'>,
cx: number,
cy: number,
editor: Editor,
@@ -28,9 +40,10 @@ export function startPenInput(
editor.state.penCursorX = null
editor.state.penCursorY = null
- const nodeEditState = editor.state.nodeEditState
- if (nodeEditState) {
- handlePenNodeEditDown(e, cx, cy, editor)
+ const { point } = resolveVertexSnap({ x: cx, y: cy }, penSnapVertices(editor), editor)
+ editor.setSnapGuides([])
+ if (editor.state.nodeEditState) {
+ handlePenNodeEditDown(e, cx, cy, editor, point)
return true
}
@@ -47,16 +60,20 @@ export function startPenInput(
}
editor.penSetPendingClose(false)
- editor.penAddVertex(cx, cy)
- setDrag(createPenDrag(cx, cy))
+ editor.penAddVertex(point.x, point.y)
+ setDrag(createPenDrag(point.x, point.y))
cursorOverride.value = PEN_CURSOR
return true
}
export function updatePenHover(cx: number, cy: number, editor: Editor): boolean {
- if (editor.state.activeTool !== 'PEN' || !editor.state.penState) return false
- editor.state.penCursorX = cx
- editor.state.penCursorY = cy
+ if (editor.state.activeTool !== 'PEN') return false
+ if (!editor.state.penState && !editor.state.nodeEditState) return false
+ const snap = resolveVertexSnap({ x: cx, y: cy }, penSnapVertices(editor), editor)
+ editor.setSnapGuides(snap.guides)
+ if (!editor.state.penState) return true
+ editor.state.penCursorX = snap.point.x
+ editor.state.penCursorY = snap.point.y
const first = editor.state.penState.vertices[0]
if (editor.state.penState.vertices.length > 2) {
diff --git a/packages/vue/src/shared/input/snap.ts b/packages/vue/src/shared/input/snap.ts
index 448e7d14b..32a366243 100644
--- a/packages/vue/src/shared/input/snap.ts
+++ b/packages/vue/src/shared/input/snap.ts
@@ -1,3 +1,5 @@
+import { uniq } from 'es-toolkit'
+
import { SNAP_THRESHOLD_SCREEN_PX } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
import { computeSnap } from '@open-pencil/scene-graph'
@@ -187,3 +189,67 @@ export function optionalEditorState(editor: Editor): Editor['state'] | undefined
export function snappingThreshold(editor: Editor): number {
return SNAP_THRESHOLD_SCREEN_PX / Math.max(editor.state.zoom, Number.EPSILON)
}
+
+export interface PointSnapResult {
+ point: Vector
+ guides: SnapGuide[]
+}
+
+/**
+ * Lines a point up with path vertices, as Figma's pen does: on each axis the point takes the
+ * nearest vertex coordinate within the snapping distance, and the guide runs through the point and
+ * every vertex on that line, with a cross on each. A point that lands on a vertex shows only that
+ * vertex's cross.
+ */
+export function resolveVertexSnap(
+ point: Vector,
+ vertices: readonly Vector[],
+ editor: Editor
+): PointSnapResult {
+ if (!editor.state.snappingPreferences.geometry) return { point, guides: [] }
+ const threshold = snappingThreshold(editor)
+ const x = nearestVertexCoordinate(point, vertices, 'x', threshold)
+ const y = nearestVertexCoordinate(point, vertices, 'y', threshold)
+ const snapped = { x: x ?? point.x, y: y ?? point.y }
+ if (vertices.some((vertex) => vertex.x === snapped.x && vertex.y === snapped.y)) {
+ return {
+ point: snapped,
+ guides: [
+ { axis: 'x', position: snapped.x, from: snapped.y, to: snapped.y, marks: [snapped.y] }
+ ]
+ }
+ }
+ const guides: SnapGuide[] = []
+ if (x !== null) guides.push(guideThroughVertices('x', x, snapped.y, vertices))
+ if (y !== null) guides.push(guideThroughVertices('y', y, snapped.x, vertices))
+ return { point: snapped, guides }
+}
+
+function nearestVertexCoordinate(
+ point: Vector,
+ vertices: readonly Vector[],
+ axis: 'x' | 'y',
+ threshold: number
+): number | null {
+ let nearest: number | null = null
+ for (const vertex of vertices) {
+ const distance = Math.abs(vertex[axis] - point[axis])
+ if (distance >= threshold) continue
+ if (nearest === null || distance < Math.abs(nearest - point[axis])) nearest = vertex[axis]
+ }
+ return nearest
+}
+
+function guideThroughVertices(
+ axis: 'x' | 'y',
+ position: number,
+ pointAlong: number,
+ vertices: readonly Vector[]
+): SnapGuide {
+ const across = axis === 'x' ? 'y' : 'x'
+ const marks = uniq([
+ pointAlong,
+ ...vertices.filter((vertex) => vertex[axis] === position).map((vertex) => vertex[across])
+ ])
+ return { axis, position, from: Math.min(...marks), to: Math.max(...marks), marks }
+}
diff --git a/packages/vue/src/shared/input/vector/index.ts b/packages/vue/src/shared/input/vector/index.ts
index 738efc87b..3024ac273 100644
--- a/packages/vue/src/shared/input/vector/index.ts
+++ b/packages/vue/src/shared/input/vector/index.ts
@@ -22,7 +22,8 @@ type NodeEditEditor = Partial<{
exitNodeEditMode: (commit: boolean) => void
nodeEditRemoveVertex: (vertexIndex: number) => void
penResumeFromEndpoint: (nodeId: string, endpointVertexIndex: number) => void
- nodeEditAddVertex: (cx: number, cy: number) => void
+ penStartPiece: (nodeId: string, point: Vector) => void
+ nodeEditAddVertex: (cx: number, cy: number) => boolean
nodeEditPushHistory: () => void
nodeEditSetHandle: (
segmentIndex: number,
@@ -123,7 +124,17 @@ export function handleNodeEditDown(
nodeEditEditor.exitNodeEditMode?.(true)
}
-export function handlePenNodeEditDown(e: MouseEvent, cx: number, cy: number, editor: Editor) {
+/**
+ * A pen press on the path being edited: an end point continues the path from there, a segment gets
+ * a point, and anywhere else starts a new piece of the same path at `pieceStart`, as in Figma.
+ */
+export function handlePenNodeEditDown(
+ e: Pick<MouseEvent, 'altKey'>,
+ cx: number,
+ cy: number,
+ editor: Editor,
+ pieceStart: Vector = { x: cx, y: cy }
+) {
const es = getNodeEditState(editor)
if (!es) return
const nodeEditEditor = editor as Editor & NodeEditEditor
@@ -142,7 +153,10 @@ export function handlePenNodeEditDown(e: MouseEvent, cx: number, cy: number, edi
return
}
- nodeEditEditor.nodeEditAddVertex?.(cx, cy)
+ if (nodeEditEditor.nodeEditAddVertex?.(cx, cy)) return
+ const nodeId = es.nodeId
+ nodeEditEditor.exitNodeEditMode?.(true)
+ nodeEditEditor.penStartPiece?.(nodeId, pieceStart)
}
export function handleNodeEditMove(
diff --git a/packages/vue/tests/canvas/pen/input.test.ts b/packages/vue/tests/canvas/pen/input.test.ts
new file mode 100644
index 000000000..d06d6be60
--- /dev/null
+++ b/packages/vue/tests/canvas/pen/input.test.ts
@@ -0,0 +1,89 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test'
+
+import { ref } from 'vue'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+import { startPenInput, updatePenHover } from '#vue/canvas/pen/input'
+import { resolveVertexSnap } from '#vue/shared/input/snap'
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+function setup() {
+ editor = createEditor()
+ editor.setTool('PEN')
+ return editor
+}
+
+function click(x: number, y: number) {
+ startPenInput({ altKey: false }, x, y, editor, mock(), ref<string | null>(null))
+}
+
+// Figma desktop 126 at 100%: the pen's next point lines up with the path's own vertices from 4
+// screen pixels away, not 5, and ignores other layers.
+describe('pen vertex snapping', () => {
+ const vertices: Vector[] = [
+ { x: 0, y: 120 },
+ { x: 100, y: 0 },
+ { x: 200, y: 120 }
+ ]
+
+ test('takes a vertex coordinate within the snapping distance', () => {
+ setup()
+ expect(resolveVertexSnap({ x: 260, y: 4 }, vertices, editor).point).toEqual({ x: 260, y: 0 })
+ expect(resolveVertexSnap({ x: 260, y: 5 }, vertices, editor)).toEqual({
+ point: { x: 260, y: 5 },
+ guides: []
+ })
+ })
+
+ test('runs the guide through every vertex on the line and marks each', () => {
+ setup()
+ const { guides } = resolveVertexSnap({ x: 300, y: 118 }, vertices, editor)
+ expect(guides).toEqual([{ axis: 'y', position: 120, from: 0, to: 300, marks: [300, 0, 200] }])
+ })
+
+ test('a point on a vertex shows only that vertex', () => {
+ setup()
+ expect(resolveVertexSnap({ x: 198, y: 121 }, vertices, editor)).toEqual({
+ point: { x: 200, y: 120 },
+ guides: [{ axis: 'x', position: 200, from: 120, to: 120, marks: [120] }]
+ })
+ })
+
+ test('scales the distance with zoom and follows the geometry preference', () => {
+ setup()
+ editor.state.zoom = 4
+ expect(resolveVertexSnap({ x: 260, y: 1.5 }, vertices, editor).guides).toEqual([])
+ editor.state.zoom = 1
+ editor.state.snappingPreferences = { ...editor.state.snappingPreferences, geometry: false }
+ expect(resolveVertexSnap({ x: 260, y: 2 }, vertices, editor).guides).toEqual([])
+ })
+
+ test('the cursor and the next point line up with the points already drawn', () => {
+ setup()
+ click(0, 0)
+ click(100, 50)
+ updatePenHover(197, 2, editor)
+ expect([editor.state.penCursorX, editor.state.penCursorY]).toEqual([197, 0])
+ expect(editor.state.snapGuides).toEqual([
+ { axis: 'y', position: 0, from: 0, to: 197, marks: [197, 0] }
+ ])
+
+ click(197, 2)
+ expect(editor.state.penState?.vertices.at(-1)).toEqual({ x: 197, y: 0 })
+ expect(editor.state.snapGuides).toEqual([])
+ })
+
+ test('leaving the pen drops its guides', () => {
+ setup()
+ click(0, 0)
+ updatePenHover(3, 80, editor)
+ expect(editor.state.snapGuides).toHaveLength(1)
+ editor.penCancel()
+ expect(editor.state.snapGuides).toEqual([])
+ })
+})
diff --git a/src/app/editor/pen/create.ts b/src/app/editor/pen/create.ts
index cd07aeb16..bf9687a94 100644
--- a/src/app/editor/pen/create.ts
+++ b/src/app/editor/pen/create.ts
@@ -1,11 +1,14 @@
import type { Editor, Tool } from '@open-pencil/core/editor'
-import { transformVectorNetwork } from '@open-pencil/scene-graph'
+import { transformVectorNetwork, type VectorNetwork } from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
import {
+ chainEndingAt,
createResumedPenState,
- walkChainOrdered,
- walkChainToEnd,
+ newPieceAt,
+ wholeChain,
+ type PenChain,
type PenState
} from '@/app/editor/pen/resume'
@@ -13,7 +16,8 @@ import {
// instance (editor.replaceGraph), so a captured reference goes stale.
//
// Pen state is page-absolute; resumed geometry maps through the node's world
-// matrix so nested, rotated, and flipped vectors resume in place.
+// matrix so nested, rotated, and flipped vectors resume in place. The layer
+// stays in the document while its path grows, and committing updates it.
export function createPenActions(editor: Editor, state: PenState) {
function setTool(tool: Tool) {
if (state.penState && tool !== 'PEN' && tool !== 'HAND') {
@@ -22,7 +26,8 @@ export function createPenActions(editor: Editor, state: PenState) {
editor.setTool(tool)
}
- function penResumeOnPath(nodeId: string) {
+ /** Continues `nodeId`'s path with the pen, on the chain `pick` takes from its page-space network. */
+ function resumeOn(nodeId: string, pick: (network: VectorNetwork) => PenChain) {
const node = editor.graph.getNode(nodeId)
if (node?.type !== 'VECTOR' || !node.vectorNetwork) return
@@ -30,37 +35,24 @@ export function createPenActions(editor: Editor, state: PenState) {
getWorldMatrix(node, editor.graph),
node.vectorNetwork
)
- state.penState = createResumedPenState(node, absNetwork.vertices, absNetwork.segments)
-
- editor.graph.deleteNode(nodeId)
+ state.penState = createResumedPenState(node, pick(absNetwork))
editor.clearSelection()
editor.setTool('PEN')
editor.requestRender()
}
- function penResumeFromEndpoint(nodeId: string, endpointVertexIndex: number) {
- const node = editor.graph.getNode(nodeId)
- if (node?.type !== 'VECTOR' || !node.vectorNetwork) return
+ function penResumeOnPath(nodeId: string) {
+ resumeOn(nodeId, wholeChain)
+ }
- const absNetwork = transformVectorNetwork(
- getWorldMatrix(node, editor.graph),
- node.vectorNetwork
- )
- const absVertices = absNetwork.vertices
- const absSegments = absNetwork.segments
- const otherEnd = walkChainToEnd(absSegments, endpointVertexIndex)
- const { orderedVertices, orderedSegments } = walkChainOrdered(
- absVertices,
- absSegments,
- otherEnd
- )
+ function penResumeFromEndpoint(nodeId: string, endpointVertexIndex: number) {
+ resumeOn(nodeId, (network) => chainEndingAt(network, endpointVertexIndex))
+ }
- state.penState = createResumedPenState(node, orderedVertices, orderedSegments)
- editor.graph.deleteNode(nodeId)
- editor.clearSelection()
- editor.setTool('PEN')
- editor.requestRender()
+ /** Starts a new piece of `nodeId`'s path at a page point, as a pen click off the path does in Figma. */
+ function penStartPiece(nodeId: string, point: Vector) {
+ resumeOn(nodeId, (network) => newPieceAt(network, point))
}
- return { setTool, penResumeOnPath, penResumeFromEndpoint }
+ return { setTool, penResumeOnPath, penResumeFromEndpoint, penStartPiece }
}
diff --git a/src/app/editor/pen/resume.ts b/src/app/editor/pen/resume.ts
index 6fe8296d4..81a1adaeb 100644
--- a/src/app/editor/pen/resume.ts
+++ b/src/app/editor/pen/resume.ts
@@ -1,90 +1,101 @@
-import type { EditorState } from '@open-pencil/core/editor'
-import type { SceneNode, VectorSegment, VectorVertex } from '@open-pencil/scene-graph'
+import type { EditorState, ResumedPath } from '@open-pencil/core/editor'
+import {
+ cloneVectorNetwork,
+ type SceneNode,
+ type VectorNetwork,
+ type VectorSegment,
+ type VectorVertex
+} from '@open-pencil/scene-graph'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
export type PenState = EditorState
type PenStateInit = NonNullable<EditorState['penState']>
-export function createResumedPenState(
- node: SceneNode,
- vertices: VectorVertex[],
+export interface PenChain {
+ vertices: VectorVertex[]
segments: VectorSegment[]
-): PenStateInit {
+ path: ResumedPath
+}
+
+export function createResumedPenState(node: SceneNode, chain: PenChain): PenStateInit {
return {
- vertices,
- segments,
+ vertices: chain.vertices,
+ segments: chain.segments,
dragTangent: null,
oppositeDragTangent: null,
closingToFirst: false,
pendingClose: false,
resumingNodeId: node.id,
+ resumedPath: chain.path,
resumedFills: [...node.fills],
resumedStrokes: [...node.strokes]
}
}
-export 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
+/** The whole network as the pen's chain, in its own order. */
+export function wholeChain(network: VectorNetwork): PenChain {
+ // The pen moves and adds to its chain, so it gets a copy.
+ const { vertices, segments } = cloneVectorNetwork(network)
+ return {
+ vertices,
+ segments,
+ path: {
+ network,
+ vertices: network.vertices.map((_, index) => index),
+ segments: network.segments.map((_, index) => ({ index, reversed: false }))
}
- if (!found) break
}
- return current
}
-export 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)
+/**
+ * A chain that starts a new piece of `network` at `point`: it walks none of the network, so
+ * committing adds everything the pen draws beside the pieces already there.
+ */
+export function newPieceAt(network: VectorNetwork, point: Vector): PenChain {
+ return {
+ vertices: [{ ...point }],
+ segments: [],
+ path: { network, vertices: [], segments: [] }
+ }
+}
+/**
+ * The chain a pen continuing from `end` draws on: walked out from `end` and turned around, so
+ * `end` is its last vertex, where the pen adds the next point. At a branch the walk takes one
+ * way; the branches it leaves stay in `network` and are kept when the pen commits.
+ */
+export function chainEndingAt(network: VectorNetwork, end: number): PenChain {
+ const walk = [end]
+ const walked: number[] = []
+ const visited = new Set([end])
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
- }
- 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 }
- })
+ const from = walk[walk.length - 1]
+ const index = network.segments.findIndex(
+ (s) => (s.start === from && !visited.has(s.end)) || (s.end === from && !visited.has(s.start))
+ )
+ if (index === -1) break
+ const segment = network.segments[index]
+ const next = segment.start === from ? segment.end : segment.start
+ visited.add(next)
+ walk.push(next)
+ walked.push(index)
+ }
- visited.add(next)
- current = next
- foundSeg = true
- break
- }
- if (!foundSeg) break
+ const vertices = walk.toReversed()
+ const segments = walked
+ .toReversed()
+ .map((index, k) => ({ index, reversed: network.segments[index].start !== vertices[k] }))
+ return {
+ vertices: vertices.map((index) => ({ ...network.vertices[index] })),
+ segments: segments.map(({ index, reversed }, k) => {
+ const segment = network.segments[index]
+ return {
+ start: k,
+ end: k + 1,
+ tangentStart: { ...(reversed ? segment.tangentEnd : segment.tangentStart) },
+ tangentEnd: { ...(reversed ? segment.tangentStart : segment.tangentEnd) }
+ }
+ }),
+ path: { network, vertices, segments }
}
- return { orderedVertices, orderedSegments }
}
diff --git a/src/app/editor/vector/lifecycle.ts b/src/app/editor/vector/lifecycle.ts
index c0dc96d7a..28e009824 100644
--- a/src/app/editor/vector/lifecycle.ts
+++ b/src/app/editor/vector/lifecycle.ts
@@ -1,14 +1,12 @@
import type { Editor } from '@open-pencil/core/editor'
-import { computeAccurateBounds, regenerateFillGeometry } from '@open-pencil/core/vector'
+import { vectorChangesFromPagePath } from '@open-pencil/core/vector'
import {
cloneVectorNetwork,
slotScope,
transformVectorNetwork,
- vectorNetworksEqual,
- type VectorNetwork
+ vectorNetworksEqual
} from '@open-pencil/scene-graph'
-import { getNodeLocalMatrix, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
-import Matrix from '@open-pencil/scene-graph/matrix'
+import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
import { getLiveNetwork } from './network'
import type { VectorEditState } from './types'
@@ -44,49 +42,9 @@ export function createVectorEditLifecycle(editor: Editor, state: VectorEditState
// comparison detects a no-op session — skip it to keep undo clean.
if (vectorNetworksEqual(getLiveNetwork(es), es.origAbsNetwork)) return
- const world = getWorldMatrix(node, editor.graph)
- const inverse = Matrix.invert(world)
- if (!inverse) return
-
- // Map the edited page-absolute network back into the node's local frame
- const localNetwork = transformVectorNetwork(inverse, getLiveNetwork(es))
- const bounds = computeAccurateBounds(localNetwork)
- const relativeNetwork: VectorNetwork = {
- vertices: localNetwork.vertices.map((v) => ({
- ...v,
- x: v.x - bounds.x,
- y: v.y - bounds.y
- })),
- segments: localNetwork.segments,
- regions: localNetwork.regions
- }
-
- // The node rotates/flips about its center, so with rotation preserved the
- // new x/y follow from where the new geometry's center lands in the parent
- // frame (via the OLD local matrix — the geometry itself has not moved).
- const localMatrix = getNodeLocalMatrix(node)
- const center = Matrix.mapPoint(localMatrix, {
- x: bounds.x + bounds.width / 2,
- y: bounds.y + bounds.height / 2
- })
-
- editor.updateNodeWithUndo(
- node.id,
- {
- x: center.x - bounds.width / 2,
- y: center.y - bounds.height / 2,
- width: bounds.width,
- height: bounds.height,
- vectorNetwork: relativeNetwork,
- // Fills render from fillGeometry blobs when present — rebuild them from
- // the edited network so fills follow the edit.
- fillGeometry: regenerateFillGeometry(relativeNetwork, node.fillGeometry),
- // Drop stale imported stroke outline blobs; post-edit strokes come from
- // the live vector network path.
- strokeGeometry: []
- },
- 'Edit vector'
- )
+ const changes = vectorChangesFromPagePath(editor.graph, node, getLiveNetwork(es))
+ if (!changes) return
+ editor.updateNodeWithUndo(node.id, changes, 'Edit vector')
const committed = editor.graph.getNode(es.nodeId)
if (committed?.type === 'VECTOR' && committed.vectorNetwork) {
const committedWorld = getWorldMatrix(committed, editor.graph)
diff --git a/src/app/editor/vector/network.ts b/src/app/editor/vector/network.ts
index c3ee16105..0092786ee 100644
--- a/src/app/editor/vector/network.ts
+++ b/src/app/editor/vector/network.ts
@@ -70,18 +70,20 @@ export function createVectorEditNetworkActions(
editor.requestRender()
}
- function nodeEditAddVertex(cx: number, cy: number) {
+ /** Splits the segment under a canvas point; false when no segment is near enough. */
+ function nodeEditAddVertex(cx: number, cy: number): boolean {
const es = getNodeEditState()
- if (!es) return
+ if (!es) return false
const live = getLiveNetwork(es)
const nearest = nearestPointOnNetwork(cx, cy, live, nodeEditHitThreshold / state.zoom)
- if (!nearest) return
+ if (!nearest) return false
pushNodeEditHistory(es)
const split = splitSegmentAt(live, nearest.segmentIndex, nearest.t)
setNodeEditNetwork(es, split.network)
es.selectedVertexIndices = new Set([split.newVertexIndex])
es.selectedHandles = new Set()
editor.requestRender()
+ return true
}
function nodeEditRemoveVertex(vertexIndex: number) {
diff --git a/tests/app/editor/pen/resume.test.ts b/tests/app/editor/pen/resume.test.ts
new file mode 100644
index 000000000..56c3a8a7c
--- /dev/null
+++ b/tests/app/editor/pen/resume.test.ts
@@ -0,0 +1,102 @@
+import { afterEach, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+import type { VectorNetwork } from '@open-pencil/scene-graph'
+
+import { createPenActions } from '@/app/editor/pen'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+const STRAIGHT = { tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
+
+/** A T: a bar 0-1-2 and a stem 1-3 hanging from its middle. */
+const T: VectorNetwork = {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 50, y: 0 },
+ { x: 100, y: 0 },
+ { x: 50, y: 80 }
+ ],
+ segments: [
+ { start: 0, end: 1, ...STRAIGHT },
+ { start: 1, end: 2, ...STRAIGHT },
+ { start: 1, end: 3, ...STRAIGHT }
+ ],
+ regions: []
+}
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+function setup() {
+ editor = createEditor()
+ const vector = editor.graph.createNode('VECTOR', editor.state.currentPageId, {
+ width: 100,
+ height: 80,
+ vectorNetwork: structuredClone(T)
+ })
+ return { pen: createPenActions(editor, editor.state), id: vector.id }
+}
+
+const points = (network: VectorNetwork | null | undefined) =>
+ expectDefined(network).vertices.map(({ x, y }) => ({ x, y }))
+
+const lines = (network: VectorNetwork | null | undefined) =>
+ expectDefined(network).segments.map(({ start, end }) => [start, end])
+
+test('continues a branched path from the endpoint pressed', () => {
+ const { pen, id } = setup()
+ pen.penResumeFromEndpoint(id, 3)
+ const last = expectDefined(editor.state.penState?.vertices.at(-1))
+ expect({ x: last.x, y: last.y }).toEqual({ x: 50, y: 80 })
+})
+
+test('leaves a branched path whole when the pen adds nothing', () => {
+ const { pen, id } = setup()
+ pen.penResumeFromEndpoint(id, 3)
+ editor.penCommit(false)
+
+ expect(editor.graph.getNode(id)?.vectorNetwork).toEqual(T)
+ expect(editor.undo.canUndo).toBe(false)
+})
+
+test('keeps the branches the pen did not walk when it adds a point', () => {
+ const { pen, id } = setup()
+ pen.penResumeFromEndpoint(id, 3)
+ editor.penAddVertex(50, 120)
+ editor.penCommit(false)
+
+ const network = editor.graph.getNode(id)?.vectorNetwork
+ expect(points(network)).toEqual([...points(T), { x: 50, y: 120 }])
+ expect(lines(network)).toEqual([...lines(T), [3, 4]])
+
+ editor.undo.undo()
+ expect(editor.graph.getNode(id)?.vectorNetwork).toEqual(T)
+})
+
+// Figma desktop 126: a pen click off the path in vector edit mode starts a new piece of the same
+// layer, and the points drawn from it join the network unconnected to the rest.
+test('a new piece adds its points and segments beside the path', () => {
+ const { pen, id } = setup()
+ pen.penStartPiece(id, { x: 0, y: 120 })
+ editor.penAddVertex(100, 120)
+ editor.penCommit(false)
+
+ const network = editor.graph.getNode(id)?.vectorNetwork
+ expect(points(network)).toEqual([...points(T), { x: 0, y: 120 }, { x: 100, y: 120 }])
+ expect(lines(network)).toEqual([...lines(T), [4, 5]])
+ expect(editor.graph.getChildren(editor.state.currentPageId)).toHaveLength(1)
+
+ editor.undo.undo()
+ expect(editor.graph.getNode(id)?.vectorNetwork).toEqual(T)
+})
+
+test('a new piece with one point leaves the path as it was', () => {
+ const { pen, id } = setup()
+ pen.penStartPiece(id, { x: 0, y: 120 })
+ editor.penCommit(false)
+
+ expect(editor.graph.getNode(id)?.vectorNetwork).toEqual(T)
+ expect(editor.undo.canUndo).toBe(false)
+})
diff --git a/tests/e2e/canvas/vector/pen.spec.ts b/tests/e2e/canvas/vector/pen.spec.ts
new file mode 100644
index 000000000..efc9dc71d
--- /dev/null
+++ b/tests/e2e/canvas/vector/pen.spec.ts
@@ -0,0 +1,63 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+// Figma desktop 126: continuing a path, the point the pen draws from is solid, the segment to the
+// cursor is blue, and a cursor within 4 pixels of a vertex's y snaps to it with a guide.
+test('the pen previews a continued path and lines the next point up with its vertices', async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const straight = { tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
+ const vector = store.graph.createNode('VECTOR', store.state.currentPageId, {
+ name: 'Open path',
+ x: 100,
+ y: 80,
+ width: 200,
+ height: 120,
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ align: 'CENTER',
+ weight: 1
+ }
+ ],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 120 },
+ { x: 100, y: 0 },
+ { x: 200, y: 120 }
+ ],
+ segments: [
+ { start: 0, end: 1, ...straight },
+ { start: 1, end: 2, ...straight }
+ ],
+ regions: []
+ }
+ })
+ store.enterNodeEditMode(vector.id)
+ store.setTool('PEN')
+ })
+ await editor.canvas.waitForRender()
+ const box = await editor.canvas.canvas.boundingBox()
+ if (!box) throw new Error('Canvas bounds unavailable')
+
+ await editor.page.mouse.click(box.x + 300, box.y + 200)
+ await editor.page.mouse.move(box.x + 380, box.y + 83)
+ await editor.canvas.waitForRender()
+
+ const state = await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ return {
+ cursor: [store?.state.penCursorX, store?.state.penCursorY],
+ guides: store?.state.snapGuides
+ }
+ })
+ expect(state.cursor).toEqual([380, 80])
+ expect(state.guides).toEqual([{ axis: 'y', position: 80, from: 200, to: 380, marks: [380, 200] }])
+ editor.canvas.assertNoErrors()
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('pen-continue-guide.png')
+})
diff --git a/tests/e2e/canvas/vector/pen.spec.ts-snapshots/pen-continue-guide-openpencil-darwin.png b/tests/e2e/canvas/vector/pen.spec.ts-snapshots/pen-continue-guide-openpencil-darwin.png
new file mode 100644
index 000000000..477165c85
Binary files /dev/null and b/tests/e2e/canvas/vector/pen.spec.ts-snapshots/pen-continue-guide-openpencil-darwin.png differ