AI-native design editor. Open-source Figma alternative.
feat(vector): hatch and select regions in vector edit mode, as in Figma (#1192)
rcoenen319b79b53556
diff --git a/changes/1192/added.md b/changes/1192/added.mdnew file mode 100644index 000000000..0143f502f--- /dev/null+++ b/changes/1192/added.md@@ -0,0 +1 @@+- In vector edit mode, the filled region under the pointer is hatched, as in Figma. Clicking inside it selects the region with its points, which then drag together.diff --git a/packages/core/src/canvas/node-edit-overlay.ts b/packages/core/src/canvas/node-edit-overlay.tsindex b1bc1e12e..91a37756a 100644--- a/packages/core/src/canvas/node-edit-overlay.ts+++ b/packages/core/src/canvas/node-edit-overlay.ts@@ -20,6 +20,7 @@ import {} from '#core/vector'import { evalCubic, segmentToAbsolute } from '#core/vector/curve-math'+import { drawRegionHatch } from './region-hatch'import type { SkiaRenderer, RenderOverlays } from './renderer'type ToScreenFn = (x: number, y: number) => Vector@@ -38,6 +39,8 @@ export interface NodeEditOverlayState {selectedSegmentIndices?: Set<number>selectedHandles?: Set<number>hoveredHandleInfo?: HandleInfo+ hoveredRegion?: number | null+ selectedRegions?: Set<number>}// Blue = rgb(59,130,246) ≈ 0.23, 0.51, 0.96@@ -98,6 +101,9 @@ export function drawNodeEditOverlay(// Draw the node shape with its original fills/strokes/effects using live verticesdrawLiveShape(r, canvas, graph, editState.nodeId, vertices, segments, regions)+ // Hatch the hovered and selected regions, as Figma does+ drawRegionHatch(r, canvas, graph, editState)+// Draw technical stroke outline over the shapedrawTechStroke(r, canvas, graph, editState.nodeId, vertices, segments, regions)diff --git a/packages/core/src/canvas/region-hatch.ts b/packages/core/src/canvas/region-hatch.tsnew file mode 100644index 000000000..ab94c6f70--- /dev/null+++ b/packages/core/src/canvas/region-hatch.ts@@ -0,0 +1,86 @@+import type { Canvas } from 'canvaskit-wasm'++import type { SceneGraph } from '@open-pencil/scene-graph'+import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'+import Matrix from '@open-pencil/scene-graph/matrix'++import { regionHatchPeriod } from '#core/vector'+import { addLoopToPath } from '#core/vector/path-helpers'++import type { RenderOverlays, SkiaRenderer } from './renderer'++/** Width of a hatch line in screen pixels, as Figma's shaded-region shader covers it. */+const HATCH_LINE_WIDTH = 1.4++/**+ * Figma's shaded regions (`UIRenderShadedRegionsCommand`): 45° lines running "/" in screen space,+ * anchored at the node's origin so they move with it, clipped to each region by its fill rule.+ * The hovered region and the selected ones are hatched.+ */+export function drawRegionHatch(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ editState: NonNullable<RenderOverlays['nodeEditState']>+): void {+ const hatched = new Set(editState.selectedRegions)+ if (editState.hoveredRegion != null) hatched.add(editState.hoveredRegion)+ if (hatched.size === 0) return+ const node = graph.getNode(editState.nodeId)+ if (!node) return++ // The edit session's network is in canvas coordinates; draw it in screen pixels.+ const vertices = editState.vertices.map((v) => ({+ ...v,+ x: v.x * r.zoom + r.panX,+ y: v.y * r.zoom + r.panY+ }))+ const segments = editState.segments.map((s) => ({+ ...s,+ tangentStart: { x: s.tangentStart.x * r.zoom, y: s.tangentStart.y * r.zoom },+ tangentEnd: { x: s.tangentEnd.x * r.zoom, y: s.tangentEnd.y * r.zoom }+ }))+ const [originX, originY] = Matrix.mapPoints(getWorldMatrix(node, graph), [0, 0])+ const ox = originX * r.zoom + r.panX+ const oy = originY * r.zoom + r.panY+ // Lines x + y = c, a period apart across them, so √2 periods apart along either axis.+ const step = regionHatchPeriod(r.zoom) * Math.SQRT2++ const paint = new r.ck.Paint()+ paint.setAntiAlias(true)+ paint.setStyle(r.ck.PaintStyle.Stroke)+ paint.setStrokeWidth(HATCH_LINE_WIDTH)+ paint.setColor(r.selColor())++ for (const index of hatched) {+ const region = editState.regions.at(index)+ if (!region) continue+ const builder = new r.ck.PathBuilder()+ for (const loop of region.loops) addLoopToPath(builder, loop, segments, vertices)+ const path = builder.detachAndDelete()+ // On the detached path: the builder's setFillType returns a copy that nothing deletes.+ path.setFillType(+ region.windingRule === 'EVENODD' ? r.ck.FillType.EvenOdd : r.ck.FillType.Winding+ )+ // Lines only where the region is on screen: a large region would otherwise draw thousands of+ // invisible ones on every hover repaint.+ const [pathLeft, pathTop, pathRight, pathBottom] = path.getBounds()+ const left = Math.max(pathLeft, 0)+ const top = Math.max(pathTop, 0)+ const right = Math.min(pathRight, r.viewportWidth)+ const bottom = Math.min(pathBottom, r.viewportHeight)+ if (left < right && top < bottom) {+ canvas.save()+ canvas.clipPath(path, r.ck.ClipOp.Intersect, true)+ const first = Math.floor((left + top - ox - oy) / step)+ const last = Math.ceil((right + bottom - ox - oy) / step)+ for (let k = first; k <= last; k++) {+ const c = ox + oy + k * step+ canvas.drawLine(c - top, top, c - bottom, bottom, paint)+ }+ canvas.restore()+ }+ path.delete()+ }+ paint.delete()+}diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.tsindex 7e2448ff6..7b7fe55a1 100644--- a/packages/core/src/canvas/renderer/types.ts+++ b/packages/core/src/canvas/renderer/types.ts@@ -105,6 +105,10 @@ export interface RenderOverlays {selectedSegmentIndices?: Set<number>selectedHandles?: Set<number>hoveredHandleInfo?: { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null+ /** The region under the pointer, hatched as in Figma. */+ hoveredRegion?: number | null+ /** Regions picked by clicking inside them, hatched while selected. */+ selectedRegions?: Set<number>} | nullpresenceCursors?: PresenceCursor[]designIssues?: DesignIssueOverlay | nulldiff --git a/packages/core/src/vector/index.ts b/packages/core/src/vector/index.tsindex 8eda72bef..c561be91f 100644--- a/packages/core/src/vector/index.ts+++ b/packages/core/src/vector/index.ts@@ -27,6 +27,7 @@ import type { VectorNetwork, WindingRule } from '@open-pencil/scene-graph'import { addLoopToPath, addOpenSegmentsToPath } from './path-helpers'export { vectorNetworkToCenterlinePath, fitCircleArc, isClosedThinCrescent } from './centerline'export { regenerateFillGeometry } from './fill-geometry'+export { regionAtPoint, regionHatchPeriod, regionVertexIndices } from './region-hit'export { addStrokeRunToPath, strokeRuns, type StrokeRun } from './path-helpers'export { vectorChangesFromPagePath, type VectorPathChanges } from './placement'diff --git a/packages/core/src/vector/region-hit.ts b/packages/core/src/vector/region-hit.tsnew file mode 100644index 000000000..fca0ebc93--- /dev/null+++ b/packages/core/src/vector/region-hit.ts@@ -0,0 +1,138 @@+import type { VectorNetwork } from '@open-pencil/scene-graph'+import type { Vector } from '@open-pencil/scene-graph/primitives'++/** How far, in network units, a flattened curve may stray from the curve unless a caller says. */+const DEFAULT_TOLERANCE = 0.25+/** Keeps a huge curve at a tiny tolerance from flattening into an unbounded number of points. */+const MAX_CURVE_STEPS = 1024++/**+ * Steps that keep a cubic's polyline within `tolerance` of it: equal steps in t stray at most+ * M / (8n²) from a curve whose second derivative is at most M, and for a cubic+ * M ≤ 6 · max(|p0 − 2p1 + p2|, |p1 − 2p2 + p3|).+ */+function curveSteps(p0: Vector, p1: Vector, p2: Vector, p3: Vector, tolerance: number): number {+ const bend = Math.max(+ Math.hypot(p0.x - 2 * p1.x + p2.x, p0.y - 2 * p1.y + p2.y),+ Math.hypot(p1.x - 2 * p2.x + p3.x, p1.y - 2 * p2.y + p3.y)+ )+ const steps = Math.ceil(Math.sqrt((6 * bend) / (8 * tolerance)))+ return Math.min(MAX_CURVE_STEPS, Math.max(1, steps))+}++/** Points along a segment, from its start to its end, in network coordinates. */+function segmentPoints(network: VectorNetwork, index: number, tolerance: number): Vector[] | null {+ const segment = network.segments.at(index)+ if (!segment || segment.start < 0 || segment.end < 0) return null+ const p0 = network.vertices.at(segment.start)+ const p3 = network.vertices.at(segment.end)+ if (!p0 || !p3) return null+ const { tangentStart: a, tangentEnd: b } = segment+ if (a.x === 0 && a.y === 0 && b.x === 0 && b.y === 0) return [p0, p3]+ const p1 = { x: p0.x + a.x, y: p0.y + a.y }+ const p2 = { x: p3.x + b.x, y: p3.y + b.y }+ const points: Vector[] = []+ const steps = curveSteps(p0, p1, p2, p3, tolerance)+ for (let step = 0; step <= steps; step++) {+ const t = step / steps+ const u = 1 - t+ points.push({+ x: u * u * u * p0.x + 3 * u * u * t * p1.x + 3 * u * t * t * p2.x + t * t * t * p3.x,+ y: u * u * u * p0.y + 3 * u * u * t * p1.y + 3 * u * t * t * p2.y + t * t * t * p3.y+ })+ }+ return points+}++/**+ * A loop's points in the order it is walked. Segments in a loop can be stored either way round,+ * so each is followed from the vertex the previous one ended on.+ */+function loopPoints(network: VectorNetwork, loop: number[], tolerance: number): Vector[] {+ const { segments } = network+ const first = segments.at(loop[0] ?? -1)+ const second = segments.at(loop[1] ?? -1)+ if (!first) return []+ // Walk the first segment toward the vertex it shares with the next one.+ const firstForward = !second || first.end === second.start || first.end === second.end+ let current = firstForward ? first.start : first.end+ const points: Vector[] = []+ for (const index of loop) {+ const segment = segments.at(index)+ const along = segmentPoints(network, index, tolerance)+ if (!segment || !along) continue+ const forward = segment.start === current+ points.push(...(forward ? along : along.toReversed()))+ current = forward ? segment.end : segment.start+ }+ return points+}++/** The signed number of times the region's loops wind around `point`. */+function windingNumber(+ network: VectorNetwork,+ regionIndex: number,+ point: Vector,+ tolerance: number+): number {+ let winding = 0+ for (const loop of network.regions[regionIndex]?.loops ?? []) {+ const points = loopPoints(network, loop, tolerance)+ for (let i = 0; i + 1 < points.length; i++) {+ const a = points[i]+ const b = points[i + 1]+ // Which side of the edge a→b the point is on, positive when left.+ const side = (b.x - a.x) * (point.y - a.y) - (point.x - a.x) * (b.y - a.y)+ if (a.y <= point.y) {+ if (b.y > point.y && side > 0) winding+++ } else if (b.y <= point.y && side < 0) {+ winding--+ }+ }+ }+ return winding+}++/**+ * The region of a vector network that contains `point`, as Figma finds the region under the+ * pointer in vector edit mode: each region's loops wind around the point by its own fill rule,+ * and where regions overlap the last one wins. Null outside every region. Curves are flattened+ * to within `tolerance` network units, so a point farther than that from an edge is placed+ * exactly.+ */+export function regionAtPoint(+ network: VectorNetwork,+ point: Vector,+ tolerance = DEFAULT_TOLERANCE+): number | null {+ for (let index = network.regions.length - 1; index >= 0; index--) {+ const winding = windingNumber(network, index, point, tolerance)+ const inside =+ network.regions[index].windingRule === 'EVENODD' ? winding % 2 !== 0 : winding !== 0+ if (inside) return index+ }+ return null+}++/** The vertices on a region's loops, which a selected region moves with it. */+export function regionVertexIndices(network: VectorNetwork, regionIndex: number): number[] {+ const indices = new Set<number>()+ for (const loop of network.regions.at(regionIndex)?.loops ?? []) {+ for (const index of loop) {+ const segment = network.segments.at(index)+ if (!segment) continue+ indices.add(segment.start)+ indices.add(segment.end)+ }+ }+ return [...indices]+}++/**+ * The distance between region hatch lines, in screen pixels at `zoom`: 8 at 100%, halving and+ * doubling between powers of two as Figma's does, so the stripes keep a steady density.+ */+export function regionHatchPeriod(zoom: number): number {+ if (!(zoom > 0)) return 8+ return (8 * zoom) / 2 ** Math.round(Math.log2(zoom))+}diff --git a/packages/core/tests/vector/region-hit.test.ts b/packages/core/tests/vector/region-hit.test.tsnew file mode 100644index 000000000..e4c9b8a69--- /dev/null+++ b/packages/core/tests/vector/region-hit.test.ts@@ -0,0 +1,135 @@+import { describe, expect, test } from 'bun:test'++import type { VectorNetwork, VectorSegment } from '@open-pencil/scene-graph'++import { regionAtPoint, regionHatchPeriod, regionVertexIndices } from '#core/vector/region-hit'++const zero = { x: 0, y: 0 }+const line = (start: number, end: number): VectorSegment => ({+ start,+ end,+ tangentStart: zero,+ tangentEnd: zero+})++/** A 100 square (vertices 0–3) with a 40 square inside it (vertices 4–7). */+function squareWithInner(rule: 'NONZERO' | 'EVENODD'): VectorNetwork {+ return {+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 0 },+ { x: 100, y: 100 },+ { x: 0, y: 100 },+ { x: 30, y: 30 },+ { x: 70, y: 30 },+ { x: 70, y: 70 },+ { x: 30, y: 70 }+ ],+ segments: [+ line(0, 1),+ line(1, 2),+ line(2, 3),+ line(3, 0),+ line(4, 5),+ line(5, 6),+ line(6, 7),+ line(7, 4)+ ],+ regions: [+ {+ windingRule: rule,+ loops: [+ [0, 1, 2, 3],+ [4, 5, 6, 7]+ ]+ }+ ]+ }+}++describe('the region under a point', () => {+ test('follows the region’s own fill rule', () => {+ // Both loops wind the same way: nonzero fills the middle, even-odd leaves a hole there.+ expect(regionAtPoint(squareWithInner('NONZERO'), { x: 50, y: 50 })).toBe(0)+ expect(regionAtPoint(squareWithInner('EVENODD'), { x: 50, y: 50 })).toBeNull()+ expect(regionAtPoint(squareWithInner('EVENODD'), { x: 10, y: 50 })).toBe(0)+ expect(regionAtPoint(squareWithInner('EVENODD'), { x: 150, y: 50 })).toBeNull()+ })++ test('is the last one where regions overlap, as in Figma', () => {+ const network = squareWithInner('NONZERO')+ network.regions = [+ { windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] },+ { windingRule: 'NONZERO', loops: [[4, 5, 6, 7]] }+ ]+ expect(regionAtPoint(network, { x: 50, y: 50 })).toBe(1)+ expect(regionAtPoint(network, { x: 10, y: 50 })).toBe(0)+ })++ test('counts a curved edge where it bulges, not along its chord', () => {+ // A lens: the top edge bows up 50 above the chord y = 0.+ const network: VectorNetwork = {+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 0 }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 30, y: -66 }, tangentEnd: { x: -30, y: -66 } },+ line(1, 0)+ ],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1]] }]+ }+ expect(regionAtPoint(network, { x: 50, y: -30 })).toBe(0)+ expect(regionAtPoint(network, { x: 50, y: 10 })).toBeNull()+ })++ test('places a point close inside a large curve on the right side', () => {+ // A lens 100000 wide: a fixed number of steps would cut hundreds of units off its bulge.+ const width = 100_000+ const network: VectorNetwork = {+ vertices: [+ { x: 0, y: 0 },+ { x: width, y: 0 }+ ],+ segments: [+ {+ start: 0,+ end: 1,+ tangentStart: { x: 0, y: -width },+ tangentEnd: { x: 0, y: -width }+ },+ line(1, 0)+ ],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1]] }]+ }+ // The edge at t = 17/32, between where coarse steps would sample it.+ const t = 17 / 32+ const u = 1 - t+ const edge = { x: (3 * u * t * t + t * t * t) * width, y: -3 * t * u * width }+ expect(regionAtPoint(network, { x: edge.x, y: edge.y + 1 })).toBe(0)+ expect(regionAtPoint(network, { x: edge.x, y: edge.y - 1 })).toBeNull()+ })+})++test('segments stored against the loop’s direction still enclose it', () => {+ // The same square, with its second and fourth sides stored backwards.+ const network = squareWithInner('NONZERO')+ network.segments[1] = line(2, 1)+ network.segments[3] = line(0, 3)+ network.regions = [{ windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] }]+ expect(regionAtPoint(network, { x: 50, y: 50 })).toBe(0)+ expect(regionAtPoint(network, { x: 150, y: 50 })).toBeNull()+})++test('a region’s vertices are those on its loops', () => {+ expect(regionVertexIndices(squareWithInner('NONZERO'), 0).toSorted()).toEqual([+ 0, 1, 2, 3, 4, 5, 6, 7+ ])+})++test('hatch lines are 8 px apart at 100% and keep a steady density as you zoom', () => {+ expect(regionHatchPeriod(1)).toBe(8)+ expect(regionHatchPeriod(2)).toBe(8)+ expect(regionHatchPeriod(1.3)).toBeCloseTo(10.4, 6)+ expect(regionHatchPeriod(1.5)).toBeCloseTo(6, 6)+})diff --git a/packages/docs/user-guide/vector-edit.md b/packages/docs/user-guide/vector-edit.mdindex 8cd90b116..b00082b69 100644--- a/packages/docs/user-guide/vector-edit.md+++ b/packages/docs/user-guide/vector-edit.md@@ -50,6 +50,12 @@ This activates geometry editing for the selected vector.- Drag over empty space to select the anchors inside the rectangle and the segments between them.- <kbd>Shift</kbd> + drag adds them to the selection.+### Select a Region++- Move the pointer inside a filled area: the region under it is hatched with diagonal lines.+- Click inside it to select the region and all of its points; drag to move it.+- <kbd>Shift</kbd> + click adds the region to the selection.+### Delete Anchors and Segments- Press <kbd>Delete</kbd> or <kbd>Backspace</kbd> to delete the selection.diff --git a/packages/vue/src/canvas/vector-input/input.ts b/packages/vue/src/canvas/vector-input/input.tsindex ca975b61d..133eee8f4 100644--- a/packages/vue/src/canvas/vector-input/input.ts+++ b/packages/vue/src/canvas/vector-input/input.ts@@ -11,9 +11,11 @@ import {import type { DragState } from '#vue/shared/input/types'import {finishNodeEditMarquee,+ getNodeEditState,hitTestEditHandle,+ hitTestEditRegion,isEndpoint,- finishSegmentClick,+ finishPartClick,NODE_HIT_THRESHOLD} from '#vue/shared/input/vector'@@ -35,6 +37,13 @@ export function updateNodeEditHover(editor: Editor, cx: number, cy: number): boostate.hoveredHandleInfo = nulleditor.requestRepaint()}+ // The region under the pointer is hatched, as in Figma, unless a handle is under it.+ const es = getNodeEditState(editor)+ const region = hit ? null : hitTestEditRegion(editor, cx, cy)+ if (es && (es.hoveredRegion ?? null) !== region) {+ es.hoveredRegion = region+ editor.requestRepaint()+ }return true}@@ -53,7 +62,7 @@ export function handleNodeEditPointerUp(drag: Ref<DragState | null>, editor: Edi}if (current.type === 'edit-node') {editor.setSnapGuides([])- finishSegmentClick(current, editor)+ finishPartClick(current, editor)const state = getCanvasNodeEditState(editor)if (state && current.origPositions.size === 1) {const [draggedIndex] = current.origPositions.keys()diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex 0ba9d2534..e2133947d 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -208,10 +208,10 @@ export interface DragEditNode {startY: numberorigPositions: Map<number, Vector>/**- * A selected segment that was pressed: releasing without a drag selects only it, or with Shift- * takes it out of the selection.+ * A selected segment or region that was pressed: releasing without a drag selects only it, or+ * with Shift takes it out of the selection.*/- segmentClick?: { segment: number; deselect: boolean }+ click?: { part: 'segment' | 'region'; index: number; deselect: boolean }}export interface DragEditHandle {diff --git a/packages/vue/src/shared/input/vector/hit-test.ts b/packages/vue/src/shared/input/vector/hit-test.tsindex 851f5bbe5..a6c1b6b65 100644--- a/packages/vue/src/shared/input/vector/hit-test.ts+++ b/packages/vue/src/shared/input/vector/hit-test.ts@@ -1,12 +1,13 @@import type { Editor } from '@open-pencil/core/editor'-import { nearestPointOnNetwork, vectorHandleParts } from '@open-pencil/core/vector'-import type { VectorSegment, VectorVertex } from '@open-pencil/scene-graph'+import { nearestPointOnNetwork, regionAtPoint, vectorHandleParts } from '@open-pencil/core/vector'+import type { VectorRegion, VectorSegment, VectorVertex } from '@open-pencil/scene-graph'import type { Rect } from '@open-pencil/scene-graph/primitives'export type NodeEditState = {nodeId: stringvertices: VectorVertex[]segments: VectorSegment[]+ regions: VectorRegion[]selectedVertexIndices: Set<number>selectedSegmentIndices: Set<number>selectedHandles: Set<number>@@ -14,6 +15,8 @@ export type NodeEditState = {segmentIndex: numbertangentField: 'tangentStart' | 'tangentEnd'} | null+ hoveredRegion?: number | null+ selectedRegions?: Set<number>}export function getNodeEditState(editor: Editor): NodeEditState | null {@@ -51,6 +54,27 @@ export function hitTestEditSegment(editor: Editor, cx: number, cy: number): numbreturn hit?.segmentIndex ?? null}+/**+ * How close, in screen pixels, a point or a segment keeps the pointer from a region, as in+ * Figma: a region under the pointer wins unless a point is within 4 px or a segment within 2.667 px.+ */+const REGION_POINT_CLEARANCE = 4+const REGION_SEGMENT_CLEARANCE = 8 / 3++/** The region of the path being edited under a canvas point, unless a point or segment is closer. */+export function hitTestEditRegion(editor: Editor, cx: number, cy: number): number | null {+ const es = getNodeEditState(editor)+ if (!es || es.regions.length === 0) return null+ const iz = 1 / editor.state.zoom+ if (es.vertices.some((v) => Math.hypot(cx - v.x, cy - v.y) <= REGION_POINT_CLEARANCE * iz)) {+ return null+ }+ const network = { vertices: es.vertices, segments: es.segments, regions: es.regions }+ if (nearestPointOnNetwork(cx, cy, network, REGION_SEGMENT_CLEARANCE * iz)) return null+ // Past the segment clearance the point is off every edge, so half of it bounds the curve error.+ return regionAtPoint(network, { x: cx, y: cy }, (REGION_SEGMENT_CLEARANCE * iz) / 2)+}+/** The points of the path being edited that lie inside a canvas rectangle. */export function editVerticesInRect(editor: Editor, rect: Rect): number[] {const es = getNodeEditState(editor)diff --git a/packages/vue/src/shared/input/vector/index.ts b/packages/vue/src/shared/input/vector/index.tsindex 1a9669687..1e911f014 100644--- a/packages/vue/src/shared/input/vector/index.ts+++ b/packages/vue/src/shared/input/vector/index.ts@@ -9,6 +9,7 @@ import {editVerticesInRect,getNodeEditState,hitTestEditHandle,+ hitTestEditRegion,hitTestEditSegment,hitTestEditVertex,isEndpoint,@@ -19,12 +20,13 @@ import { applyNodeEditSnap } from '#vue/shared/input/vector/snap'export {getNodeEditState,hitTestEditHandle,+ hitTestEditRegion,hitTestEditSegment,isEndpoint,NODE_HIT_THRESHOLD} from '#vue/shared/input/vector/hit-test'import type { Editor } from '@open-pencil/core/editor'-import { vectorHandleId } from '@open-pencil/core/vector'+import { regionVertexIndices, vectorHandleId } from '@open-pencil/core/vector'import type { Vector } from '@open-pencil/scene-graph/primitives'type NodeEditEditor = Partial<{@@ -59,34 +61,21 @@ export function handleNodeEditDown(const nodeEditEditor = editor as Editor & NodeEditEditorconst handleHit = hitTestEditHandle(editor, cx, cy)+ const ri = handleHit ? null : hitTestEditRegion(editor, cx, cy)+ if (!e.shiftKey && !pressesPickedRegion(es, ri)) es.selectedRegions = new Set()+if (handleHit) {- const key = vectorHandleId(handleHit.segmentIndex, handleHit.tangentField)+ pressHandle(es, handleHit, e.shiftKey, cx, cy, nodeEditEditor, setDrag)+ return+ }- if (e.shiftKey) {- const next = new Set(es.selectedHandles)- if (next.has(key)) next.delete(key)- else next.add(key)- es.selectedHandles = next- } else {- es.selectedVertexIndices = new Set()- es.selectedSegmentIndices = new Set()- es.selectedHandles = new Set([key])- }- nodeEditEditor.nodeEditPushHistory?.()- 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 }- })()- })+ // As in Figma, a press inside a region away from its points and segments picks the region:+ // its points are selected with it and drag with it. A press on a picked region keeps the+ // selection so all of it drags, as with segments.+ if (ri !== null) {+ const click = pickRegion(es, ri, e.shiftKey)+ editor.requestRepaint()+ startPointsDrag(es, regionPoints(es, ri), cx, cy, nodeEditEditor, setDrag, click)return}@@ -123,20 +112,10 @@ export function handleNodeEditDown(// selection so all of it drags; the click acts only on a release without a drag.const si = hitTestEditSegment(editor, cx, cy)if (si !== null) {- const wasSelected = es.selectedSegmentIndices.has(si)- es.selectedHandles = new Set()- if (!wasSelected) selectPressedSegment(es, si, e.shiftKey)+ const click = selectPressedSegment(es, si, e.shiftKey)editor.requestRepaint()const { start, end } = es.segments[si]- startPointsDrag(- es,- [start, end],- cx,- cy,- nodeEditEditor,- setDrag,- wasSelected ? { segment: si, deselect: e.shiftKey } : undefined- )+ startPointsDrag(es, [start, end], cx, cy, nodeEditEditor, setDrag, click)return}@@ -150,17 +129,105 @@ export function handleNodeEditDown(})}-/** Shift adds the pressed segment to the selection; otherwise it becomes the selection. */-function selectPressedSegment(es: NodeEditState, segmentIndex: number, add: boolean) {- if (!add) es.selectedVertexIndices = new Set()- es.selectedSegmentIndices = add+/**+ * Whether a press lands on a region already picked, which keeps the picked regions; any other+ * press without Shift picks something else, so they go.+ */+function pressesPickedRegion(es: NodeEditState, region: number | null) {+ return region !== null && Boolean(es.selectedRegions?.has(region))+}++/** Selects a pressed tangent handle, toggling it with Shift, and starts dragging it. */+function pressHandle(+ es: NodeEditState,+ handleHit: NonNullable<ReturnType<typeof hitTestEditHandle>>,+ shift: boolean,+ cx: number,+ cy: number,+ nodeEditEditor: NodeEditEditor,+ setDrag: (d: DragState) => void+) {+ const key = vectorHandleId(handleHit.segmentIndex, handleHit.tangentField)++ if (shift) {+ const next = new Set(es.selectedHandles)+ if (next.has(key)) next.delete(key)+ else next.add(key)+ es.selectedHandles = next+ } else {+ es.selectedVertexIndices = new Set()+ es.selectedSegmentIndices = new Set()+ es.selectedHandles = new Set([key])+ }+ nodeEditEditor.nodeEditPushHistory?.()+ 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 }+ })()+ })+}++/**+ * Selects a pressed segment: Shift adds it, otherwise it becomes the selection. A segment already+ * selected stays as it is, so all of the selection drags; the result is what a release without a+ * drag does to it then.+ */+function selectPressedSegment(+ es: NodeEditState,+ segmentIndex: number,+ shift: boolean+): DragEditNode['click'] {+ es.selectedHandles = new Set()+ if (es.selectedSegmentIndices.has(segmentIndex)) {+ return { part: 'segment', index: segmentIndex, deselect: shift }+ }+ if (!shift) es.selectedVertexIndices = new Set()+ es.selectedSegmentIndices = shift? new Set([...es.selectedSegmentIndices, segmentIndex]): new Set([segmentIndex])+ return undefined+}++function regionPoints(es: NodeEditState, regionIndex: number): number[] {+ return regionVertexIndices(+ { vertices: es.vertices, segments: es.segments, regions: es.regions },+ regionIndex+ )+}++/**+ * Picks a pressed region and its points: Shift adds them, otherwise they become the selection. A+ * region already picked stays as it is, so all of the selection drags; the result is what a+ * release without a drag does to it then.+ */+function pickRegion(es: NodeEditState, regionIndex: number, add: boolean): DragEditNode['click'] {+ es.selectedHandles = new Set()+ if (es.selectedRegions?.has(regionIndex)) {+ return { part: 'region', index: regionIndex, deselect: add }+ }+ const points = regionPoints(es, regionIndex)+ if (add) {+ es.selectedRegions = new Set([...(es.selectedRegions ?? new Set<number>()), regionIndex])+ es.selectedVertexIndices = new Set([...es.selectedVertexIndices, ...points])+ } else {+ es.selectedRegions = new Set([regionIndex])+ es.selectedVertexIndices = new Set(points)+ es.selectedSegmentIndices = new Set()+ }+ return undefined}/*** Drags the selected points and segments, and `pressed` with them, from where the pointer went- * down. `segmentClick` is what a release without a drag does to a selected segment.+ * down. `click` is what a release without a drag does to the selected part that was pressed.*/function startPointsDrag(es: NodeEditState,@@ -169,7 +236,7 @@ function startPointsDrag(cy: number,nodeEditEditor: NodeEditEditor,setDrag: (d: DragState) => void,- segmentClick?: DragEditNode['segmentClick']+ click?: DragEditNode['click']) {const segmentEnds = [...es.selectedSegmentIndices].flatMap((index) => {const segment = es.segments.at(index)@@ -180,22 +247,27 @@ function startPointsDrag(origPositions.set(index, { x: es.vertices[index].x, y: es.vertices[index].y })}nodeEditEditor.nodeEditPushHistory?.()- setDrag({ type: 'edit-node', startX: cx, startY: cy, origPositions, segmentClick })+ setDrag({ type: 'edit-node', startX: cx, startY: cy, origPositions, click })}/**- * A press on a selected segment that ends without moving anything: as in Figma, a click selects- * only that segment and a Shift-click takes it out of the selection.+ * A press on a selected segment or region that ends without moving anything: as in Figma, a click+ * selects only that part and a Shift-click takes it out of the selection.*/-export function finishSegmentClick(d: DragEditNode, editor: Editor) {+export function finishPartClick(d: DragEditNode, editor: Editor) {const es = getNodeEditState(editor)- if (!es || !d.segmentClick) return+ if (!es || !d.click) returnconst moved = [...d.origPositions].some(([index, orig]) => {const vertex = es.vertices.at(index)return vertex !== undefined && (vertex.x !== orig.x || vertex.y !== orig.y)})if (moved) return- const { segment, deselect } = d.segmentClick+ if (d.click.part === 'segment') clickSegment(es, d.click.index, d.click.deselect)+ else clickRegion(es, d.click.index, d.click.deselect)+ editor.requestRepaint()+}++function clickSegment(es: NodeEditState, segment: number, deselect: boolean) {if (deselect) {const next = new Set(es.selectedSegmentIndices)next.delete(segment)@@ -204,7 +276,23 @@ export function finishSegmentClick(d: DragEditNode, editor: Editor) {es.selectedVertexIndices = new Set()es.selectedSegmentIndices = new Set([segment])}- editor.requestRepaint()+}++/** A deselected region takes its points with it, except those another picked region shares. */+function clickRegion(es: NodeEditState, region: number, deselect: boolean) {+ if (!deselect) {+ es.selectedRegions = new Set([region])+ es.selectedVertexIndices = new Set(regionPoints(es, region))+ es.selectedSegmentIndices = new Set()+ return+ }+ const rest = [...(es.selectedRegions ?? [])].filter((index) => index !== region)+ const kept = new Set(rest.flatMap((index) => regionPoints(es, index)))+ const dropped = new Set(regionPoints(es, region).filter((index) => !kept.has(index)))+ es.selectedRegions = new Set(rest)+ es.selectedVertexIndices = new Set(+ [...es.selectedVertexIndices].filter((index) => !dropped.has(index))+ )}/** Selects the points inside the marquee and the segments between them, with what it started with. */diff --git a/packages/vue/tests/shared/input/vector/segments.test.ts b/packages/vue/tests/shared/input/vector/segments.test.tsindex 1b48bbebf..bf967daa3 100644--- a/packages/vue/tests/shared/input/vector/segments.test.ts+++ b/packages/vue/tests/shared/input/vector/segments.test.ts@@ -140,6 +140,107 @@ describe('editing a path: marquee', () => {})})+describe('editing a path: regions and segments', () => {+ /** The same path closed back to (0,0), filled as one region. */+ function setupFilled() {+ setup()+ const es = getNodeEditState(editor)+ if (!es) throw new Error('expected edit state')+ es.segments = [...es.segments, { start: 2, end: 0, tangentStart: zero, tangentEnd: zero }]+ es.regions = [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]+ es.selectedRegions = new Set()+ return es+ }++ test('picking a region replaces selected segments with the region and its points', () => {+ const es = setupFilled()+ press(50, 0)+ expect(selectedSegments()).toEqual([0])+ press(70, 30)+ expect([...(es.selectedRegions ?? [])]).toEqual([0])+ expect(selected()).toEqual([0, 1, 2])+ expect(selectedSegments()).toEqual([])+ })++ test('a press on a segment drops the picked region', () => {+ const es = setupFilled()+ press(70, 30)+ press(100, 50)+ expect([...(es.selectedRegions ?? [])]).toEqual([])+ expect(selectedSegments()).toEqual([1])+ })+})++// Figma desktop 126, a 260 × 200 shape of two rooms sharing the wall x = 130: a press on a picked+// room keeps both picked so a drag moves them together; a click narrows to that room and a+// Shift-click drops it.+describe('editing a path: pressing a picked region', () => {+ function setupRooms() {+ setup()+ const es = getNodeEditState(editor)+ if (!es) throw new Error('expected edit state')+ const line = (start: number, end: number) => ({+ start,+ end,+ tangentStart: zero,+ tangentEnd: zero+ })+ es.vertices = [+ { x: 0, y: 0 },+ { x: 130, y: 0 },+ { x: 260, y: 0 },+ { x: 260, y: 200 },+ { x: 130, y: 200 },+ { x: 0, y: 200 }+ ]+ es.segments = [+ line(0, 1),+ line(1, 4),+ line(4, 5),+ line(5, 0),+ line(1, 2),+ line(2, 3),+ line(3, 4)+ ]+ es.regions = [+ { windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] },+ { windingRule: 'NONZERO', loops: [[4, 5, 6, 1]] }+ ]+ es.selectedRegions = new Set()+ press(65, 100)+ press(195, 100, true)+ return es+ }++ function release(drag: DragState | null) {+ handleNodeEditPointerUp(ref(drag), editor)+ }++ test('a drag from one moves both and keeps both picked', () => {+ const es = setupRooms()+ const drag = press(65, 100)+ if (drag?.type !== 'edit-node') throw new Error('expected a point drag')+ handleNodeEditMove(drag, 65, 140, editor, false, false, false, true)+ release(drag)+ expect([...(es.selectedRegions ?? [])].sort()).toEqual([0, 1])+ expect(es.vertices.map((vertex) => vertex.y)).toEqual([40, 40, 40, 240, 240, 240])+ })++ test('a click narrows to the room clicked', () => {+ const es = setupRooms()+ release(press(65, 100))+ expect([...(es.selectedRegions ?? [])]).toEqual([0])+ expect(selected()).toEqual([0, 1, 4, 5])+ })++ test('a Shift-click drops the room and the points only it had', () => {+ const es = setupRooms()+ release(press(195, 100, true))+ expect([...(es.selectedRegions ?? [])]).toEqual([0])+ expect(selected()).toEqual([0, 1, 4, 5])+ })+})+describe('editing a path: pressing a selected segment', () => {function release(drag: DragState | null) {handleNodeEditPointerUp(ref(drag), editor)diff --git a/src/app/editor/vector/history.ts b/src/app/editor/vector/history.tsindex 4d6530eb7..a2b080507 100644--- a/src/app/editor/vector/history.ts+++ b/src/app/editor/vector/history.ts@@ -40,6 +40,7 @@ export function createVectorEditHistoryActions(editor: Editor, state: VectorEdit// indices may no longer exist in the restored geometryes.selectedVertexIndices = new Set()es.selectedSegmentIndices = new Set()+ es.selectedRegions = new Set()es.selectedHandles = new Set()es.hoveredHandleInfo = nulleditor.requestRender()diff --git a/src/app/editor/vector/lifecycle.ts b/src/app/editor/vector/lifecycle.tsindex 5296fde57..5f23dbc77 100644--- a/src/app/editor/vector/lifecycle.ts+++ b/src/app/editor/vector/lifecycle.ts@@ -86,7 +86,9 @@ export function createVectorEditLifecycle(editor: Editor, state: VectorEditStateselectedSegmentIndices: new Set(),draggedHandleInfo: null,selectedHandles: new Set(),- hoveredHandleInfo: null+ hoveredHandleInfo: null,+ hoveredRegion: null,+ selectedRegions: new Set()}editor.select([nodeId])diff --git a/src/app/editor/vector/network.ts b/src/app/editor/vector/network.tsindex 954c3b787..72b13dec2 100644--- a/src/app/editor/vector/network.ts+++ b/src/app/editor/vector/network.ts@@ -67,6 +67,7 @@ export function createVectorEditNetworkActions(setNodeEditNetwork(es, { vertices: nextVertices, segments: nextSegments, regions: [] })es.selectedVertexIndices = new Set([keepIndex])es.selectedSegmentIndices = new Set()+ es.selectedRegions = new Set()es.selectedHandles = new Set()editor.requestRender()}@@ -83,6 +84,7 @@ export function createVectorEditNetworkActions(setNodeEditNetwork(es, split.network)es.selectedVertexIndices = new Set([split.newVertexIndex])es.selectedSegmentIndices = new Set()+ es.selectedRegions = new Set()es.selectedHandles = new Set()editor.requestRender()return true@@ -98,6 +100,7 @@ export function createVectorEditNetworkActions(setNodeEditNetwork(es, next)es.selectedVertexIndices = new Set()es.selectedSegmentIndices = new Set()+ es.selectedRegions = new Set()es.selectedHandles = new Set()editor.requestRender()}diff --git a/src/app/editor/vector/selection.ts b/src/app/editor/vector/selection.tsindex 9090b232b..aad38e673 100644--- a/src/app/editor/vector/selection.ts+++ b/src/app/editor/vector/selection.ts@@ -25,6 +25,7 @@ export function createVectorEditSelectionActions(} else {es.selectedVertexIndices = new Set([vertexIndex])es.selectedSegmentIndices = new Set()+ es.selectedRegions = new Set()}editor.requestRepaint()}@@ -88,6 +89,7 @@ export function createVectorEditSelectionActions(setNodeEditNetwork(es, live)es.selectedVertexIndices = new Set()es.selectedSegmentIndices = new Set()+ es.selectedRegions = new Set()es.selectedHandles = new Set()editor.requestRender()}@@ -102,6 +104,7 @@ export function createVectorEditSelectionActions(setNodeEditNetwork(es, next)es.selectedHandles = new Set()es.selectedSegmentIndices = new Set()+ es.selectedRegions = new Set()es.selectedVertexIndices = new Set([vertexIndex])editor.requestRender()}diff --git a/src/app/editor/vector/types.ts b/src/app/editor/vector/types.tsindex eb3591dd4..d21ee0119 100644--- a/src/app/editor/vector/types.ts+++ b/src/app/editor/vector/types.ts@@ -34,6 +34,10 @@ export type NodeEditState = {segmentIndex: numbertangentField: 'tangentStart' | 'tangentEnd'} | null+ /** The region under the pointer, hatched as in Figma. */+ hoveredRegion: number | null+ /** Regions picked by clicking inside them; their points are selected with them. */+ selectedRegions: Set<number>}export type VectorEditState = EditorState & { nodeEditState: NodeEditState | null }diff --git a/tests/e2e/canvas/vector/regions.spec.ts b/tests/e2e/canvas/vector/regions.spec.tsnew file mode 100644index 000000000..606ca2d36--- /dev/null+++ b/tests/e2e/canvas/vector/regions.spec.ts@@ -0,0 +1,68 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'++const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')++// Figma desktop 126: in vector edit mode the region under the pointer is hatched with 45° lines,+// and so is a picked one.+test('vector edit mode hatches the hovered and the picked region', async () => {+ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const line = (start: number, end: number) => ({+ start,+ end,+ tangentStart: { x: 0, y: 0 },+ tangentEnd: { x: 0, y: 0 }+ })+ const vector = store.graph.createNode('VECTOR', store.state.currentPageId, {+ name: 'Two rooms',+ x: 100,+ y: 80,+ width: 260,+ height: 200,+ fills: [+ { type: 'SOLID', color: { r: 0.64, g: 0.74, b: 0.97, a: 1 }, opacity: 1, visible: true }+ ],+ vectorNetwork: {+ vertices: [+ { x: 0, y: 0 },+ { x: 130, y: 0 },+ { x: 260, y: 0 },+ { x: 260, y: 200 },+ { x: 130, y: 200 },+ { x: 0, y: 200 }+ ],+ segments: [+ line(0, 1),+ line(1, 4),+ line(4, 5),+ line(5, 0),+ line(1, 2),+ line(2, 3),+ line(3, 4)+ ],+ regions: [+ { windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] },+ { windingRule: 'NONZERO', loops: [[4, 5, 6, 1]] }+ ]+ }+ })+ store.enterNodeEditMode(vector.id)+ })+ await editor.canvas.waitForRender()+ const box = await editor.canvas.canvas.boundingBox()+ if (!box) throw new Error('Canvas bounds unavailable')++ // Pick the left room, then hover the right one.+ await editor.page.mouse.click(box.x + 165, box.y + 180)+ await editor.page.mouse.move(box.x + 295, box.y + 180)+ await editor.canvas.waitForRender()++ const regions = await editor.page.evaluate(() => {+ const edit = window.openPencil?.getStore?.().getNodeEditState?.()+ return { picked: [...(edit?.selectedRegions ?? [])], hovered: edit?.hoveredRegion ?? null }+ })+ expect(regions).toEqual({ picked: [0], hovered: 1 })+ editor.canvas.assertNoErrors()+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('region-hatch.png')+})diff --git a/tests/e2e/canvas/vector/regions.spec.ts-snapshots/region-hatch-openpencil-darwin.png b/tests/e2e/canvas/vector/regions.spec.ts-snapshots/region-hatch-openpencil-darwin.pngnew file mode 100644index 000000000..3b3ef9e09Binary files /dev/null and b/tests/e2e/canvas/vector/regions.spec.ts-snapshots/region-hatch-openpencil-darwin.png differdiff --git a/tests/engine/vue/input/node-edit-snap.test.ts b/tests/engine/vue/input/node-edit-snap.test.tsindex 7a859485e..a00cc050d 100644--- a/tests/engine/vue/input/node-edit-snap.test.ts+++ b/tests/engine/vue/input/node-edit-snap.test.ts@@ -39,6 +39,7 @@ describe('vector edit snapping', () => {nodeId: vector.id,vertices: [{ x: 10, y: 20 }],segments: [],+ regions: [],selectedVertexIndices: new Set([0]),selectedSegmentIndices: new Set<number>(),selectedHandles: new Set<number>(),@@ -80,6 +81,7 @@ describe('vector edit snapping', () => {{ x: 80, y: 60 }],segments: [],+ regions: [],selectedVertexIndices: new Set([0]),selectedSegmentIndices: new Set<number>(),selectedHandles: new Set<number>(),@@ -122,6 +124,7 @@ describe('vector edit snapping', () => {{ x: 80, y: 60 }],segments: [],+ regions: [],selectedVertexIndices: new Set([0]),selectedSegmentIndices: new Set<number>(),selectedHandles: new Set<number>(),@@ -160,6 +163,7 @@ describe('vector edit snapping', () => {{ x: 80, y: 60 }],segments: [],+ regions: [],selectedVertexIndices: new Set([0]),selectedSegmentIndices: new Set<number>(),selectedHandles: new Set<number>(),@@ -198,6 +202,7 @@ describe('vector edit snapping', () => {nodeId: vector.id,vertices: [{ x: 10.2, y: 20.4 }],segments: [],+ regions: [],selectedVertexIndices: new Set([0]),selectedSegmentIndices: new Set<number>(),selectedHandles: new Set<number>(),