Skip to content

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

fix(scene-graph): hit shapes on what their paints draw, as Figma does (#1685)

Danila Poyarkov078ca1f8da9d
diff --git a/changes/1685/breaking.md b/changes/1685/breaking.md
new file mode 100644
index 000000000..d4688820c
--- /dev/null
+++ b/changes/1685/breaking.md
@@ -0,0 +1 @@
+- `@open-pencil/core/vector` no longer exports `evalCubic`, and `@open-pencil/scene-graph/geometry` no longer exports `geometryCommandCoordCount`; use `cubicPoint` and `readGeometryBlob` from `@open-pencil/scene-graph/geometry` (#1685).
diff --git a/changes/1685/fixed.md b/changes/1685/fixed.md
new file mode 100644
index 000000000..c8a76659f
--- /dev/null
+++ b/changes/1685/fixed.md
@@ -0,0 +1 @@
+- Clicks and hover select a shape only where its fill or stroke draws, as in Figma: an unfilled line or curve is picked by its stroke, a filled ellipse or rounded rectangle by its outline, and a layer whose paints show nothing lets clicks through (#1685).
diff --git a/packages/core/src/canvas/node-edit-overlay.ts b/packages/core/src/canvas/node-edit-overlay.ts
index 1a8c18c63..93434e638 100644
--- a/packages/core/src/canvas/node-edit-overlay.ts
+++ b/packages/core/src/canvas/node-edit-overlay.ts
@@ -7,6 +7,7 @@ import type {
SceneGraph
} from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import { cubicPoint } from '@open-pencil/scene-graph/geometry'
import Matrix from '@open-pencil/scene-graph/matrix'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import { transformVectorNetwork } from '@open-pencil/scene-graph/vector-network'
@@ -18,7 +19,7 @@ import {
vectorHandleParts,
vectorNetworkToPath
} from '#core/vector'
-import { evalCubic, segmentToAbsolute } from '#core/vector/curve-math'
+import { segmentToAbsolute } from '#core/vector/curve-math'
import { drawRegionHatch } from './region-hatch'
import type { SkiaRenderer, RenderOverlays } from './renderer'
@@ -312,7 +313,7 @@ function drawSelectedSegments(
canvas.drawPath(path, segmentSelectedPaint)
path.delete()
- const mid = evalCubic(s0.x, s0.y, s1.x, s1.y, s2.x, s2.y, s3.x, s3.y, 0.5)
+ const mid = cubicPoint(s0, s1, s2, s3, 0.5)
canvas.drawCircle(mid.x, mid.y, PEN_HANDLE_RADIUS, r.penVertexFill)
canvas.drawCircle(mid.x, mid.y, PEN_HANDLE_RADIUS, vertexStroke1px)
}
diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.ts
index 1a66f034a..3ab95b633 100644
--- a/packages/core/src/io/formats/svg/paths.ts
+++ b/packages/core/src/io/formats/svg/paths.ts
@@ -1,7 +1,11 @@
import { compact } from 'es-toolkit/array'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { polygonVertices } from '@open-pencil/scene-graph/geometry'
+import {
+ GeometryCommand,
+ polygonVertices,
+ readGeometryBlob
+} from '@open-pencil/scene-graph/geometry'
import { outlineSVGPath, polygonOutline } from '@open-pencil/scene-graph/polygon'
import { shapeWithTextGeometry } from '@open-pencil/scene-graph/shape-with-text'
import { vectorNetworkToSVGPaths } from '@open-pencil/scene-graph/vector-network'
@@ -10,12 +14,6 @@ import { traceSmoothRect, type SmoothCornerSink } from '#core/canvas/paths/smoot
import { nodeHasRadius } from '#core/canvas/shapes'
import type { PathSink } from '#core/vector/path-helpers'
-const CMD_CLOSE = 0
-const CMD_MOVE_TO = 1
-const CMD_LINE_TO = 2
-const CMD_QUAD_TO = 3
-const CMD_CUBIC_TO = 4
-
export function round(n: number, decimals = 2): number {
const factor = 10 ** decimals
return Math.round(n * factor) / factor
@@ -26,56 +24,18 @@ function coordinate(value: number, decimals: number | null): number {
}
export function geometryBlobToSVGPath(blob: Uint8Array, decimals: number | null = 2): string {
- if (blob.length === 0) return ''
- const dv = new DataView(blob.buffer, blob.byteOffset, blob.byteLength)
- let o = 0
const parts: string[] = []
-
- while (o < blob.length) {
- const cmd = blob[o++]
- switch (cmd) {
- case CMD_CLOSE:
- parts.push('Z')
- break
- case CMD_MOVE_TO: {
- const x = coordinate(dv.getFloat32(o, true), decimals)
- const y = coordinate(dv.getFloat32(o + 4, true), decimals)
- o += 8
- parts.push(`M${x} ${y}`)
- break
- }
- case CMD_LINE_TO: {
- const x = coordinate(dv.getFloat32(o, true), decimals)
- const y = coordinate(dv.getFloat32(o + 4, true), decimals)
- o += 8
- parts.push(`L${x} ${y}`)
- break
- }
- case CMD_QUAD_TO: {
- const x1 = coordinate(dv.getFloat32(o, true), decimals)
- const y1 = coordinate(dv.getFloat32(o + 4, true), decimals)
- const x = coordinate(dv.getFloat32(o + 8, true), decimals)
- const y = coordinate(dv.getFloat32(o + 12, true), decimals)
- o += 16
- parts.push(`Q${x1} ${y1} ${x} ${y}`)
- break
- }
- case CMD_CUBIC_TO: {
- const x1 = coordinate(dv.getFloat32(o, true), decimals)
- const y1 = coordinate(dv.getFloat32(o + 4, true), decimals)
- const x2 = coordinate(dv.getFloat32(o + 8, true), decimals)
- const y2 = coordinate(dv.getFloat32(o + 12, true), decimals)
- const x = coordinate(dv.getFloat32(o + 16, true), decimals)
- const y = coordinate(dv.getFloat32(o + 20, true), decimals)
- o += 24
- parts.push(`C${x1} ${y1} ${x2} ${y2} ${x} ${y}`)
- break
- }
- default:
- return parts.join('')
- }
+ const letters: Record<GeometryCommand, string> = {
+ [GeometryCommand.CLOSE]: 'Z',
+ [GeometryCommand.MOVE]: 'M',
+ [GeometryCommand.LINE]: 'L',
+ [GeometryCommand.QUAD]: 'Q',
+ [GeometryCommand.CUBIC]: 'C'
}
-
+ readGeometryBlob(blob, (command, coords) => {
+ const values = coords.map((value) => coordinate(value, decimals))
+ parts.push(`${letters[command]}${values.join(' ')}`)
+ })
return parts.join('')
}
diff --git a/packages/core/src/text/ink.ts b/packages/core/src/text/ink.ts
index 8cb4fc615..3efd676bb 100644
--- a/packages/core/src/text/ink.ts
+++ b/packages/core/src/text/ink.ts
@@ -1,4 +1,4 @@
-import { geometryCommandCoordCount } from '@open-pencil/scene-graph/geometry'
+import { cubicPoint, GeometryCommand, readGeometryBlob } from '@open-pencil/scene-graph/geometry'
import type { OutlineCommand } from '#core/text/font/glyphs'
@@ -50,15 +50,13 @@ class BandInk {
}
cubicTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void {
- const { x: x0, y: y0 } = this
+ const start = { x: this.x, y: this.y }
+ const c1 = { x: x1, y: y1 }
+ const c2 = { x: x2, y: y2 }
+ const end = { x, y }
for (let step = 1; step <= CURVE_STEPS; step++) {
- const t = step / CURVE_STEPS
- const u = 1 - t
- const a = u * u * u
- const b = 3 * u * u * t
- const c = 3 * u * t * t
- const d = t * t * t
- this.lineTo(a * x0 + b * x1 + c * x2 + d * x, a * y0 + b * y1 + c * y2 + d * y)
+ const point = cubicPoint(start, c1, c2, end, step / CURVE_STEPS)
+ this.lineTo(point.x, point.y)
}
}
@@ -120,31 +118,25 @@ export function savedGlyphInk(
bottom: number
): InkSpan | null {
const ink = new BandInk(top, bottom)
- const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength)
const sx = glyph.fontSize * (glyph.scaleX ?? 1)
const sy = glyph.fontSize * (glyph.scaleY ?? 1)
const points: number[] = []
let startX = 0
let startY = 0
- let offset = 0
- while (offset < blob.length) {
- const command = blob[offset++]
- const count = geometryCommandCoordCount(command)
- if (count === null || offset + count * 8 > blob.length) break
+ readGeometryBlob(blob, (command, coords) => {
points.length = 0
- for (let index = 0; index < count; index++) {
- points.push(glyph.x + view.getFloat32(offset, true) * sx)
- points.push(glyph.y - view.getFloat32(offset + 4, true) * sy)
- offset += 8
+ for (let index = 0; index < coords.length; index += 2) {
+ points.push(glyph.x + coords[index] * sx, glyph.y - coords[index + 1] * sy)
}
- if (command === 0) ink.lineTo(startX, startY)
- else if (command === 1) {
+ if (command === GeometryCommand.CLOSE) ink.lineTo(startX, startY)
+ else if (command === GeometryCommand.MOVE) {
ink.moveTo(points[0], points[1])
startX = points[0]
startY = points[1]
- } else if (command === 2) ink.lineTo(points[0], points[1])
- else if (command === 3) ink.quadTo(points[0], points[1], points[2], points[3])
+ } else if (command === GeometryCommand.LINE) ink.lineTo(points[0], points[1])
+ else if (command === GeometryCommand.QUAD)
+ ink.quadTo(points[0], points[1], points[2], points[3])
else ink.cubicTo(points[0], points[1], points[2], points[3], points[4], points[5])
- }
+ })
return ink.span()
}
diff --git a/packages/core/src/text/path/sampling.ts b/packages/core/src/text/path/sampling.ts
index 658005b12..61a2065d0 100644
--- a/packages/core/src/text/path/sampling.ts
+++ b/packages/core/src/text/path/sampling.ts
@@ -1,6 +1,7 @@
import { clamp } from 'es-toolkit'
import type { TextPathData } from '@open-pencil/scene-graph'
+import { cubicPoint } from '@open-pencil/scene-graph/geometry'
import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
interface Cubic {
@@ -60,18 +61,6 @@ function pathCurves(data: TextPathData, box: Rect): Cubic[] | null {
return curves.length > 0 ? curves : null
}
-function cubicPoint({ p0, p1, p2, p3 }: Cubic, t: number): Vector {
- const u = 1 - t
- const a = u * u * u
- const b = 3 * u * u * t
- const c = 3 * u * t * t
- const d = t * t * t
- return {
- x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
- y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
- }
-}
-
function cubicDerivative({ p0, p1, p2, p3 }: Cubic, t: number): Vector {
const u = 1 - t
const a = 3 * u * u
@@ -113,7 +102,7 @@ export function sampleTextPath(data: TextPathData, box: Rect): SampledPath | nul
for (const [curve, cubic] of curves.entries()) {
for (let step = 0; step <= steps[curve]; step++) {
const t = step / steps[curve]
- const point = cubicPoint(cubic, t)
+ const point = cubicPoint(cubic.p0, cubic.p1, cubic.p2, cubic.p3, t)
// A segment that does not start where the last one ended jumps there without adding length.
if (step > 0) length += Math.hypot(point.x - xs[index - 1], point.y - ys[index - 1])
xs[index] = point.x
@@ -147,7 +136,7 @@ export function pointAtArc(path: SampledPath, sIn: number): PathPoint {
const sameCurve = curveIndex[lo] === curveIndex[hi]
const curve = path.curves[sameCurve ? curveIndex[lo] : curveIndex[hi]]
const t = sameCurve && span > 0 ? ts[lo] + ((ts[hi] - ts[lo]) * (s - cum[lo])) / span : ts[hi]
- const point = cubicPoint(curve, t)
+ const point = cubicPoint(curve.p0, curve.p1, curve.p2, curve.p3, t)
// A straight segment with no handles has no derivative at its ends; take the samples' direction.
let { x: dx, y: dy } = cubicDerivative(curve, t)
diff --git a/packages/core/src/vector/bezier.ts b/packages/core/src/vector/bezier.ts
index 425adf3b1..b6b1e427b 100644
--- a/packages/core/src/vector/bezier.ts
+++ b/packages/core/src/vector/bezier.ts
@@ -1,9 +1,10 @@
-import { evalCubic, isLineSegment, segmentToAbsolute, splitCubicAt } from './curve-math'
+import { cubicPoint } from '@open-pencil/scene-graph/geometry'
+
+import { isLineSegment, segmentToAbsolute, splitCubicAt } from './curve-math'
import { reindexRegionLoops, remapRegions } from './regions'
export {
computeAccurateBounds,
cubicExtrema,
- evalCubic,
isLineSegment,
nearestPointOnCubic,
nearestPointOnNetwork,
@@ -165,15 +166,11 @@ function buildMergedSegmentForRemovedVertex(
const scaledTS: Vector = { x: dirA.x * scaleA, y: dirA.y * scaleA }
const scaledTE: Vector = { x: dirB.x * scaleB, y: dirB.y * scaleB }
- const ptScaled = evalCubic(
- vA.x,
- vA.y,
- vA.x + scaledTS.x,
- vA.y + scaledTS.y,
- vB.x + scaledTE.x,
- vB.y + scaledTE.y,
- vB.x,
- vB.y,
+ const ptScaled = cubicPoint(
+ vA,
+ { x: vA.x + scaledTS.x, y: vA.y + scaledTS.y },
+ { x: vB.x + scaledTE.x, y: vB.y + scaledTE.y },
+ vB,
t
)
const scaledDev = Math.hypot(ptScaled.x - vR.x, ptScaled.y - vR.y)
diff --git a/packages/core/src/vector/curve-math.ts b/packages/core/src/vector/curve-math.ts
index 6e0555b05..61df5674f 100644
--- a/packages/core/src/vector/curve-math.ts
+++ b/packages/core/src/vector/curve-math.ts
@@ -1,4 +1,5 @@
import type { VectorNetwork, VectorSegment } from '@open-pencil/scene-graph'
+import { cubicPoint } from '@open-pencil/scene-graph/geometry'
import type { Vector, Rect } from '@open-pencil/scene-graph/primitives'
export interface CubicPoints {
@@ -23,31 +24,6 @@ export interface NetworkNearestResult extends NearestResult {
// De Casteljau evaluation
// ---------------------------------------------------------------------------
-/** Evaluate a cubic bezier at parameter t (0..1). */
-export function evalCubic(
- p0x: number,
- p0y: number,
- p1x: number,
- p1y: number,
- p2x: number,
- p2y: number,
- p3x: number,
- p3y: number,
- t: number
-): Vector {
- const mt = 1 - t
- const mt2 = mt * mt
- const t2 = t * t
- const a = mt2 * mt
- const b = 3 * mt2 * t
- const c = 3 * mt * t2
- const d = t2 * t
- return {
- x: a * p0x + b * p1x + c * p2x + d * p3x,
- y: a * p0y + b * p1y + c * p2y + d * p3y
- }
-}
-
// ---------------------------------------------------------------------------
// Curve splitting (De Casteljau subdivision)
// ---------------------------------------------------------------------------
@@ -190,13 +166,13 @@ export function computeAccurateBounds(network: VectorNetwork): Rect {
// X extrema
for (const t of cubicExtrema(p0.x, cp1.x, cp2.x, p3.x)) {
- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)
+ const pt = cubicPoint(p0, cp1, cp2, p3, t)
update(pt.x, pt.y)
}
// Y extrema
for (const t of cubicExtrema(p0.y, cp1.y, cp2.y, p3.y)) {
- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)
+ const pt = cubicPoint(p0, cp1, cp2, p3, t)
update(pt.x, pt.y)
}
}
@@ -227,7 +203,7 @@ export function nearestPointOnCubic(
// Coarse sampling
for (let i = 0; i <= coarseSamples; i++) {
const t = i / coarseSamples
- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)
+ const pt = cubicPoint(p0, cp1, cp2, p3, t)
const dx = pt.x - px
const dy = pt.y - py
const d = dx * dx + dy * dy
@@ -248,7 +224,7 @@ export function nearestPointOnCubic(
for (let i = 0; i <= 4; i++) {
const t = lo + step * i
- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)
+ const pt = cubicPoint(p0, cp1, cp2, p3, t)
const dx = pt.x - px
const dy = pt.y - py
const d = dx * dx + dy * dy
@@ -264,7 +240,7 @@ export function nearestPointOnCubic(
hi = Math.min(1, bestT + step)
}
- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, bestT)
+ const pt = cubicPoint(p0, cp1, cp2, p3, bestT)
return { t: bestT, x: pt.x, y: pt.y, distance: Math.sqrt(bestDist) }
}
diff --git a/packages/core/src/vector/index.ts b/packages/core/src/vector/index.ts
index 5eb810705..9729cfc87 100644
--- a/packages/core/src/vector/index.ts
+++ b/packages/core/src/vector/index.ts
@@ -18,6 +18,7 @@ export {
import type { CanvasKit, Path } from 'canvaskit-wasm'
import type { VectorNetwork, WindingRule } from '@open-pencil/scene-graph'
+import { GeometryCommand, readGeometryBlob } from '@open-pencil/scene-graph/geometry'
import { addLoopToPath, addOpenSegmentsToPath } from './path-helpers'
export { vectorNetworkToCenterlinePath, fitCircleArc, isClosedThinCrescent } from './centerline'
@@ -70,12 +71,6 @@ export function vectorNetworkToPath(
return [path.detachAndDelete()]
}
-const CMD_CLOSE = 0
-const CMD_MOVE_TO = 1
-const CMD_LINE_TO = 2
-const CMD_QUAD_TO = 3
-const CMD_CUBIC_TO = 4
-
export function geometryBlobToPath(
ck: CanvasKit,
blob: Uint8Array,
@@ -83,61 +78,19 @@ export function geometryBlobToPath(
): Path {
const path = new ck.PathBuilder()
if (!(blob.buffer instanceof ArrayBuffer)) return path.detachAndDelete()
- const dv = new DataView(blob.buffer, blob.byteOffset, blob.byteLength)
- let o = 0
-
- while (o < blob.length) {
- const cmd = blob[o++]
- switch (cmd) {
- case CMD_CLOSE:
- path.close()
- break
- case CMD_MOVE_TO: {
- const x = dv.getFloat32(o, true)
- const y = dv.getFloat32(o + 4, true)
- o += 8
- path.moveTo(x, y)
- break
- }
- case CMD_LINE_TO: {
- const x = dv.getFloat32(o, true)
- const y = dv.getFloat32(o + 4, true)
- o += 8
- path.lineTo(x, y)
- break
- }
- case CMD_QUAD_TO: {
- const x1 = dv.getFloat32(o, true)
- const y1 = dv.getFloat32(o + 4, true)
- const x = dv.getFloat32(o + 8, true)
- const y = dv.getFloat32(o + 12, true)
- o += 16
- path.quadTo(x1, y1, x, y)
- break
- }
- case CMD_CUBIC_TO: {
- const x1 = dv.getFloat32(o, true)
- const y1 = dv.getFloat32(o + 4, true)
- const x2 = dv.getFloat32(o + 8, true)
- const y2 = dv.getFloat32(o + 12, true)
- const x = dv.getFloat32(o + 16, true)
- const y = dv.getFloat32(o + 20, true)
- o += 24
- path.cubicTo(x1, y1, x2, y2, x, y)
- break
- }
- default:
- return path.detachAndDelete()
- }
- }
-
+ readGeometryBlob(blob, (command, c) => {
+ if (command === GeometryCommand.CLOSE) path.close()
+ else if (command === GeometryCommand.MOVE) path.moveTo(c[0], c[1])
+ else if (command === GeometryCommand.LINE) path.lineTo(c[0], c[1])
+ else if (command === GeometryCommand.QUAD) path.quadTo(c[0], c[1], c[2], c[3])
+ else path.cubicTo(c[0], c[1], c[2], c[3], c[4], c[5])
+ })
const result = path.detachAndDelete()
result.setFillType(fillType(ck, windingRule))
return result
}
export {
cubicExtrema,
- evalCubic,
isLineSegment,
nearestPointOnCubic,
segmentToAbsolute,
diff --git a/packages/core/src/vector/region-hit.ts b/packages/core/src/vector/region-hit.ts
index fca0ebc93..86d14ba0f 100644
--- a/packages/core/src/vector/region-hit.ts
+++ b/packages/core/src/vector/region-hit.ts
@@ -1,97 +1,9 @@
import type { VectorNetwork } from '@open-pencil/scene-graph'
+import { containsByWinding, loopPoints } from '@open-pencil/scene-graph/outline'
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
@@ -106,10 +18,9 @@ export function regionAtPoint(
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
+ const region = network.regions[index]
+ const loops = region.loops.map((loop) => loopPoints(network, loop, tolerance))
+ if (containsByWinding(loops, region.windingRule, point)) return index
}
return null
}
diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.json
index d827bdac7..99e8e1069 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -224,6 +224,12 @@
"import": "./dist/order-keys.js",
"default": "./dist/order-keys.js"
},
+ "./outline": {
+ "types": "./dist/outline/index.d.ts",
+ "bun": "./src/outline/index.ts",
+ "import": "./dist/outline/index.js",
+ "default": "./dist/outline/index.js"
+ },
"./paints": {
"types": "./dist/paints/index.d.ts",
"bun": "./src/paints/index.ts",
diff --git a/packages/scene-graph/src/arrow-caps.ts b/packages/scene-graph/src/arrow-caps.ts
index 610d0bc88..6236082d4 100644
--- a/packages/scene-graph/src/arrow-caps.ts
+++ b/packages/scene-graph/src/arrow-caps.ts
@@ -1,3 +1,4 @@
+import { cubicPoint } from './cubic'
import type { Vector } from './primitives'
import type { Stroke, StrokeCap, VectorNetwork } from './types'
@@ -256,11 +257,7 @@ export function trimArrowShafts(
type Cubic = [Vector, Vector, Vector, Vector]
function cubicAt([a, b, c, d]: Cubic, t: number): Vector {
- const u = 1 - t
- return {
- x: u * u * u * a.x + 3 * u * u * t * b.x + 3 * u * t * t * c.x + t * t * t * d.x,
- y: u * u * u * a.y + 3 * u * u * t * b.y + 3 * u * t * t * c.y + t * t * t * d.y
- }
+ return cubicPoint(a, b, c, d, t)
}
function lerp(a: Vector, b: Vector, t: number): Vector {
diff --git a/packages/scene-graph/src/connectors/hit.ts b/packages/scene-graph/src/connectors/hit.ts
index 8d8fec2b9..b61207365 100644
--- a/packages/scene-graph/src/connectors/hit.ts
+++ b/packages/scene-graph/src/connectors/hit.ts
@@ -1,7 +1,7 @@
import { getWorldMatrix } from '../coordinate'
import type { SceneGraph } from '../graph'
import Matrix from '../matrix'
-import type { Vector } from '../primitives'
+import { distanceToSegment } from '../outline/point'
import type { SceneNode } from '../types'
import { isStraight, pointAt, type ConnectorPiece } from './pieces'
import { connectorSublayers } from './sublayers'
@@ -11,17 +11,6 @@ const CONNECTOR_HIT_SLOP = 4
/** Points sampled along a curved segment to measure distance to it. */
const CURVE_SAMPLES = 24
-function distanceToSegment(p: Vector, a: Vector, b: Vector): number {
- const dx = b.x - a.x
- const dy = b.y - a.y
- const lengthSquared = dx * dx + dy * dy
- const t =
- lengthSquared === 0
- ? 0
- : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSquared))
- return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))
-}
-
/**
* Whether a canvas point lands on a connector's line: within half its stroke and a few units of
* slop, plus `pad`. A connector is picked by its line, not by the box around its route.
diff --git a/packages/scene-graph/src/connectors/pieces.ts b/packages/scene-graph/src/connectors/pieces.ts
index b9fccc6d0..416b0782e 100644
--- a/packages/scene-graph/src/connectors/pieces.ts
+++ b/packages/scene-graph/src/connectors/pieces.ts
@@ -1,3 +1,4 @@
+import { cubicPoint } from '../cubic'
import { computeBounds } from '../geometry'
import type { Rect, Vector } from '../primitives'
import type { StrokeCap, VectorNetwork } from '../types'
@@ -47,11 +48,7 @@ export function pointAt(piece: ConnectorPiece, t: number): Vector {
const { from: a, to: b } = piece
if (isStraight(piece)) return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }
const [c1, c2] = controls(piece)
- const u = 1 - t
- return {
- x: u * u * u * a.x + 3 * u * u * t * c1.x + 3 * u * t * t * c2.x + t * t * t * b.x,
- y: u * u * u * a.y + 3 * u * u * t * c1.y + 3 * u * t * t * c2.y + t * t * t * b.y
- }
+ return cubicPoint(a, c1, c2, b, t)
}
function derivativeAt(piece: ConnectorPiece, t: number): Vector {
diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.ts
index ee5a18153..98789f6df 100644
--- a/packages/scene-graph/src/copy.ts
+++ b/packages/scene-graph/src/copy.ts
@@ -8,7 +8,7 @@
* no shared references between source and copy.
*/
-import { geometryCommandCoordCount } from './geometry'
+import { readGeometryBlob } from './geometry'
import { cloneInstanceOverrideState } from './instances/overrides'
import { createDefaultSourceMetadata } from './node-defaults'
import type {
@@ -159,21 +159,15 @@ export function transformGeometryBlob(
ty = 0
): Uint8Array {
const out = blob.slice()
- const dv = new DataView(out.buffer, out.byteOffset, out.byteLength)
- let offset = 0
- while (offset < out.length) {
- const command = out[offset++]
- const coords = geometryCommandCoordCount(command)
- if (coords == null) break
- for (let i = 0; i < coords; i++) {
- if (offset + 8 > out.length) break
- const x = dv.getFloat32(offset, true)
- const y = dv.getFloat32(offset + 4, true)
- dv.setFloat32(offset, m00 * x + m01 * y + tx, true)
- dv.setFloat32(offset + 4, m10 * x + m11 * y + ty, true)
- offset += 8
+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength)
+ readGeometryBlob(out, (_, coords, offset) => {
+ for (let i = 0; i < coords.length; i += 2) {
+ const x = coords[i]
+ const y = coords[i + 1]
+ view.setFloat32(offset + i * 4, m00 * x + m01 * y + tx, true)
+ view.setFloat32(offset + i * 4 + 4, m10 * x + m11 * y + ty, true)
}
- }
+ })
return out
}
diff --git a/packages/scene-graph/src/cubic.ts b/packages/scene-graph/src/cubic.ts
new file mode 100644
index 000000000..7addaf387
--- /dev/null
+++ b/packages/scene-graph/src/cubic.ts
@@ -0,0 +1,14 @@
+import type { Vector } from './primitives'
+
+/** The point at `t` along the cubic from `p0` to `p3` with control points `p1` and `p2`. */
+export function cubicPoint(p0: Vector, p1: Vector, p2: Vector, p3: Vector, t: number): Vector {
+ const u = 1 - t
+ const a = u * u * u
+ const b = 3 * u * u * t
+ const c = 3 * u * t * t
+ const d = t * t * t
+ return {
+ x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
+ y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
+ }
+}
diff --git a/packages/scene-graph/src/geometry.ts b/packages/scene-graph/src/geometry.ts
index d5e95d202..cc7537bcf 100644
--- a/packages/scene-graph/src/geometry.ts
+++ b/packages/scene-graph/src/geometry.ts
@@ -3,6 +3,8 @@ import type { Rect, Vector } from './primitives'
import { textLinesOverflow } from './text/overflow'
import type { Effect, Stroke, StrokeCap, StrokeJoin, VectorNetwork } from './types'
+export { cubicPoint } from './cubic'
+
export function degToRad(degrees: number): number {
return (degrees * Math.PI) / 180
}
@@ -328,38 +330,54 @@ export function intersectVisualBounds(a: VisualBounds, b: VisualBounds): VisualB
return minX < maxX && minY < maxY ? { minX, minY, maxX, maxY } : null
}
+/** The path commands of a Figma geometry blob, by their byte code. */
+export const GeometryCommand = { CLOSE: 0, MOVE: 1, LINE: 2, QUAD: 3, CUBIC: 4 } as const
+export type GeometryCommand = (typeof GeometryCommand)[keyof typeof GeometryCommand]
+
/**
- * Coordinate pairs per path blob command: 0=close, 1=move, 2=line,
- * 3=quad (glyph-derived blobs are quad-heavy), 4=cubic. Unknown → null so
- * walkers stop instead of desyncing into coordinate bytes.
+ * Coordinate pairs per command: glyph-derived blobs are quad-heavy, so every code needs its
+ * count. Unknown codes are null, so readers stop instead of desyncing into coordinate bytes.
*/
-export function geometryCommandCoordCount(command: number): number | null {
- if (command === 0) return 0
- if (command === 1 || command === 2) return 1
- if (command === 3) return 2
- if (command === 4) return 3
+function commandCoordCount(command: number): number | null {
+ if (command === GeometryCommand.CLOSE) return 0
+ if (command === GeometryCommand.MOVE || command === GeometryCommand.LINE) return 1
+ if (command === GeometryCommand.QUAD) return 2
+ if (command === GeometryCommand.CUBIC) return 3
return null
}
+/**
+ * Walks a Figma geometry blob: `visit` gets each command, its coordinates as x, y pairs in one
+ * array reused between calls, and the byte offset of the first coordinate. It stops at an
+ * unknown command or one cut short.
+ */
+export function readGeometryBlob(
+ blob: Uint8Array,
+ visit: (command: GeometryCommand, coords: readonly number[], offset: number) => void
+): void {
+ const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength)
+ const coords: number[] = []
+ let offset = 0
+ while (offset < blob.length) {
+ const command = blob[offset]
+ const count = commandCoordCount(command)
+ if (count === null || offset + 1 + count * 8 > blob.length) return
+ offset += 1
+ coords.length = 0
+ for (let i = 0; i < count; i++) {
+ coords.push(view.getFloat32(offset + i * 8, true), view.getFloat32(offset + i * 8 + 4, true))
+ }
+ visit(command as GeometryCommand, coords, offset)
+ offset += count * 8
+ }
+}
+
export function geometryBlobBounds(paths: Array<{ commandsBlob: Uint8Array }>): Rect | null {
const bounds = createBoundsAccumulator()
-
for (const path of paths) {
- const blob = path.commandsBlob
- const dv = new DataView(blob.buffer, blob.byteOffset, blob.byteLength)
- let offset = 0
- while (offset < blob.length) {
- const command = blob[offset++]
- const coords = geometryCommandCoordCount(command)
- if (coords == null) break
- for (let i = 0; i < coords; i++) {
- if (offset + 8 > blob.length) break
- const x = dv.getFloat32(offset, true)
- const y = dv.getFloat32(offset + 4, true)
- includePoint(bounds, x, y)
- offset += 8
- }
- }
+ readGeometryBlob(path.commandsBlob, (_, coords) => {
+ for (let i = 0; i < coords.length; i += 2) includePoint(bounds, coords[i], coords[i + 1])
+ })
}
return bounds.minX === Infinity ? null : boundsToRect(bounds)
diff --git a/packages/scene-graph/src/hit-test.ts b/packages/scene-graph/src/hit-test.ts
index ca7b37943..3d6950f1f 100644
--- a/packages/scene-graph/src/hit-test.ts
+++ b/packages/scene-graph/src/hit-test.ts
@@ -2,6 +2,7 @@ import { hitsConnectorLine } from './connectors/hit'
import { getWorldMatrix } from './coordinate'
import type { SceneGraph } from './graph'
import Matrix from './matrix'
+import { hitsShape, strokeReach } from './outline/hit'
import type { SceneNode, NodeType } from './types'
const CONTAINER_TYPES = new Set<NodeType>([
@@ -179,12 +180,30 @@ function hitTestChildren(
if (hitsConnectorLine(graph, child, px, py, pad)) return child
continue
}
- if (containsPoint(px, py, child, graph, transformCache, pad)) return child
+ if (hitsLeaf(graph, px, py, child, transformCache, pad)) return child
}
return null
}
+/**
+ * Whether a click lands on a leaf layer: on what its paints draw, as Figma tests shapes (see
+ * `hitsShape`), or on its box for layers without an outline to test, such as text.
+ */
+function hitsLeaf(
+ graph: SceneGraph,
+ px: number,
+ py: number,
+ node: SceneNode,
+ transformCache: Map<string, boolean>,
+ pad: number
+): boolean {
+ if (!containsPoint(px, py, node, graph, transformCache, pad + strokeReach(node))) return false
+ return (
+ hitsShape(graph, node, px, py, pad) ?? containsPoint(px, py, node, graph, transformCache, pad)
+ )
+}
+
export function hitTest(
graph: SceneGraph,
px: number,
diff --git a/packages/scene-graph/src/outline/flatten.ts b/packages/scene-graph/src/outline/flatten.ts
new file mode 100644
index 000000000..07a9f6ab7
--- /dev/null
+++ b/packages/scene-graph/src/outline/flatten.ts
@@ -0,0 +1,190 @@
+import { cubicPoint } from '../cubic'
+import { GeometryCommand, readGeometryBlob } from '../geometry'
+import type { PolygonOutlineCommand } from '../polygon'
+import type { Vector } from '../primitives'
+import type { VectorNetwork } from '../types'
+
+/**
+ * Keeps a huge curve at a tiny tolerance from flattening into an unbounded number of points, while
+ * leaving room for the largest arcs at the maximum zoom: a 100,000-unit circle at 25,600% needs
+ * about 12,000 steps to stay within the click pad.
+ */
+const MAX_CURVE_STEPS = 65_536
+
+/**
+ * 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 cubic after its start, within `tolerance` of it, ending on `p3`. */
+function cubicPoints(p0: Vector, p1: Vector, p2: Vector, p3: Vector, tolerance: number): Vector[] {
+ const steps = curveSteps(p0, p1, p2, p3, tolerance)
+ const points: Vector[] = []
+ for (let step = 1; step <= steps; step++) points.push(cubicPoint(p0, p1, p2, p3, step / steps))
+ return points
+}
+
+/** Points along a vector network segment, from its start to its end, in network coordinates. */
+export function segmentPoints(
+ network: VectorNetwork,
+ index: number,
+ tolerance: number
+): Vector[] | null {
+ // `at` counts a negative index from the end and truncates a fraction; a loop naming either
+ // refers to no segment.
+ if (!Number.isInteger(index) || index < 0) return 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 }
+ return [p0, ...cubicPoints(p0, p1, p2, p3, tolerance)]
+}
+
+/**
+ * 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.
+ */
+export 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 network's segments joined into runs, a run continuing while each segment starts where the
+ * last ended, as a path draws them one after another.
+ */
+export function segmentRuns(network: VectorNetwork, tolerance: number): Vector[][] {
+ const runs: Vector[][] = []
+ let run: Vector[] = []
+ let end = -1
+ for (const [index, segment] of network.segments.entries()) {
+ const along = segmentPoints(network, index, tolerance)
+ if (!along) continue
+ if (segment.start === end && run.length > 0) run.push(...along.slice(1))
+ else {
+ if (run.length > 1) runs.push(run)
+ run = along
+ }
+ end = segment.end
+ }
+ if (run.length > 1) runs.push(run)
+ return runs
+}
+
+/** The contours of a Figma geometry blob, curves flattened to within `tolerance`. */
+export function blobContours(blob: Uint8Array, tolerance: number): Vector[][] {
+ const contours: Vector[][] = []
+ let contour: Vector[] = []
+ const flush = () => {
+ if (contour.length > 1) contours.push(contour)
+ contour = []
+ }
+ readGeometryBlob(blob, (command, c) => {
+ if (command === GeometryCommand.CLOSE) return flush()
+ if (command === GeometryCommand.MOVE) {
+ flush()
+ contour.push({ x: c[0], y: c[1] })
+ return
+ }
+ const end = { x: c[c.length - 2], y: c[c.length - 1] }
+ const last = contour.at(-1)
+ if (!last || command === GeometryCommand.LINE) {
+ contour.push(end)
+ } else if (command === GeometryCommand.QUAD) {
+ // A quadratic as the cubic with the same curve.
+ const q = { x: c[0], y: c[1] }
+ const c1 = { x: last.x + (2 / 3) * (q.x - last.x), y: last.y + (2 / 3) * (q.y - last.y) }
+ const c2 = { x: end.x + (2 / 3) * (q.x - end.x), y: end.y + (2 / 3) * (q.y - end.y) }
+ contour.push(...cubicPoints(last, c1, c2, end, tolerance))
+ } else {
+ contour.push(...cubicPoints(last, { x: c[0], y: c[1] }, { x: c[2], y: c[3] }, end, tolerance))
+ }
+ })
+ flush()
+ return contours
+}
+
+/** The contours of polygon outline commands, curves flattened to within `tolerance`. */
+export function commandContours(
+ commands: readonly PolygonOutlineCommand[],
+ tolerance: number
+): Vector[][] {
+ const contours: Vector[][] = []
+ let contour: Vector[] = []
+ for (const command of commands) {
+ if (command.type === 'Z' || command.type === 'M') {
+ if (contour.length > 1) contours.push(contour)
+ contour = command.type === 'M' ? [{ x: command.x, y: command.y }] : []
+ continue
+ }
+ const last = contour.at(-1) ?? { x: 0, y: 0 }
+ if (command.type !== 'C') contour.push({ x: command.x, y: command.y })
+ else
+ contour.push(
+ ...cubicPoints(
+ last,
+ { x: command.x1, y: command.y1 },
+ { x: command.x2, y: command.y2 },
+ { x: command.x, y: command.y },
+ tolerance
+ )
+ )
+ }
+ if (contour.length > 1) contours.push(contour)
+ return contours
+}
+
+/** Points around an ellipse arc from `start` to `end` radians, at most `tolerance` off it. */
+export function arcPoints(
+ cx: number,
+ cy: number,
+ rx: number,
+ ry: number,
+ start: number,
+ end: number,
+ tolerance: number
+): Vector[] {
+ const radius = Math.max(rx, ry)
+ // A chord over angle θ strays r(1 − cos(θ/2)) from the arc.
+ const step =
+ radius > tolerance ? 2 * Math.acos(Math.max(-1, 1 - tolerance / radius)) : Math.PI / 2
+ const steps = Math.min(
+ MAX_CURVE_STEPS,
+ Math.max(1, Math.ceil(Math.abs(end - start) / Math.max(step, 1e-3)))
+ )
+ const points: Vector[] = []
+ for (let i = 0; i <= steps; i++) {
+ const angle = start + ((end - start) * i) / steps
+ points.push({ x: cx + rx * Math.cos(angle), y: cy + ry * Math.sin(angle) })
+ }
+ return points
+}
diff --git a/packages/scene-graph/src/outline/heads.ts b/packages/scene-graph/src/outline/heads.ts
new file mode 100644
index 000000000..f272c8763
--- /dev/null
+++ b/packages/scene-graph/src/outline/heads.ts
@@ -0,0 +1,52 @@
+import {
+ arrowLinesSegments,
+ circleCapRadius,
+ collectArrowEndpoints,
+ diamondCapPoints,
+ equilateralArrowPoints,
+ triangleCapPoints
+} from '../arrow-caps'
+import type { Vector } from '../primitives'
+import type { StrokeCap, VectorNetwork } from '../types'
+import { containsByWinding, distanceToLines, distanceToSegment } from './point'
+
+/** The outline of each filled head with corners, at an end pointing along `angle`. */
+const HEAD_OUTLINES: Record<
+ 'ARROW_EQUILATERAL' | 'TRIANGLE_FILLED' | 'DIAMOND_FILLED',
+ (x: number, y: number, angle: number, weight: number) => Vector[]
+> = {
+ ARROW_EQUILATERAL: equilateralArrowPoints,
+ TRIANGLE_FILLED: triangleCapPoints,
+ DIAMOND_FILLED: diamondCapPoints
+}
+
+/**
+ * Whether the point lands on an arrow head drawn at the open ends of `network`, in its own
+ * coordinates, within `pad`: inside a filled head or near its outline, or near a line arrow's
+ * wings, which are stroked at the line's weight.
+ */
+export function hitsArrowHeads(
+ network: VectorNetwork,
+ cap: StrokeCap,
+ weight: number,
+ point: Vector,
+ pad: number
+): boolean {
+ for (const { x, y, angle, cap: head } of collectArrowEndpoints(network, cap)) {
+ if (head === 'CIRCLE_FILLED') {
+ if (Math.hypot(point.x - x, point.y - y) <= circleCapRadius(weight) + pad) return true
+ continue
+ }
+ if (head === 'ARROW_LINES') {
+ const wings = arrowLinesSegments(x, y, angle, weight)
+ if (wings.some((wing) => distanceToSegment(point, wing.from, wing.to) <= weight / 2 + pad)) {
+ return true
+ }
+ continue
+ }
+ const outline = HEAD_OUTLINES[head](x, y, angle, weight)
+ if (containsByWinding([outline], 'NONZERO', point)) return true
+ if (distanceToLines([[...outline, outline[0]]], point) <= pad) return true
+ }
+ return false
+}
diff --git a/packages/scene-graph/src/outline/hit.ts b/packages/scene-graph/src/outline/hit.ts
new file mode 100644
index 000000000..5b02395ab
--- /dev/null
+++ b/packages/scene-graph/src/outline/hit.ts
@@ -0,0 +1,369 @@
+import { compact } from 'es-toolkit'
+
+import { arrowCapOverflow, isArrowCap, lineStrokeEnds } from '../arrow-caps'
+import { getWorldMatrix } from '../coordinate'
+import type { SceneGraph } from '../graph'
+import Matrix from '../matrix'
+import type { Vector } from '../primitives'
+import type { Fill, SceneNode, Stroke } from '../types'
+import { hitsArrowHeads } from './heads'
+import { containsByWinding, distanceToLines, distanceToSegment } from './point'
+import { shapeOutline, type OutlineArea, type ShapeOutline } from './shapes'
+
+/** Points tested along each edge near the point for whether the filled result changes there. */
+const EDGE_SAMPLES = 8
+
+/** How far a flattened curve may stray from the shape when nothing tighter is asked for. */
+const DEFAULT_TOLERANCE = 0.25
+
+/**
+ * Whether a paint makes its layer clickable, as in Figma: a visible paint that shows something.
+ * A paint at 0% opacity, or a gradient whose stops are all transparent, does not; 1% does, and
+ * the layer's own opacity does not matter.
+ */
+export function isHitPaint(paint: Fill): boolean {
+ if (!paint.visible || !(paint.opacity > 0)) return false
+ if (paint.gradientStops) return paint.gradientStops.some((stop) => stop.color.a > 0)
+ if (paint.type === 'SOLID') return paint.color.a > 0
+ return true
+}
+
+function insideArea(area: OutlineArea, point: Vector): boolean {
+ return containsByWinding(area.contours, area.windingRule, point)
+}
+
+/** A stroke's weight; with independent borders the widest side, for layers without per-side lines. */
+function strokeWeightOf(node: SceneNode, stroke: Stroke): number {
+ if (node.independentStrokeWeights) {
+ return Math.max(
+ node.borderTopWeight,
+ node.borderRightWeight,
+ node.borderBottomWeight,
+ node.borderLeftWeight
+ )
+ }
+ return Number.isFinite(stroke.weight) ? stroke.weight : node.strokeWeight
+}
+
+/** The farthest a layer's clickable strokes reach outside its box, in its own units. */
+export function strokeReach(node: SceneNode): number {
+ let reach = 0
+ for (const stroke of node.strokes) {
+ if (!isHitPaint(stroke)) continue
+ const weight = strokeWeightOf(node, stroke)
+ // A line's stroke lies a full weight to one side of it.
+ const side = node.type === 'LINE' || stroke.align === 'OUTSIDE'
+ reach = Math.max(reach, side ? weight : weight / 2)
+ }
+ // Arrow heads reach past the stroke.
+ const hitStrokes = node.strokes.filter(isHitPaint)
+ return Math.max(reach, arrowCapOverflow(hitStrokes, node.strokeCap, node.vectorNetwork))
+}
+
+function localPoint(graph: SceneGraph, node: SceneNode, px: number, py: number): Vector | null {
+ const inverse = Matrix.invert(getWorldMatrix(node, graph))
+ if (!inverse) return null
+ const [x, y] = Matrix.mapPoints(inverse, [px, py])
+ return { x, y }
+}
+
+interface Probe {
+ inside: boolean
+ /** The point in the layer's own coordinates, where its outline has one. */
+ local?: Vector
+ /**
+ * Whether the outline of the filled area passes within `radius` of the point, counting only
+ * edges where the filled result changes from one side to the other.
+ */
+ edgeWithin: (radius: number) => boolean
+ /** Each line a stroke follows, measured from the point in canvas units. */
+ lines: LineReach[]
+ /** Each line's own stroke weight, where sides differ. */
+ lineWeights?: number[]
+ /** Whether the layer has an area of its own; strokes on lines are always centred. */
+ closed: boolean
+ /** Strokes centre on the lines whatever their alignment. */
+ centered?: boolean
+ /** Strokes follow the filled area's outline, for a shape combined from operands. */
+ strokeOnEdge?: boolean
+ /** Whether the point lies on or within `radius` of the saved outline a stroke fills. */
+ strokeAreaWithin?: (radius: number) => boolean
+}
+
+/**
+ * Whether an outline made of `edges` passes within `radius` of the point, counting a stretch of
+ * edge only where `insideAt` changes from one side of it to the other: edges that cancel or that
+ * lie hidden inside or outside the result count for nothing.
+ */
+function changingEdgeWithin(
+ edges: Vector[][],
+ insideAt: (x: number, y: number) => boolean | null,
+ point: Vector,
+ radius: number,
+ tolerance: number
+): boolean {
+ const step = Math.max(1e-6, Math.min(tolerance, radius / 4) / 4)
+ for (const edge of edges) {
+ for (let i = 0; i + 1 < edge.length; i++) {
+ const a = edge[i]
+ const b = edge[i + 1]
+ if (a.x === b.x && a.y === b.y) continue
+ if (distanceToSegment(point, a, b) > radius) continue
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const length = Math.hypot(dx, dy)
+ const nx = -dy / length
+ const ny = dx / length
+ // The part of the edge inside the circle, sampled evenly.
+ const centre = ((point.x - a.x) * dx + (point.y - a.y) * dy) / (length * length)
+ const offset = Math.abs((point.x - a.x) * nx + (point.y - a.y) * ny)
+ const half = Math.sqrt(Math.max(0, radius * radius - offset * offset)) / length
+ const from = Math.max(0, centre - half)
+ const to = Math.min(1, centre + half)
+ for (let k = 0; k <= EDGE_SAMPLES; k++) {
+ const t = from + ((to - from) * k) / EDGE_SAMPLES
+ const qx = a.x + dx * t
+ const qy = a.y + dy * t
+ const left = insideAt(qx + nx * step, qy + ny * step)
+ const right = insideAt(qx - nx * step, qy - ny * step)
+ if (left !== null && right !== null && left !== right) return true
+ }
+ }
+ }
+ return false
+}
+
+/**
+ * How a point lies from a line: its distance, and past an open end how far beyond the end it is
+ * along the line and how far across it, for a flat cap that paints nothing past the end.
+ */
+interface LineReach {
+ distance: number
+ beyond: number
+ across: number
+}
+
+function measureLine(
+ line: Vector[],
+ ends: [boolean, boolean] | undefined,
+ point: Vector
+): LineReach {
+ const reach: LineReach = { distance: distanceToLines([line], point), beyond: 0, across: 0 }
+ if (!ends || line.length < 2) return reach
+ // Past an open end, the point projects beyond the first or last segment.
+ const tips: Array<[boolean, Vector, Vector]> = [
+ [ends[0], line[0], line[1]],
+ [ends[1], line[line.length - 1], line[line.length - 2]]
+ ]
+ for (const [open, tip, next] of tips) {
+ if (!open) continue
+ const dx = tip.x - next.x
+ const dy = tip.y - next.y
+ const length = Math.hypot(dx, dy)
+ if (length === 0) continue
+ const along = ((point.x - tip.x) * dx + (point.y - tip.y) * dy) / length
+ if (along <= 0 || Math.hypot(point.x - tip.x, point.y - tip.y) > reach.distance + 1e-9) continue
+ reach.beyond = along
+ reach.across = Math.abs((point.x - tip.x) * dy - (point.y - tip.y) * dx) / length
+ }
+ return reach
+}
+
+function probeOutline(outline: ShapeOutline, point: Vector, tolerance: number): Probe {
+ const insideAt = (x: number, y: number) =>
+ outline.areas.some((area) => insideArea(area, { x, y }))
+ const edges = outline.areas.flatMap((area) => area.contours.map(closedLoop))
+ const { strokeAreas } = outline
+ return {
+ inside: insideAt(point.x, point.y),
+ local: point,
+ edgeWithin: (radius) => changingEdgeWithin(edges, insideAt, point, radius, tolerance),
+ lines: outline.lines.map((line, index) => measureLine(line, outline.lineEnds?.[index], point)),
+ lineWeights: outline.lineWeights,
+ closed: outline.areas.some((area) => area.contours.length > 0),
+ centered: outline.strokeCentered,
+ strokeAreaWithin: strokeAreas
+ ? (radius) =>
+ strokeAreas.some((area) => insideArea(area, point)) ||
+ changingEdgeWithin(
+ strokeAreas.flatMap((area) => area.contours.map(closedLoop)),
+ (x, y) => strokeAreas.some((area) => insideArea(area, { x, y })),
+ point,
+ radius,
+ tolerance
+ )
+ : undefined
+ }
+}
+
+function closedLoop(contour: Vector[]): Vector[] {
+ const first = contour.at(0)
+ return first ? [...contour, first] : contour
+}
+
+const BOOLEAN_COMBINE: Record<
+ NonNullable<SceneNode['booleanOperation']>,
+ (hits: boolean[]) => boolean
+> = {
+ UNION: (hits) => hits.some(Boolean),
+ INTERSECT: (hits) => hits.length > 0 && hits.every(Boolean),
+ SUBTRACT: ([first = false, ...rest]) => first && !rest.some(Boolean),
+ EXCLUDE: (hits) => compact(hits).length % 2 === 1
+}
+
+/** The lines an operand draws its outline along, in canvas coordinates. */
+function operandEdges(graph: SceneGraph, node: SceneNode, tolerance: number): Vector[][] {
+ if (node.type === 'BOOLEAN_OPERATION' && node.fillGeometry.length === 0) {
+ return graph
+ .getChildren(node.id)
+ .filter((child) => child.visible)
+ .flatMap((child) => operandEdges(graph, child, tolerance))
+ }
+ const outline =
+ node.type === 'BOOLEAN_OPERATION'
+ ? shapeOutline({ ...node, type: 'VECTOR', vectorNetwork: null }, tolerance)
+ : shapeOutline(node, tolerance)
+ if (!outline) return []
+ const world = getWorldMatrix(node, graph)
+ const local = [
+ ...outline.lines,
+ ...outline.areas.flatMap((area) => area.contours.map(closedLoop))
+ ]
+ return local.map((line) =>
+ line.map((point) => {
+ const [x, y] = Matrix.mapPoints(world, [point.x, point.y])
+ return { x, y }
+ })
+ )
+}
+
+/**
+ * A boolean operation without saved geometry, combined from its operands as it draws. Its outline
+ * runs along the operand edges where the combined result changes from one side to the other, so
+ * edges hidden inside or outside the result count for nothing. Each side is probed at most a
+ * quarter of a screen pixel out, so a result thinner than that, which draws no visible pixel, is
+ * not seen.
+ */
+function probeBoolean(
+ graph: SceneGraph,
+ node: SceneNode,
+ px: number,
+ py: number,
+ tolerance: number
+): Probe | null {
+ const operands = graph.getChildren(node.id).filter((child) => child.visible)
+ if (operands.length === 0) return null
+ const combine = BOOLEAN_COMBINE[node.booleanOperation ?? 'UNION']
+ const insideAt = (x: number, y: number): boolean | null => {
+ const hits: boolean[] = []
+ for (const operand of operands) {
+ const probe = probeNode(graph, operand, x, y, tolerance)
+ if (!probe) return null
+ hits.push(probe.inside)
+ }
+ return combine(hits)
+ }
+ const inside = insideAt(px, py)
+ if (inside === null) return null
+ const point = { x: px, y: py }
+ const edges = operands.flatMap((operand) => operandEdges(graph, operand, tolerance))
+ return {
+ inside,
+ edgeWithin: (radius) => changingEdgeWithin(edges, insideAt, point, radius, tolerance),
+ lines: [],
+ closed: true,
+ strokeOnEdge: true
+ }
+}
+
+function probeNode(
+ graph: SceneGraph,
+ node: SceneNode,
+ px: number,
+ py: number,
+ tolerance: number
+): Probe | null {
+ if (node.type === 'BOOLEAN_OPERATION' && node.fillGeometry.length === 0) {
+ return probeBoolean(graph, node, px, py, tolerance)
+ }
+ const outline =
+ node.type === 'BOOLEAN_OPERATION'
+ ? shapeOutline({ ...node, type: 'VECTOR', vectorNetwork: null }, tolerance)
+ : shapeOutline(node, tolerance)
+ if (!outline) return null
+ const point = localPoint(graph, node, px, py)
+ return point ? probeOutline(outline, point, tolerance) : null
+}
+
+/** How far from a line a stroke's band reaches toward the point, beyond which it misses. */
+function strokeReachAt(align: Stroke['align'], weight: number, inside: boolean): number {
+ if (align === 'INSIDE') return inside ? weight : 0
+ if (align === 'OUTSIDE') return inside ? 0 : weight
+ return weight / 2
+}
+
+function strokeHits(node: SceneNode, stroke: Stroke, probe: Probe, pad: number): boolean {
+ if (probe.strokeAreaWithin) return probe.strokeAreaWithin(pad)
+ const align = probe.closed && !probe.centered ? stroke.align : 'CENTER'
+ if (probe.strokeOnEdge) {
+ const weight = strokeWeightOf(node, stroke)
+ return probe.edgeWithin(strokeReachAt(align, weight, probe.inside) + pad)
+ }
+ // A flat cap ends the stroke at the line's end; round and square caps paint past it.
+ const cap = stroke.cap ?? node.strokeCap
+ const flatEnds = cap === 'NONE'
+ const reaches = (line: LineReach, band: number): boolean => {
+ if (flatEnds && line.beyond > 0) {
+ // Past a flat end, the distance to the painted band's square end.
+ return Math.hypot(line.beyond, Math.max(0, line.across - band)) <= pad
+ }
+ return line.distance <= band + pad
+ }
+ if (node.type === 'LINE' && probe.local) {
+ // Figma strokes a line a full weight to one side, along the path the renderer draws.
+ const weight = strokeWeightOf(node, stroke)
+ if (!(weight > 0)) return false
+ const { start, end } = lineStrokeEnds(node.width, node.height, weight, cap)
+ if (reaches(measureLine([start, end], [true, true], probe.local), weight / 2)) return true
+ if (!isArrowCap(cap)) return false
+ const still = { x: 0, y: 0 }
+ const shaft = {
+ vertices: [start, end],
+ segments: [{ start: 0, end: 1, tangentStart: still, tangentEnd: still }],
+ regions: []
+ }
+ return hitsArrowHeads(shaft, cap, weight, probe.local, pad)
+ }
+ const network = node.type === 'VECTOR' ? node.vectorNetwork : null
+ if (network && probe.local) {
+ const weight = strokeWeightOf(node, stroke)
+ if (weight > 0 && hitsArrowHeads(network, cap, weight, probe.local, pad)) return true
+ }
+ return probe.lines.some((line, index) => {
+ const weight = probe.lineWeights?.[index] ?? strokeWeightOf(node, stroke)
+ // A side with no weight paints no border.
+ if (!(weight > 0)) return false
+ return reaches(line, strokeReachAt(align, weight, probe.inside))
+ })
+}
+
+/**
+ * Whether a click at the canvas point lands on the shape, as in Figma: inside the area a
+ * clickable fill covers, or on the band a clickable stroke draws, either grown by `pad` canvas
+ * units. A shape whose paints show nothing is never hit. Null for a layer without an outline to
+ * test, which is hit by its box.
+ */
+export function hitsShape(
+ graph: SceneGraph,
+ node: SceneNode,
+ px: number,
+ py: number,
+ pad = 0
+): boolean | null {
+ const tolerance = pad > 0 ? Math.min(DEFAULT_TOLERANCE, pad / 4) : DEFAULT_TOLERANCE
+ const probe = probeNode(graph, node, px, py, tolerance)
+ if (!probe) return null
+ const fills = node.fills.filter(isHitPaint)
+ if (fills.length > 0 && probe.closed && (probe.inside || probe.edgeWithin(pad))) return true
+ return node.strokes.some((stroke) => isHitPaint(stroke) && strokeHits(node, stroke, probe, pad))
+}
diff --git a/packages/scene-graph/src/outline/index.ts b/packages/scene-graph/src/outline/index.ts
new file mode 100644
index 000000000..184ef792d
--- /dev/null
+++ b/packages/scene-graph/src/outline/index.ts
@@ -0,0 +1,4 @@
+export { hitsShape, isHitPaint, strokeReach } from './hit'
+export { shapeOutline, type OutlineArea, type ShapeOutline } from './shapes'
+export { blobContours, loopPoints, segmentPoints } from './flatten'
+export { containsByWinding, distanceToLines, distanceToSegment, windingNumber } from './point'
diff --git a/packages/scene-graph/src/outline/point.ts b/packages/scene-graph/src/outline/point.ts
new file mode 100644
index 000000000..4c7d5b859
--- /dev/null
+++ b/packages/scene-graph/src/outline/point.ts
@@ -0,0 +1,59 @@
+import type { Vector } from '../primitives'
+import type { WindingRule } from '../types'
+
+/**
+ * The signed number of times closed contours wind around `point`, each closing back to its start
+ * as a path fill closes it.
+ */
+export function windingNumber(contours: Iterable<Vector[]>, point: Vector): number {
+ let winding = 0
+ for (const contour of contours) {
+ for (let i = 0; i < contour.length; i++) {
+ const a = contour[i]
+ const b = contour[(i + 1) % contour.length]
+ // 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
+}
+
+/** Whether contours filled by `windingRule` cover the point. */
+export function containsByWinding(
+ contours: Iterable<Vector[]>,
+ windingRule: WindingRule,
+ point: Vector
+): boolean {
+ const winding = windingNumber(contours, point)
+ return windingRule === 'EVENODD' ? winding % 2 !== 0 : winding !== 0
+}
+
+export function distanceToSegment(p: Vector, a: Vector, b: Vector): number {
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const lengthSquared = dx * dx + dy * dy
+ const t =
+ lengthSquared === 0
+ ? 0
+ : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSquared))
+ return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))
+}
+
+/** The distance from the point to the nearest of the polylines. */
+export function distanceToLines(lines: readonly Vector[][], point: Vector): number {
+ let nearest = Infinity
+ for (const line of lines) {
+ if (line.length === 1) {
+ nearest = Math.min(nearest, Math.hypot(point.x - line[0].x, point.y - line[0].y))
+ }
+ for (let i = 0; i + 1 < line.length; i++) {
+ nearest = Math.min(nearest, distanceToSegment(point, line[i], line[i + 1]))
+ }
+ }
+ return nearest
+}
diff --git a/packages/scene-graph/src/outline/shapes.ts b/packages/scene-graph/src/outline/shapes.ts
new file mode 100644
index 000000000..3c6d392e1
--- /dev/null
+++ b/packages/scene-graph/src/outline/shapes.ts
@@ -0,0 +1,207 @@
+import { polygonOutline } from '../polygon'
+import type { Vector } from '../primitives'
+import type { SceneNode, WindingRule } from '../types'
+import {
+ arcPoints,
+ blobContours,
+ commandContours,
+ loopPoints,
+ segmentPoints,
+ segmentRuns
+} from './flatten'
+
+/** Contours filled together under one winding rule. */
+export interface OutlineArea {
+ windingRule: WindingRule
+ contours: Vector[][]
+}
+
+/**
+ * A shape's geometry in its own coordinates, curves flattened: the areas its fills cover and the
+ * lines its strokes follow, closed contours ending where they began.
+ */
+export interface ShapeOutline {
+ areas: OutlineArea[]
+ lines: Vector[][]
+ /** Each line's own stroke weight, where sides differ, as a rectangle's independent borders. */
+ lineWeights?: number[]
+ /**
+ * Strokes centre on the lines whatever their alignment, as on a network without regions that is
+ * open or has no saved stroke geometry.
+ */
+ strokeCentered?: boolean
+ /** For each line, whether its start and its end are open ends, where a stroke's cap is drawn. */
+ lineEnds?: Array<[boolean, boolean]>
+ /** The saved outline a stroke fills, for a shape whose stroke has no lines to follow. */
+ strokeAreas?: OutlineArea[]
+}
+
+function closed(contour: Vector[]): Vector[] {
+ const first = contour.at(0)
+ const last = contour.at(-1)
+ if (!first || !last || (first.x === last.x && first.y === last.y)) return contour
+ return [...contour, first]
+}
+
+function fromContours(contours: Vector[][], windingRule: WindingRule = 'NONZERO'): ShapeOutline {
+ return { areas: [{ windingRule, contours }], lines: contours.map(closed) }
+}
+
+function cornerRadii(node: SceneNode): [number, number, number, number] {
+ const radii: [number, number, number, number] = node.independentCorners
+ ? [node.topLeftRadius, node.topRightRadius, node.bottomRightRadius, node.bottomLeftRadius]
+ : [node.cornerRadius, node.cornerRadius, node.cornerRadius, node.cornerRadius]
+ const limit = Math.min(node.width, node.height) / 2
+ return radii.map((radius) => Math.max(0, Math.min(radius, limit))) as typeof radii
+}
+
+function rectangleContour(node: SceneNode, tolerance: number): Vector[] {
+ const { width: w, height: h } = node
+ const [tl, tr, br, bl] = cornerRadii(node)
+ const corner = (cx: number, cy: number, r: number, from: number): Vector[] =>
+ r > 0 ? arcPoints(cx, cy, r, r, from, from + Math.PI / 2, tolerance) : [{ x: cx, y: cy }]
+ return [
+ ...corner(w - tr, tr, tr, -Math.PI / 2),
+ ...corner(w - br, h - br, br, 0),
+ ...corner(bl, h - bl, bl, Math.PI / 2),
+ ...corner(tl, tl, tl, Math.PI)
+ ]
+}
+
+/**
+ * A rectangle's four sides with the weight each draws its border at: top, right, bottom, left.
+ * Each side runs from the middle of one rounded corner to the middle of the next, as its border
+ * is drawn round them.
+ */
+function rectangleSides(
+ node: SceneNode,
+ tolerance: number
+): Pick<ShapeOutline, 'lines' | 'lineWeights'> {
+ const { width: w, height: h } = node
+ const [tl, tr, br, bl] = cornerRadii(node)
+ const quarter = Math.PI / 4
+ const arc = (cx: number, cy: number, r: number, from: number): Vector[] =>
+ r > 0 ? arcPoints(cx, cy, r, r, from, from + quarter, tolerance) : [{ x: cx, y: cy }]
+ return {
+ lines: [
+ [...arc(tl, tl, tl, 5 * quarter), ...arc(w - tr, tr, tr, -2 * quarter)],
+ [...arc(w - tr, tr, tr, -quarter), ...arc(w - br, h - br, br, 0)],
+ [...arc(w - br, h - br, br, quarter), ...arc(bl, h - bl, bl, 2 * quarter)],
+ [...arc(bl, h - bl, bl, 3 * quarter), ...arc(tl, tl, tl, 4 * quarter)]
+ ],
+ lineWeights: [
+ node.borderTopWeight,
+ node.borderRightWeight,
+ node.borderBottomWeight,
+ node.borderLeftWeight
+ ]
+ }
+}
+
+const FULL_TURN = Math.PI * 2
+
+function ellipseContours(node: SceneNode, tolerance: number): Vector[][] {
+ const rx = node.width / 2
+ const ry = node.height / 2
+ const arc = node.arcData
+ const start = arc?.startingAngle ?? 0
+ const end = arc?.endingAngle ?? FULL_TURN
+ const inner = arc?.innerRadius ?? 0
+ const whole = Math.abs(end - start) >= FULL_TURN - 1e-6
+ const outer = arcPoints(rx, ry, rx, ry, start, whole ? start + FULL_TURN : end, tolerance)
+ if (inner <= 0) return [whole ? outer : [{ x: rx, y: ry }, ...outer]]
+ const hole = arcPoints(
+ rx,
+ ry,
+ rx * inner,
+ ry * inner,
+ whole ? start + FULL_TURN : end,
+ start,
+ tolerance
+ )
+ // A whole ring is two loops wound opposite ways; a part ring is one outline across its ends.
+ return whole ? [outer, hole] : [[...outer, ...hole]]
+}
+
+function vectorOutline(node: SceneNode, tolerance: number): ShapeOutline | null {
+ const network = node.vectorNetwork
+ const geometry = node.fillGeometry.map((path) => ({
+ windingRule: path.windingRule,
+ contours: path.commandsBlob.length > 0 ? blobContours(path.commandsBlob, tolerance) : []
+ }))
+ if (!network) {
+ if (geometry.length === 0 && node.strokeGeometry.length === 0) return null
+ // Without a network the renderer fills the saved stroke geometry, or draws no stroke.
+ const strokeAreas = node.strokeGeometry.map((path) => ({
+ windingRule: path.windingRule,
+ contours: path.commandsBlob.length > 0 ? blobContours(path.commandsBlob, tolerance) : []
+ }))
+ return { areas: geometry, lines: [], strokeAreas }
+ }
+ // A vertex on one segment only is an open end.
+ const degree = new Map<number, number>()
+ for (const segment of network.segments) {
+ degree.set(segment.start, (degree.get(segment.start) ?? 0) + 1)
+ degree.set(segment.end, (degree.get(segment.end) ?? 0) + 1)
+ }
+ const lines: Vector[][] = []
+ const lineEnds: Array<[boolean, boolean]> = []
+ for (const [index, segment] of network.segments.entries()) {
+ const points = segmentPoints(network, index, tolerance)
+ if (!points) continue
+ lines.push(points)
+ lineEnds.push([degree.get(segment.start) === 1, degree.get(segment.end) === 1])
+ }
+ // Without regions the stroke draws centred on each segment, unless a closed network carries
+ // saved stroke geometry, which the renderer draws with its alignment.
+ const open = lineEnds.some(([start, end]) => start || end)
+ const strokeCentered = network.regions.length === 0 && (open || node.strokeGeometry.length === 0)
+ if (geometry.length > 0) return { areas: geometry, lines, lineEnds, strokeCentered }
+ const areas =
+ network.regions.length > 0
+ ? network.regions.map((region) => ({
+ windingRule: region.windingRule,
+ contours: region.loops.map((loop) => loopPoints(network, loop, tolerance))
+ }))
+ : // Without regions a fill closes each run of segments, as a path fill does.
+ [{ windingRule: 'NONZERO' as const, contours: segmentRuns(network, tolerance) }]
+ return { areas, lines, lineEnds, strokeCentered }
+}
+
+/**
+ * The outline a click is tested against, in the node's own coordinates, with curves within
+ * `tolerance` of the shape; null for layers tested by their box, such as text.
+ */
+export function shapeOutline(node: SceneNode, tolerance: number): ShapeOutline | null {
+ switch (node.type) {
+ case 'RECTANGLE':
+ case 'ROUNDED_RECTANGLE': {
+ const outline = fromContours([rectangleContour(node, tolerance)])
+ return node.independentStrokeWeights
+ ? { ...outline, ...rectangleSides(node, tolerance) }
+ : outline
+ }
+ case 'ELLIPSE': {
+ if (node.fillGeometry.length > 0) return vectorOutline(node, tolerance)
+ return fromContours(ellipseContours(node, tolerance))
+ }
+ case 'POLYGON':
+ case 'STAR':
+ return fromContours(commandContours(polygonOutline(node), tolerance))
+ case 'LINE':
+ return {
+ areas: [],
+ lines: [
+ [
+ { x: 0, y: 0 },
+ { x: node.width, y: node.height }
+ ]
+ ],
+ lineEnds: [[true, true]]
+ }
+ case 'VECTOR':
+ return vectorOutline(node, tolerance)
+ default:
+ return null
+ }
+}
diff --git a/packages/scene-graph/tests/basic/helpers.ts b/packages/scene-graph/tests/basic/helpers.ts
index fd0952b8a..f831d7921 100644
--- a/packages/scene-graph/tests/basic/helpers.ts
+++ b/packages/scene-graph/tests/basic/helpers.ts
@@ -3,6 +3,21 @@ export function pageId(graph: SceneGraph) {
return graph.getPages()[0].id
}
+/** A fill that shows, so the layer takes clicks as a drawn shape does. */
+export const SOLID_FILL = {
+ type: 'SOLID' as const,
+ color: { r: 0.8, g: 0.8, b: 0.8, a: 1 },
+ opacity: 1,
+ visible: true
+}
+
export function rect(graph: SceneGraph, name: string, x = 0, y = 0, w = 50, h = 50) {
- return graph.createNode('RECTANGLE', pageId(graph), { name, x, y, width: w, height: h }).id
+ return graph.createNode('RECTANGLE', pageId(graph), {
+ name,
+ x,
+ y,
+ width: w,
+ height: h,
+ fills: [SOLID_FILL]
+ }).id
}
diff --git a/packages/scene-graph/tests/basic/hit-test.test.ts b/packages/scene-graph/tests/basic/hit-test.test.ts
index 6fcee39e4..61232e410 100644
--- a/packages/scene-graph/tests/basic/hit-test.test.ts
+++ b/packages/scene-graph/tests/basic/hit-test.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
import { expectDefined } from '../helpers/assert'
-import { pageId, rect } from './helpers'
+import { pageId, rect, SOLID_FILL } from './helpers'
describe('hitTest', () => {
test('hits a rectangle', () => {
@@ -63,6 +63,7 @@ describe('hitTest', () => {
}).id
graph.createNode('RECTANGLE', groupId, {
name: 'Child',
+ fills: [SOLID_FILL],
x: 10,
y: 10,
width: 30,
@@ -87,6 +88,7 @@ describe('hitTest', () => {
})
const childId = graph.createNode('RECTANGLE', frame.id, {
name: 'Overflow Child',
+ fills: [SOLID_FILL],
x: 50,
y: 50,
width: 200,
@@ -110,6 +112,7 @@ describe('hitTest', () => {
}).id
graph.createNode('RECTANGLE', compId, {
name: 'Inner',
+ fills: [SOLID_FILL],
x: 10,
y: 10,
width: 30,
@@ -174,3 +177,26 @@ describe('hitTest', () => {
expect(graph.hitTest(50, 50, page)?.id).toBe(rectId)
})
})
+
+describe('hitTest on drawn shapes', () => {
+ test('a click inside an unfilled line reaches the layer under it', () => {
+ const graph = new SceneGraph()
+ const below = rect(graph, 'Below', 0, 0, 300, 100)
+ const line = graph.createNode('VECTOR', pageId(graph), {
+ name: 'Line',
+ width: 300,
+ height: 100,
+ strokes: [{ ...SOLID_FILL, weight: 2, align: 'CENTER' }],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 100 },
+ { x: 300, y: 0 }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ }).id
+ expect(graph.hitTestDeep(150, 50, pageId(graph), 3.5)?.id).toBe(line)
+ expect(graph.hitTestDeep(30, 30, pageId(graph), 3.5)?.id).toBe(below)
+ })
+})
diff --git a/packages/scene-graph/tests/comments/document.test.ts b/packages/scene-graph/tests/comments/document.test.ts
index 223b6f90c..8dbe08a40 100644
--- a/packages/scene-graph/tests/comments/document.test.ts
+++ b/packages/scene-graph/tests/comments/document.test.ts
@@ -52,7 +52,13 @@ describe('document comments', () => {
const page = graph.getPages()[0]
if (!page) throw new Error('Page missing')
const frame = graph.createNode('FRAME', page.id, { x: 100, y: 50, width: 200, height: 100 })
- graph.createNode('RECTANGLE', frame.id, { x: 10, y: 10, width: 20, height: 20 })
+ graph.createNode('RECTANGLE', frame.id, {
+ x: 10,
+ y: 10,
+ width: 20,
+ height: 20,
+ fills: [{ type: 'SOLID', color: { r: 0.8, g: 0.8, b: 0.8, a: 1 }, opacity: 1, visible: true }]
+ })
const anchor = commentAnchor(graph, page.id, { x: 115, y: 65 })
expect(anchor).toMatchObject({ nodeId: frame.id, offsetX: 15, offsetY: 15 })
@@ -69,7 +75,13 @@ describe('document comments', () => {
if (!page) throw new Error('Page missing')
const section = graph.createNode('SECTION', page.id, { x: 0, y: 0, width: 800, height: 600 })
const frame = graph.createNode('FRAME', section.id, { x: 100, y: 100, width: 200, height: 100 })
- graph.createNode('RECTANGLE', frame.id, { x: 10, y: 10, width: 20, height: 20 })
+ graph.createNode('RECTANGLE', frame.id, {
+ x: 10,
+ y: 10,
+ width: 20,
+ height: 20,
+ fills: [{ type: 'SOLID', color: { r: 0.8, g: 0.8, b: 0.8, a: 1 }, opacity: 1, visible: true }]
+ })
expect(commentAnchor(graph, page.id, { x: 115, y: 115 }).nodeId).toBe(frame.id)
})
diff --git a/packages/scene-graph/tests/outline/hit.test.ts b/packages/scene-graph/tests/outline/hit.test.ts
new file mode 100644
index 000000000..5c30fd3b1
--- /dev/null
+++ b/packages/scene-graph/tests/outline/hit.test.ts
@@ -0,0 +1,640 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type Fill, type SceneNode, type Stroke } from '@open-pencil/scene-graph'
+import { getAxisAlignedWorldBounds } from '@open-pencil/scene-graph/coordinate'
+import { hitsShape } from '@open-pencil/scene-graph/outline'
+
+// Measured in Figma 126.6.12 with real clicks (scratch/pr-oracle/stroke-hit*.ts): a click selects a
+// shape inside the area a showing fill covers or on the band a showing stroke draws, either grown
+// by 3.5 screen pixels, and a shape whose paints show nothing is never selected by a click.
+const PAD = 3.5
+
+const fill = (overrides: Partial<Fill> = {}): Fill => ({
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ ...overrides
+})
+
+const stroke = (weight: number, align: Stroke['align'] = 'CENTER', overrides: Partial<Stroke> = {}): Stroke => ({
+ ...fill({ color: { r: 0, g: 0, b: 0, a: 1 } }),
+ weight,
+ align,
+ ...overrides
+})
+
+/** A Figma geometry blob for straight contours, each closed. */
+function contoursBlob(contours: Array<Array<[number, number]>>): Uint8Array {
+ const size = contours.reduce((sum, contour) => sum + contour.length * 9 + 1, 0)
+ const blob = new Uint8Array(size)
+ const view = new DataView(blob.buffer)
+ let offset = 0
+ for (const contour of contours) {
+ for (const [index, [x, y]] of contour.entries()) {
+ blob[offset++] = index === 0 ? 1 : 2
+ view.setFloat32(offset, x, true)
+ view.setFloat32(offset + 4, y, true)
+ offset += 8
+ }
+ blob[offset++] = 0
+ }
+ return blob
+}
+
+/** An open path along the x axis from 0 to `length`. */
+function straight(length: number) {
+ return {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: length, y: 0 }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+}
+
+function setup() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const add = (type: SceneNode['type'], props: Partial<SceneNode>) => graph.createNode(type, page, props)
+ const hits = (node: SceneNode, x: number, y: number, pad = PAD) => hitsShape(graph, node, x, y, pad)
+ return { graph, add, hits }
+}
+
+/** An open curve from (0, 75) to (300, 75) bowing up to its apex at (150, 0). */
+function curve(add: ReturnType<typeof setup>['add'], strokes: Stroke[], fills: Fill[] = []) {
+ return add('VECTOR', {
+ width: 300,
+ height: 75,
+ fills,
+ strokes,
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 75 },
+ { x: 300, y: 75 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: { x: 100, y: -100 }, tangentEnd: { x: -100, y: -100 } }
+ ],
+ regions: []
+ }
+ })
+}
+
+describe('a stroked shape without a fill', () => {
+ test('is hit on its curve and within 3.5 px of the stroke band, not inside its box', () => {
+ const { add, hits } = setup()
+ const line = curve(add, [stroke(2)])
+ expect(hits(line, 150, 0)).toBe(true)
+ expect(hits(line, 150, 4)).toBe(true)
+ expect(hits(line, 150, 6)).toBe(false)
+ expect(hits(line, 150, 60)).toBe(false)
+ })
+
+ test('reaches 3.5 px past a thick stroke centred on an open path', () => {
+ const { add, hits } = setup()
+ const path = add('VECTOR', { width: 300, height: 0, strokes: [stroke(10)], vectorNetwork: straight(300) })
+ expect(hits(path, 150, 8)).toBe(true)
+ expect(hits(path, 150, 9)).toBe(false)
+ })
+
+ // Measured in Figma 126 on a line layer of weight 10 (scratch/pr-oracle/line-hit.ts): its stroke
+ // runs a full weight to the line's negative y, and clicks hit from 13 px above to 3 px below.
+ test('takes a line layer by the stroke a full weight to one side of it', () => {
+ const { add, hits } = setup()
+ const line = add('LINE', { width: 300, height: 0, strokeCap: 'NONE', strokes: [stroke(10)] })
+ expect(hits(line, 150, -13)).toBe(true)
+ expect(hits(line, 150, -14)).toBe(false)
+ expect(hits(line, 150, 3)).toBe(true)
+ expect(hits(line, 150, 4)).toBe(false)
+ // Past its flat end, within the pad only.
+ expect(hits(line, 303, -5)).toBe(true)
+ expect(hits(line, 304, -5)).toBe(false)
+ })
+
+ test('scales its reach with the zoom, as the pad is screen pixels', () => {
+ const { add, hits } = setup()
+ const path = add('VECTOR', { width: 300, height: 0, strokes: [stroke(1)], vectorNetwork: straight(300) })
+ // At 400% the 0.5 unit half stroke is 2 px, so 5 px out hits and 6 px misses.
+ expect(hits(path, 150, 5 / 4, PAD / 4)).toBe(true)
+ expect(hits(path, 150, 6 / 4, PAD / 4)).toBe(false)
+ })
+
+ test('is hit on a rectangle by its inside stroke, not in its middle', () => {
+ const { add, hits } = setup()
+ const box = add('RECTANGLE', { x: 0, y: 0, width: 200, height: 150, strokes: [stroke(1, 'INSIDE')] })
+ expect(hits(box, 100, 75)).toBe(false)
+ expect(hits(box, 4, 75)).toBe(true)
+ expect(hits(box, 5, 75)).toBe(false)
+ expect(hits(box, -3, 75)).toBe(true)
+ expect(hits(box, -4, 75)).toBe(false)
+ })
+
+ test('is missed inside a closed path', () => {
+ const { add, hits } = setup()
+ const triangle = add('VECTOR', {
+ width: 200,
+ height: 200,
+ strokes: [stroke(2)],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 200 },
+ { x: 200, y: 200 },
+ { x: 100, y: 0 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 2, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
+ ],
+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]
+ }
+ })
+ expect(hits(triangle, 100, 150)).toBe(false)
+ expect(hits(triangle, 50, 200)).toBe(true)
+ })
+})
+
+describe('a filled shape', () => {
+ test('is hit inside its outline, not in the corners of its box', () => {
+ const { add, hits } = setup()
+ const ellipse = add('ELLIPSE', { width: 200, height: 200, fills: [fill()] })
+ expect(hits(ellipse, 100, 100)).toBe(true)
+ expect(hits(ellipse, 5, 5)).toBe(false)
+ expect(hits(ellipse, -3, 100)).toBe(true)
+ expect(hits(ellipse, -4, 100)).toBe(false)
+
+ const rounded = add('RECTANGLE', { x: 300, width: 200, height: 200, cornerRadius: 80, fills: [fill()] })
+ expect(hits(rounded, 303, 3)).toBe(false)
+ expect(hits(rounded, 298, 100)).toBe(true)
+ })
+
+ test('is missed in the hole of a boolean subtraction it draws without saved geometry', () => {
+ const { graph, add, hits } = setup()
+ const boolean = add('BOOLEAN_OPERATION', {
+ width: 200,
+ height: 200,
+ booleanOperation: 'SUBTRACT',
+ fills: [fill()]
+ })
+ graph.createNode('RECTANGLE', boolean.id, { width: 200, height: 200 })
+ graph.createNode('RECTANGLE', boolean.id, { x: 50, y: 50, width: 100, height: 100 })
+ expect(hits(boolean, 20, 20)).toBe(true)
+ expect(hits(boolean, 100, 100)).toBe(false)
+ })
+})
+
+describe('a boolean operation without saved geometry', () => {
+ function emptySubtraction(paints: Partial<SceneNode>) {
+ const { graph, add, hits } = setup()
+ const boolean = add('BOOLEAN_OPERATION', {
+ width: 200,
+ height: 200,
+ booleanOperation: 'SUBTRACT',
+ ...paints
+ })
+ graph.createNode('RECTANGLE', boolean.id, { width: 200, height: 200 })
+ graph.createNode('RECTANGLE', boolean.id, { width: 200, height: 200 })
+ return { boolean, hits }
+ }
+
+ test('counts no edge of an operand its result does not draw, for a fill', () => {
+ const { boolean, hits } = emptySubtraction({ fills: [fill()] })
+ expect(hits(boolean, 100, 100)).toBe(false)
+ expect(hits(boolean, 1, 100)).toBe(false)
+ expect(hits(boolean, -2, 100)).toBe(false)
+ })
+
+ test('counts no edge of an operand its result does not draw, for a stroke', () => {
+ const { boolean, hits } = emptySubtraction({ strokes: [stroke(4)] })
+ expect(hits(boolean, 0, 100)).toBe(false)
+ })
+
+ test('reaches a result thinner than the pad', () => {
+ const { graph, add, hits } = setup()
+ const boolean = add('BOOLEAN_OPERATION', {
+ width: 200,
+ height: 200,
+ booleanOperation: 'SUBTRACT',
+ fills: [fill()]
+ })
+ graph.createNode('RECTANGLE', boolean.id, { width: 200, height: 200 })
+ graph.createNode('RECTANGLE', boolean.id, { x: -10, width: 112.9, height: 200 })
+ graph.createNode('RECTANGLE', boolean.id, { x: 103.2, width: 96.8, height: 200 })
+ // The result is the strip from x 102.9 to 103.2, 2.9 units from the click.
+ expect(hits(boolean, 100, 100)).toBe(true)
+ expect(hits(boolean, 98, 100)).toBe(false)
+ })
+
+ test("reaches the edges its result draws", () => {
+ const { graph, add, hits } = setup()
+ const boolean = add('BOOLEAN_OPERATION', {
+ width: 200,
+ height: 200,
+ booleanOperation: 'SUBTRACT',
+ strokes: [stroke(2)]
+ })
+ graph.createNode('RECTANGLE', boolean.id, { width: 200, height: 200 })
+ graph.createNode('RECTANGLE', boolean.id, { x: 50, y: 50, width: 100, height: 100 })
+ expect(hits(boolean, 2, 100)).toBe(true)
+ expect(hits(boolean, 52, 100)).toBe(true)
+ expect(hits(boolean, 100, 100)).toBe(false)
+ })
+})
+
+describe('which paints take clicks', () => {
+ const cases: Array<[string, Partial<SceneNode>, boolean]> = [
+ ['no paints', {}, false],
+ ['a fill at 0% opacity', { fills: [fill({ opacity: 0 })] }, false],
+ ['a hidden fill', { fills: [fill({ visible: false })] }, false],
+ [
+ 'a gradient whose stops are all transparent',
+ {
+ fills: [
+ fill({
+ type: 'GRADIENT_LINEAR',
+ gradientStops: [
+ { position: 0, color: { r: 1, g: 0, b: 0, a: 0 } },
+ { position: 1, color: { r: 0, g: 0, b: 1, a: 0 } }
+ ]
+ })
+ ]
+ },
+ false
+ ],
+ ['a fill at 1% opacity', { fills: [fill({ opacity: 0.01 })] }, true],
+ ['a showing fill on a layer at 0% opacity', { fills: [fill()], opacity: 0 }, true]
+ ]
+ test.each(cases)('%s', (_, props, hit) => {
+ const { add, hits } = setup()
+ const box = add('RECTANGLE', { width: 200, height: 150, ...props })
+ expect(hits(box, 100, 75)).toBe(hit)
+ })
+
+ test('a stroke at 0% opacity is missed on its edge', () => {
+ const { add, hits } = setup()
+ const box = add('RECTANGLE', { width: 200, height: 150, strokes: [stroke(1, 'INSIDE', { opacity: 0 })] })
+ expect(hits(box, 0, 75)).toBe(false)
+ })
+})
+
+test('a rotated line is hit where it draws, not where it would lie unrotated', () => {
+ const { graph, add, hits } = setup()
+ const line = add('LINE', { x: 100, y: 100, width: 200, height: 0, rotation: 90, strokes: [stroke(1)] })
+ const drawn = getAxisAlignedWorldBounds(line, graph)
+ // Turned a quarter, the line stands upright: its world box is a vertical sliver.
+ expect(drawn.width).toBeLessThan(1)
+ expect(drawn.height).toBeCloseTo(200, 6)
+ expect(hits(line, drawn.x, drawn.y + 100)).toBe(true)
+ expect(hits(line, 200, 100)).toBe(false)
+})
+
+describe('outline details', () => {
+ test('a sloped line is hit along the diagonal it draws', () => {
+ const { add, hits } = setup()
+ const line = add('LINE', { width: 100, height: 100, strokes: [stroke(1)] })
+ expect(hits(line, 50, 50)).toBe(true)
+ expect(hits(line, 50, 0)).toBe(false)
+ })
+
+ test('each side of a rectangle with independent borders reaches by its own weight', () => {
+ const { add, hits } = setup()
+ const box = add('RECTANGLE', {
+ width: 200,
+ height: 150,
+ strokes: [stroke(1, 'INSIDE')],
+ independentStrokeWeights: true,
+ borderTopWeight: 20,
+ borderRightWeight: 1,
+ borderBottomWeight: 1,
+ borderLeftWeight: 1
+ })
+ // 15 units in from the thick top border is on it; 15 in from the thin left one is not.
+ expect(hits(box, 100, 15)).toBe(true)
+ expect(hits(box, 15, 75)).toBe(false)
+ })
+
+ test("a fill's pad follows the filled area, not a stray open segment", () => {
+ const { add, hits } = setup()
+ const shape = add('VECTOR', {
+ width: 300,
+ height: 100,
+ fills: [fill()],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ { x: 300, y: 50 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 2, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 2, end: 3, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
+ ],
+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]
+ }
+ })
+ expect(hits(shape, 80, 20)).toBe(true)
+ // On the unstroked open segment, far from the triangle.
+ expect(hits(shape, 200, 75)).toBe(false)
+ })
+
+ test('a loop naming a negative segment index adds no geometry', () => {
+ const { add, hits } = setup()
+ const shape = add('VECTOR', {
+ width: 100,
+ height: 100,
+ fills: [fill()],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
+ ],
+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, -1]] }]
+ }
+ })
+ // Without the stray index the loop is the triangle (0,0)–(100,0)–(100,100), closed back.
+ expect(hits(shape, 80, 20)).toBe(true)
+ expect(hits(shape, 20, 80)).toBe(false)
+ })
+
+ test('a loop naming a fractional segment index adds no geometry', () => {
+ const { add, hits } = setup()
+ const shape = add('VECTOR', {
+ width: 100,
+ height: 100,
+ fills: [fill()],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
+ ],
+ regions: [{ windingRule: 'NONZERO', loops: [[0.5, 1]] }]
+ }
+ })
+ // Read as segment 0, the stray index would close a triangle over (80, 20).
+ expect(hits(shape, 80, 20)).toBe(false)
+ })
+
+ test('an open network centres its stroke even when its fill geometry is saved', () => {
+ const { add, hits } = setup()
+ const blob = new Uint8Array(1 + 8 + 1 + 8 + 1 + 8 + 1)
+ const view = new DataView(blob.buffer)
+ let offset = 0
+ const command = (code: number, ...points: number[]) => {
+ blob[offset++] = code
+ for (const value of points) {
+ view.setFloat32(offset, value, true)
+ offset += 4
+ }
+ }
+ command(1, 0, 0)
+ command(2, 100, 0)
+ command(2, 100, 100)
+ command(0)
+ const shape = add('VECTOR', {
+ width: 100,
+ height: 100,
+ strokes: [stroke(10, 'INSIDE')],
+ fillGeometry: [{ windingRule: 'NONZERO', commandsBlob: blob }],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
+ ],
+ regions: []
+ }
+ })
+ // 4 units outside the top segment lies on its centred 10-unit band.
+ expect(hits(shape, 50, -4)).toBe(true)
+ })
+
+ test('independent borders follow rounded corners', () => {
+ const { add, hits } = setup()
+ const box = add('RECTANGLE', {
+ width: 100,
+ height: 100,
+ cornerRadius: 50,
+ strokes: [stroke(1, 'INSIDE')],
+ independentStrokeWeights: true,
+ borderTopWeight: 10,
+ borderRightWeight: 1,
+ borderBottomWeight: 1,
+ borderLeftWeight: 1
+ })
+ // 5 units in from the rounded corner lies on the 10-unit top border drawn round it.
+ expect(hits(box, 18.2, 18.2)).toBe(true)
+ // The square corner outside the curve is empty.
+ expect(hits(box, 1, 1)).toBe(false)
+ })
+
+ test('a flat cap ends an open path at its end; a round one paints past it', () => {
+ const { add, hits } = setup()
+ const flat = add('VECTOR', { width: 100, height: 0, strokeCap: 'NONE', strokes: [stroke(20)], vectorNetwork: straight(100) })
+ // 8 units past the end, on the path's axis.
+ expect(hits(flat, 108, 0)).toBe(false)
+ expect(hits(flat, 103, 0)).toBe(true)
+ const round = add('VECTOR', { width: 100, height: 0, strokeCap: 'ROUND', strokes: [stroke(20)], vectorNetwork: straight(100) })
+ expect(hits(round, 108, 0)).toBe(true)
+ })
+
+ test('an arrow head on a line layer takes clicks across its full width', () => {
+ const { add, hits } = setup()
+ const arrow = add('LINE', {
+ width: 200,
+ height: 0,
+ strokeCap: 'TRIANGLE_FILLED',
+ strokes: [stroke(4)]
+ })
+ // The head spreads about 11.5 units either side of the shaft at its base, here 10 below it.
+ expect(hits(arrow, 197, 8)).toBe(true)
+ expect(hits(arrow, 197, 14)).toBe(false)
+ // The shaft alone reaches no further than its band and the pad.
+ expect(hits(arrow, 100, 8)).toBe(false)
+ })
+
+ test("a line arrow's wings take clicks on an open path", () => {
+ const { add, hits } = setup()
+ const path = add('VECTOR', {
+ width: 200,
+ height: 0,
+ strokeCap: 'ARROW_LINES',
+ strokes: [stroke(2)],
+ vectorNetwork: straight(200)
+ })
+ // Beside the lower wing, which runs 9 units back from the tip at 45°: off the shaft's reach.
+ expect(hits(path, 194.5, 5.8)).toBe(true)
+ expect(hits(path, 188, 10)).toBe(false)
+ })
+
+ test("a line's caps end where the line does", () => {
+ const { add, hits } = setup()
+ const round = add('LINE', { width: 100, height: 0, strokeCap: 'ROUND', strokes: [stroke(20)] })
+ // The cap is drawn inside the line's length, so 8 past the end is beyond the pad.
+ expect(hits(round, 108, -10)).toBe(false)
+ expect(hits(round, 103, -10)).toBe(true)
+ })
+
+ test('a closed network without regions keeps its stroke alignment when stroke geometry is saved', () => {
+ const { add, hits } = setup()
+ const network = {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
+ { start: 2, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
+ ],
+ regions: []
+ }
+ const saved = add('VECTOR', {
+ width: 100,
+ height: 100,
+ strokes: [stroke(10, 'INSIDE')],
+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: new Uint8Array([0]) }],
+ vectorNetwork: network
+ })
+ // 4.5 units outside the top edge: an inside stroke draws nothing there.
+ expect(hits(saved, 50, -4.5)).toBe(false)
+ const drawnCentred = add('VECTOR', {
+ width: 100,
+ height: 100,
+ strokes: [stroke(10, 'INSIDE')],
+ vectorNetwork: network
+ })
+ expect(hits(drawnCentred, 50, -4.5)).toBe(true)
+ })
+
+ test('loops that cancel under even-odd fill take no clicks on their shared edge', () => {
+ const { add, hits } = setup()
+ const square: Array<[number, number]> = [
+ [0, 0],
+ [100, 0],
+ [100, 100],
+ [0, 100]
+ ]
+ const shape = add('VECTOR', {
+ width: 100,
+ height: 100,
+ fills: [fill()],
+ fillGeometry: [{ windingRule: 'EVENODD', commandsBlob: contoursBlob([square, square]) }]
+ })
+ expect(hits(shape, 50, 50)).toBe(false)
+ expect(hits(shape, 50, 1)).toBe(false)
+ })
+
+ test('a side with no border weight takes no clicks', () => {
+ const { add, hits } = setup()
+ const box = add('RECTANGLE', {
+ width: 200,
+ height: 150,
+ strokes: [stroke(1, 'INSIDE')],
+ independentStrokeWeights: true,
+ borderTopWeight: 4,
+ borderRightWeight: 0,
+ borderBottomWeight: 4,
+ borderLeftWeight: 4
+ })
+ expect(hits(box, 199, 75)).toBe(false)
+ expect(hits(box, 1, 75)).toBe(true)
+ })
+
+ test('past a flat end the reach is measured from the painted corner', () => {
+ const { add, hits } = setup()
+ const path = add('VECTOR', { width: 100, height: 0, strokeCap: 'NONE', strokes: [stroke(20)], vectorNetwork: straight(100) })
+ // 4.24 units from the corner (100, 10): beyond the 3.5 pad.
+ expect(hits(path, 103, 13)).toBe(false)
+ expect(hits(path, 102, 11)).toBe(true)
+ })
+
+ test('without a network or fill geometry a stroke is still hit on its saved outline only', () => {
+ const { add, hits } = setup()
+ const band: Array<[number, number]> = [
+ [0, -2],
+ [100, -2],
+ [100, 2],
+ [0, 2]
+ ]
+ const strokeOnly = add('VECTOR', {
+ width: 100,
+ height: 100,
+ strokes: [stroke(4)],
+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: contoursBlob([band]) }]
+ })
+ expect(hits(strokeOnly, 50, 0)).toBe(true)
+ // In the layer's empty box, away from the painted stroke.
+ expect(hits(strokeOnly, 50, 60)).toBe(false)
+ })
+
+ test('without a network a stroke is hit on its saved stroke outline only', () => {
+ const { add, hits } = setup()
+ const triangle: Array<[number, number]> = [
+ [0, 0],
+ [100, 0],
+ [100, 100]
+ ]
+ // The stroke outline: a 4-unit band along the top edge only.
+ const band: Array<[number, number]> = [
+ [0, -2],
+ [100, -2],
+ [100, 2],
+ [0, 2]
+ ]
+ const withOutline = add('VECTOR', {
+ width: 100,
+ height: 100,
+ strokes: [stroke(4)],
+ fillGeometry: [{ windingRule: 'NONZERO', commandsBlob: contoursBlob([triangle]) }],
+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: contoursBlob([band]) }]
+ })
+ expect(hits(withOutline, 50, 0)).toBe(true)
+ // On the triangle's closing edge, which no stroke draws.
+ expect(hits(withOutline, 50, 50)).toBe(false)
+ const withoutOutline = add('VECTOR', {
+ width: 100,
+ height: 100,
+ strokes: [stroke(4)],
+ fillGeometry: [{ windingRule: 'NONZERO', commandsBlob: contoursBlob([triangle]) }]
+ })
+ expect(hits(withoutOutline, 50, 0)).toBe(false)
+ })
+
+ test("a huge ellipse's edge stays within the pad at the maximum zoom", () => {
+ const { add, hits } = setup()
+ const radius = 50_000
+ const ellipse = add('ELLIPSE', { width: radius * 2, height: radius * 2, fills: [fill()] })
+ const pad = PAD / 256
+ // Just inside the rim, midway along the first chord of a 1,024-step polygon, which cuts the
+ // rim there by about 0.24 units, far more than the 0.014-unit pad.
+ const angle = Math.PI / 1024
+ const r = radius - pad / 2
+ expect(hits(ellipse, radius + r * Math.cos(angle), radius + r * Math.sin(angle), pad)).toBe(true)
+ })
+})
+
+test('text is left to its box', () => {
+ const { add, hits } = setup()
+ const text = add('TEXT', { width: 100, height: 20, text: 'Label' })
+ expect(hits(text, 50, 10)).toBeNull()
+})
diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.ts
index 48bc5d784..4e3398959 100644
--- a/packages/scene-graph/tsdown.config.ts
+++ b/packages/scene-graph/tsdown.config.ts
@@ -36,6 +36,7 @@ export default defineConfig({
'mutation-impact': './src/mutation-impact.ts',
'node-defaults': './src/node-defaults.ts',
'order-keys': './src/order-keys.ts',
+ 'outline/index': './src/outline/index.ts',
'paints/index': './src/paints/index.ts',
'parse-path': './src/parse-path.ts',
'plugin-data/index': './src/plugin-data/index.ts',
diff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.ts
index d94341056..63d5205ea 100644
--- a/packages/vue/src/canvas/text-edit/input.ts
+++ b/packages/vue/src/canvas/text-edit/input.ts
@@ -1,4 +1,5 @@
import { getNodeEditCapability, resolveEditorProfile, type Editor } from '@open-pencil/core'
+import { LAYER_HIT_PAD } from '@open-pencil/core/constants'
import type { SceneNode } from '@open-pencil/scene-graph'
import { generatedFrameOwner, generatedFrameText } from '@open-pencil/scene-graph/generated'
@@ -107,8 +108,10 @@ export function createTextEditInput(options: TextEditInputOptions) {
cx: number,
cy: number
): SceneNode | null {
- // Double-clicking goes one level into the container, as in Figma.
- const hit = editor.graph.hitTestSelectable(cx, cy, containerId, new Set())
+ // Double-clicking goes one level into the container, as in Figma, taking a click as near a
+ // layer as a press does: thin strokes are hit within the same few screen pixels.
+ const pad = LAYER_HIT_PAD / (editor.renderer?.zoom ?? editor.state.zoom)
+ const hit = editor.graph.hitTestSelectable(cx, cy, containerId, new Set(), { pad })
if (hit) return hit
return editor.graph.isPointInNode(containerId, cx, cy)
? (editor.graph.getNode(containerId) ?? null)
diff --git a/packages/vue/tests/shared/input/select/hit.test.ts b/packages/vue/tests/shared/input/select/hit.test.ts
index 8c842f983..8d7ef931a 100644
--- a/packages/vue/tests/shared/input/select/hit.test.ts
+++ b/packages/vue/tests/shared/input/select/hit.test.ts
@@ -72,7 +72,8 @@ function swatchRows() {
const swatch = editor.graph.createNode('RECTANGLE', frame.id, {
name: `${frame.name} swatch`,
width: 120,
- height: 60
+ height: 60,
+ fills: [{ type: 'SOLID', color: { r: 0.8, g: 0.8, b: 0.8, a: 1 }, opacity: 1, visible: true }]
})
return { frame, swatch }
}
diff --git a/tests/app/comments/session.test.ts b/tests/app/comments/session.test.ts
index 925ad6246..cba2c7f8a 100644
--- a/tests/app/comments/session.test.ts
+++ b/tests/app/comments/session.test.ts
@@ -103,7 +103,13 @@ test('comments written to the document from elsewhere show up', async () => {
test('a pin stays where its layer was when the layer is deleted, even if it was never drawn', async () => {
const store = openDocument()
const pageId = store.state.currentPageId
- const rect = store.graph.createNode('RECTANGLE', pageId, { x: 100, y: 50, width: 80, height: 40 })
+ const rect = store.graph.createNode('RECTANGLE', pageId, {
+ x: 100,
+ y: 50,
+ width: 80,
+ height: 40,
+ fills: [{ type: 'SOLID', color: { r: 0.8, g: 0.8, b: 0.8, a: 1 }, opacity: 1, visible: true }]
+ })
const pinned = comment(store, 110, 55, 'on the rectangle')
expect(pinned.nodeId).toBe(rect.id)
diff --git a/tests/e2e/canvas/distance-measurement.spec.ts b/tests/e2e/canvas/distance-measurement.spec.ts
index fdec1d74a..783561186 100644
--- a/tests/e2e/canvas/distance-measurement.spec.ts
+++ b/tests/e2e/canvas/distance-measurement.spec.ts
@@ -79,7 +79,8 @@ test('deep measurement modifier targets a nested component child', async () => {
x: 30,
y: 30,
width: 80,
- height: 60
+ height: 60,
+ fills: [{ type: 'SOLID', color: { r: 0.8, g: 0.8, b: 0.8, a: 1 }, visible: true, opacity: 1 }]
})
store.select([selected.id])
store.requestRender()
diff --git a/tests/e2e/canvas/thin-stroke-drill.spec.ts b/tests/e2e/canvas/thin-stroke-drill.spec.ts
new file mode 100644
index 000000000..925e85eb5
--- /dev/null
+++ b/tests/e2e/canvas/thin-stroke-drill.spec.ts
@@ -0,0 +1,30 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { clickDepthDriver } from '#tests/helpers/canvas/click-depth/driver'
+
+// Measured in Figma desktop 126 on the shadcn kit's line chart: from the selected component,
+// double-clicks on its curve go one level each, to the group and then the curve, at any zoom.
+// Zoomed out, the curve's 2-unit stroke is under a pixel wide, so the click is taken within a few
+// screen pixels of it, as a press is.
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+const scene = clickDepthDriver(() => editor.page)
+
+test('double-clicks drill to a thin unfilled curve in a component when zoomed out', async () => {
+ const { component, group, curve } = await scene.componentChart()
+ await scene.zoomTo(0.44)
+ await editor.canvas.waitForRender()
+ // On the curve's apex, 2 screen pixels below its centre line: 4.5 units at 44%.
+ const apex = await scene.at(component, 20 + 150, 60 + 0)
+ const point = { x: apex.x, y: apex.y + 2 }
+
+ await editor.canvas.click(point.x, point.y)
+ await expect.poll(async () => (await scene.state()).selected).toEqual([component])
+
+ await editor.canvas.dblclick(point.x, point.y)
+ await expect.poll(async () => (await scene.state()).selected).toEqual([group])
+
+ await editor.canvas.dblclick(point.x, point.y)
+ await expect.poll(async () => (await scene.state()).selected).toEqual([curve])
+ editor.canvas.assertNoErrors()
+})
diff --git a/tests/engine/hit-test/basic.test.ts b/tests/engine/hit-test/basic.test.ts
index c80bd586e..5149614e6 100644
--- a/tests/engine/hit-test/basic.test.ts
+++ b/tests/engine/hit-test/basic.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { SOLID_FILL } from '#tests/helpers/scene'
+
function pageId(graph: SceneGraph) {
return graph.getPages()[0].id
}
@@ -11,6 +13,7 @@ describe('hitTest — hidden nodes', () => {
const graph = new SceneGraph()
const page = pageId(graph)
const rect = graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'R',
x: 100,
y: 100,
@@ -27,6 +30,7 @@ describe('hitTest — hidden nodes', () => {
const graph = new SceneGraph()
const page = pageId(graph)
graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'R',
x: 100,
y: 100,
@@ -50,6 +54,7 @@ describe('hitTest — hidden nodes', () => {
height: 200
})
graph.createNode('RECTANGLE', frame.id, {
+ fills: [SOLID_FILL],
name: 'R',
x: 50,
y: 50,
@@ -78,6 +83,7 @@ describe('hitTest — locked nodes', () => {
locked: true
})
graph.createNode('RECTANGLE', group.id, {
+ fills: [SOLID_FILL],
name: 'R',
x: 50,
y: 50,
@@ -103,6 +109,7 @@ describe('hitTest — locked nodes', () => {
height: 200
})
const rect = graph.createNode('RECTANGLE', frame.id, {
+ fills: [SOLID_FILL],
name: 'R',
x: 50,
y: 50,
@@ -121,6 +128,7 @@ describe('hitTest — opacity', () => {
const graph = new SceneGraph()
const page = pageId(graph)
const rect = graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'R',
x: 100,
y: 100,
@@ -148,6 +156,7 @@ describe('hitTest — point outside all nodes', () => {
const graph = new SceneGraph()
const page = pageId(graph)
graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'R',
x: 100,
y: 100,
@@ -172,6 +181,7 @@ describe('hitTest — deep mode', () => {
height: 200
})
graph.createNode('RECTANGLE', component.id, {
+ fills: [SOLID_FILL],
name: 'R',
x: 50,
y: 50,
@@ -195,6 +205,7 @@ describe('hitTest — z-order (last child wins)', () => {
const graph = new SceneGraph()
const page = pageId(graph)
const rect1 = graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'R1',
x: 0,
y: 0,
@@ -202,6 +213,7 @@ describe('hitTest — z-order (last child wins)', () => {
height: 100
})
const rect2 = graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'R2',
x: 0,
y: 0,
diff --git a/tests/engine/hit-test/scope.test.ts b/tests/engine/hit-test/scope.test.ts
index 703ff3796..12c328e21 100644
--- a/tests/engine/hit-test/scope.test.ts
+++ b/tests/engine/hit-test/scope.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'
+import { SOLID_FILL } from '#tests/helpers/scene'
function pageId(graph: SceneGraph) {
return graph.getPages()[0].id
@@ -20,6 +21,7 @@ describe('hitTest — group behavior', () => {
height: 200
})
const child = graph.createNode('RECTANGLE', group.id, {
+ fills: [SOLID_FILL],
name: 'Rect',
x: 10,
y: 10,
@@ -82,6 +84,7 @@ describe('hitTest — nested groups', () => {
height: 100
})
const rect = graph.createNode('RECTANGLE', groupB.id, {
+ fills: [SOLID_FILL],
name: 'DeepRect',
x: 10,
y: 10,
@@ -136,6 +139,7 @@ describe('hitTest — locked nodes', () => {
locked: true
})
graph.createNode('RECTANGLE', frame.id, {
+ fills: [SOLID_FILL],
name: 'Child',
x: 10,
y: 10,
@@ -152,6 +156,7 @@ describe('hitTest — locked nodes', () => {
const graph = new SceneGraph()
const page = pageId(graph)
graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'LockedRect',
x: 0,
y: 0,
@@ -171,6 +176,7 @@ describe('hitTest — visibility', () => {
const graph = new SceneGraph()
const page = pageId(graph)
graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'Hidden',
x: 0,
y: 0,
@@ -189,6 +195,7 @@ describe('scene graph — locked node operations', () => {
const graph = new SceneGraph()
const page = pageId(graph)
const rect = graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'LockedRect',
x: 0,
y: 0,
@@ -206,6 +213,7 @@ describe('scene graph — locked node operations', () => {
const graph = new SceneGraph()
const page = pageId(graph)
const rect = graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'Rect',
x: 0,
y: 0,
@@ -224,6 +232,7 @@ describe('scene graph — locked node operations', () => {
const graph = new SceneGraph()
const page = pageId(graph)
const rect = graph.createNode('RECTANGLE', page, {
+ fills: [SOLID_FILL],
name: 'Rect',
x: 0,
y: 0,
@@ -251,6 +260,7 @@ describe('hitTest — frame with children', () => {
height: 200
})
const child = graph.createNode('RECTANGLE', frame.id, {
+ fills: [SOLID_FILL],
name: 'InnerRect',
x: 20,
y: 20,
@@ -275,6 +285,7 @@ describe('hitTest — frame with children', () => {
rotation: 45
})
const child = graph.createNode('RECTANGLE', frame.id, {
+ fills: [SOLID_FILL],
name: 'InnerRect',
x: 60,
y: 30,
@@ -298,6 +309,7 @@ describe('hitTest — frame with children', () => {
const left = graph.createNode('FRAME', page, { x: 100, y: 100, width: 200, height: 100 })
const right = graph.createNode('FRAME', page, { x: 400, y: 100, width: 200, height: 100 })
const child = graph.createNode('RECTANGLE', left.id, {
+ fills: [SOLID_FILL],
x: 20,
y: 20,
width: 40,
@@ -331,6 +343,7 @@ describe('hitTest — frame with children', () => {
flipX: true
})
const child = graph.createNode('RECTANGLE', frame.id, {
+ fills: [SOLID_FILL],
x: 20,
y: 20,
width: 40,
@@ -354,6 +367,7 @@ describe('hitTest — opaque containers (COMPONENT/INSTANCE)', () => {
height: 100
})
graph.createNode('RECTANGLE', comp.id, {
+ fills: [SOLID_FILL],
name: 'CompChild',
x: 10,
y: 10,
@@ -377,6 +391,7 @@ describe('hitTest — opaque containers (COMPONENT/INSTANCE)', () => {
height: 100
})
const child = graph.createNode('RECTANGLE', comp.id, {
+ fills: [SOLID_FILL],
name: 'CompChild',
x: 10,
y: 10,
@@ -400,6 +415,7 @@ describe('hitTest — opaque containers (COMPONENT/INSTANCE)', () => {
height: 80
})
graph.createNode('RECTANGLE', inst.id, {
+ fills: [SOLID_FILL],
name: 'InstChild',
x: 5,
y: 5,
@@ -423,6 +439,7 @@ describe('hitTest — opaque containers (COMPONENT/INSTANCE)', () => {
height: 80
})
const child = graph.createNode('RECTANGLE', inst.id, {
+ fills: [SOLID_FILL],
name: 'InstChild',
x: 5,
y: 5,
@@ -448,6 +465,7 @@ describe('hitTest — absolute position and scope offset', () => {
height: 400
})
const child = graph.createNode('RECTANGLE', frame.id, {
+ fills: [SOLID_FILL],
name: 'Child',
x: 50,
y: 60,
diff --git a/tests/helpers/canvas/click-depth/driver.ts b/tests/helpers/canvas/click-depth/driver.ts
index 758438102..fa4380be5 100644
--- a/tests/helpers/canvas/click-depth/driver.ts
+++ b/tests/helpers/canvas/click-depth/driver.ts
@@ -2,7 +2,7 @@ import type { Page } from '@playwright/test'
import type * as ClickDepthScenes from '#tests/helpers/canvas/click-depth/scene'
-type SceneName = 'createClickDepthCards' | 'createNestedBoard'
+type SceneName = 'createClickDepthCards' | 'createNestedBoard' | 'createComponentChart'
/** Builds click-depth scenes and reads back what pointer input selected, hovered, or moved. */
/** `page` is read on each call, so a spec can create the driver before its page exists. */
@@ -23,6 +23,19 @@ export function clickDepthDriver(page: () => Page) {
return {
cards: () => build('createClickDepthCards'),
nestedBoard: () => build('createNestedBoard'),
+ componentChart: () => build('createComponentChart'),
+
+ /** Shows the page at `zoom` with the canvas origin at the top left. */
+ zoomTo(zoom: number) {
+ return page().evaluate((level) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.state.zoom = level
+ store.state.panX = 0
+ store.state.panY = 0
+ store.requestRender()
+ }, zoom)
+ },
/** Canvas coordinates of a point given relative to a node's top-left corner. */
at(id: string, dx: number, dy: number) {
diff --git a/tests/helpers/canvas/click-depth/scene.ts b/tests/helpers/canvas/click-depth/scene.ts
index d5c5ef573..1f1aba42c 100644
--- a/tests/helpers/canvas/click-depth/scene.ts
+++ b/tests/helpers/canvas/click-depth/scene.ts
@@ -80,3 +80,48 @@ export function createNestedBoard(graph: SceneGraph, pageId: string) {
})
return { grid: grid.id, cell: cell.id, label: label.id }
}
+
+/**
+ * A top-level component holding a group with an unfilled curve drawn by a 2-unit stroke, as the
+ * shadcn kit's line chart is built; the curve runs from (0, 80) to (300, 80) bowing up to y 0.
+ */
+export function createComponentChart(graph: SceneGraph, pageId: string) {
+ const component = graph.createNode('COMPONENT', pageId, {
+ name: 'Chart',
+ x: 100,
+ y: 100,
+ width: 340,
+ height: 200,
+ fills: fill(1, 1, 1)
+ })
+ const group = graph.createNode('GROUP', component.id, {
+ name: 'Plot',
+ x: 20,
+ y: 60,
+ width: 300,
+ height: 80
+ })
+ const curve = graph.createNode('VECTOR', group.id, {
+ name: 'Curve',
+ width: 300,
+ height: 80,
+ fills: [],
+ strokes: [{ ...fill(0, 0, 0)[0], weight: 2, align: 'CENTER' }],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 80 },
+ { x: 300, y: 80 }
+ ],
+ segments: [
+ {
+ start: 0,
+ end: 1,
+ tangentStart: { x: 100, y: -107 },
+ tangentEnd: { x: -100, y: -107 }
+ }
+ ],
+ regions: []
+ }
+ })
+ return { component: component.id, group: group.id, curve: curve.id }
+}
diff --git a/tests/helpers/scene.ts b/tests/helpers/scene.ts
index 8c6c3d7f5..b2195be00 100644
--- a/tests/helpers/scene.ts
+++ b/tests/helpers/scene.ts
@@ -2,6 +2,14 @@ import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { computeImageHash } from '@open-pencil/scene-graph/images'
import type { Color } from '@open-pencil/scene-graph/primitives'
+/** A fill that shows, so a shape takes clicks and hover as a drawn one does in Figma. */
+export const SOLID_FILL = {
+ type: 'SOLID' as const,
+ color: { r: 0.8, g: 0.8, b: 0.8, a: 1 },
+ opacity: 1,
+ visible: true
+}
+
export function makeSceneGraph(pageName = 'Test'): SceneGraph {
const graph = new SceneGraph()
graph.addPage(pageName)