Skip to content

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

feat(canvas): render arrow stroke caps on lines and open vectors

Ed-Key9b48e473290f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 45f173508..dc2e8a48b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
### Added
+- Render triangle and line arrow stroke caps on lines and open vector paths, and choose them from the stroke cap picker.
- Add a timestamp-faithful pan and zoom benchmark workflow with physical macOS trackpad recording, CDP and DOM replay, Chromium traces, frame-pacing and latency distributions, zoom-anchor drift and viewport-jump detection, retained-backing settlement metrics, and a documented native Instruments acceptance procedure.
- Choose and persist the app interface language from General settings.
diff --git a/packages/core/src/canvas/renderer/visual-bounds.ts b/packages/core/src/canvas/renderer/visual-bounds.ts
index 5b8d78fa2..fe5223978 100644
--- a/packages/core/src/canvas/renderer/visual-bounds.ts
+++ b/packages/core/src/canvas/renderer/visual-bounds.ts
@@ -8,7 +8,7 @@ import {
import Matrix from '@open-pencil/scene-graph/matrix'
export function worldNodeVisualBounds(graph: SceneGraph, node: SceneNode): VisualBounds {
- const stroke = strokeOverflow(node.strokes)
+ const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork)
const effects = effectOverflow(node.effects)
const points = Matrix.mapPoints(getWorldMatrix(node, graph), [
-stroke - effects.left,
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index dda7c1825..9ba9db79a 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -8,6 +8,12 @@ import {
type SceneGraph,
type Fill
} from '@open-pencil/scene-graph'
+import type { ArrowEndpoint } from '@open-pencil/scene-graph/arrow-caps'
+import {
+ arrowCapOverflow,
+ collectArrowEndpoints,
+ lineArrowEndpoints
+} from '@open-pencil/scene-graph/arrow-caps'
import { computeDescendantVisualBounds } from '@open-pencil/scene-graph/geometry'
import Matrix from '@open-pencil/scene-graph/matrix'
import type { Color } from '@open-pencil/scene-graph/primitives'
@@ -34,6 +40,7 @@ import {
import { makeSmoothRRectPath, nodeHasRadius, nodeHasSmoothCorners } from './shapes'
import {
configureStrokePaint,
+ drawArrowHeads,
drawDashedRRectWithSolidCorners,
drawStyledRRectStroke,
getStrokeCapEntity,
@@ -522,7 +529,10 @@ export function renderShape(
return
}
- const margin = r.effectOverflow(node)
+ const margin = Math.max(
+ r.effectOverflow(node),
+ arrowCapOverflow(node.strokes, node.strokeCap, node.vectorNetwork)
+ )
const width = node.width + margin * 2
const height = node.height + margin * 2
const scale = targetScale
@@ -784,6 +794,30 @@ function isPathTextWithStrokeGeometry(node: SceneNode): boolean {
)
}
+/**
+ * Draws arrow-cap heads for a stroke on the node types that carry open path
+ * ends. Runs after the shaft regardless of which branch painted it, so heads
+ * survive fills, non-center alignment, corner radii, and dashed shafts.
+ */
+function drawNodeArrowHeads(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ stroke: SceneNode['strokes'][0],
+ color: Color
+): void {
+ const cap = stroke.cap ?? node.strokeCap
+ let endpoints: ArrowEndpoint[] = []
+ if (node.type === 'LINE') {
+ endpoints = lineArrowEndpoints(node.width, node.height, cap)
+ } else if (node.type === 'VECTOR' && node.vectorNetwork) {
+ endpoints = collectArrowEndpoints(node.vectorNetwork, cap)
+ }
+ if (endpoints.length > 0) {
+ drawArrowHeads(r, canvas, endpoints, stroke.weight, color, stroke.opacity)
+ }
+}
+
function paintNodeStrokes(
r: SkiaRenderer,
canvas: Canvas,
@@ -805,9 +839,11 @@ function paintNodeStrokes(
const centerline = vectorNetworkToCenterlinePath(r.ck, node.vectorNetwork)
drawVectorPathStrokes(r, canvas, [centerline], stroke, color, node.strokeMiterLimit)
centerline.delete()
+ drawNodeArrowHeads(r, canvas, node, stroke, color)
return
}
drawNodeStroke(r, canvas, node, rect, hasRadius, stroke, color, sg, vectorPaths, vectorStroke)
+ drawNodeArrowHeads(r, canvas, node, stroke, color)
})
}
diff --git a/packages/core/src/canvas/strokes.ts b/packages/core/src/canvas/strokes.ts
index 2b2a380b3..4e50d8f15 100644
--- a/packages/core/src/canvas/strokes.ts
+++ b/packages/core/src/canvas/strokes.ts
@@ -1,6 +1,8 @@
import type { Canvas, EmbindEnumEntity, Paint } from 'canvaskit-wasm'
import type { SceneNode, Stroke } from '@open-pencil/scene-graph'
+import type { ArrowEndpoint } from '@open-pencil/scene-graph/arrow-caps'
+import { arrowLinesSegments, equilateralArrowPoints } from '@open-pencil/scene-graph/arrow-caps'
import type { Color } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from './renderer'
@@ -96,6 +98,51 @@ export function drawDashedRRectWithSolidCorners(
r.strokePaint.setPathEffect(null)
}
+/**
+ * Draws arrow heads at open path endpoints in the stroke's color. The shaft
+ * is expected to be drawn separately; heads overlay its terminal segment.
+ */
+export function drawArrowHeads(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ endpoints: ArrowEndpoint[],
+ weight: number,
+ color: Color,
+ opacity: number
+): void {
+ for (const endpoint of endpoints) {
+ if (endpoint.cap === 'ARROW_EQUILATERAL') {
+ const [tip, left, right] = equilateralArrowPoints(
+ endpoint.x,
+ endpoint.y,
+ endpoint.angle,
+ weight
+ )
+ const builder = new r.ck.PathBuilder()
+ builder.moveTo(tip.x, tip.y)
+ builder.lineTo(left.x, left.y)
+ builder.lineTo(right.x, right.y)
+ builder.close()
+ const path = builder.detachAndDelete()
+ r.fillPaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ r.fillPaint.setAlphaf(opacity)
+ r.fillPaint.setShader(null)
+ canvas.drawPath(path, r.fillPaint)
+ path.delete()
+ } else {
+ r.strokePaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ r.strokePaint.setAlphaf(opacity)
+ r.strokePaint.setStrokeWidth(weight)
+ r.strokePaint.setStrokeCap(r.ck.StrokeCap.Butt)
+ r.strokePaint.setPathEffect(null)
+ r.strokePaint.setShader(null)
+ for (const wing of arrowLinesSegments(endpoint.x, endpoint.y, endpoint.angle, weight)) {
+ canvas.drawLine(wing.from.x, wing.from.y, wing.to.x, wing.to.y, r.strokePaint)
+ }
+ }
+ }
+}
+
export function configureStrokePaint(
r: SkiaRenderer,
node: SceneNode,
diff --git a/packages/core/src/figma-api/render-bounds.ts b/packages/core/src/figma-api/render-bounds.ts
index 03be6040c..06cb9d880 100644
--- a/packages/core/src/figma-api/render-bounds.ts
+++ b/packages/core/src/figma-api/render-bounds.ts
@@ -76,7 +76,7 @@ function ownRenderBounds(node: SceneNode, graph: SceneGraph): VisualBounds | nul
if (!hasRenderableGeometry(node)) return null
const base = transformedRect(node, graph, 0, 0, node.width, node.height)
- const stroke = strokeOverflow(node.strokes)
+ const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork)
let bounds = transformedRect(
node,
graph,
diff --git a/packages/core/src/tools/analyze/overlaps/helpers.ts b/packages/core/src/tools/analyze/overlaps/helpers.ts
index c6a510df2..fec2746c3 100644
--- a/packages/core/src/tools/analyze/overlaps/helpers.ts
+++ b/packages/core/src/tools/analyze/overlaps/helpers.ts
@@ -278,7 +278,7 @@ function computeNodeVisualBounds(node: SceneNode, graph: SceneGraph): VisualBoun
// through the world matrix. Expanding the already-rotated AABB by `stroke`
// underestimates the stroked bounds for rotated nodes (the true stroked AABB
// grows by `stroke * (|cos θ| + |sin θ|)`, not `stroke`).
- const stroke = strokeOverflow(node.strokes)
+ const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork)
const baseCorners = Matrix.mapPoints(matrix, [
-stroke,
-stroke,
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 9a5e1049a..e92be05e6 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -486,10 +486,10 @@ function convertLayoutProps(
}
}
-function getVectorStrokeCap(nc: NodeChange, vectorNetwork: VectorNetwork | null): StrokeCap {
- return (nc.strokeCap ??
- vectorNetwork?.vertices.find((v) => v.strokeCap)?.strokeCap ??
- 'NONE') as StrokeCap
+function getVectorStrokeCap(nc: NodeChange): StrokeCap {
+ // Per-vertex caps stay on the vector network; promoting one to the node
+ // cap would put a head on both ends of a one-ended arrow.
+ return (nc.strokeCap ?? 'NONE') as StrokeCap
}
function getVectorStrokeJoin(nc: NodeChange, vectorNetwork: VectorNetwork | null): StrokeJoin {
@@ -549,7 +549,7 @@ function convertTextPathData(nc: NodeChange, blobs: Uint8Array[]): SceneNode['te
function convertVectorAndStrokeProps(nc: NodeChange, blobs: Uint8Array[]) {
const vectorNetwork = resolveVectorNetwork(nc, blobs)
- const strokeCap = getVectorStrokeCap(nc, vectorNetwork)
+ const strokeCap = getVectorStrokeCap(nc)
const strokeJoin = getVectorStrokeJoin(nc, vectorNetwork)
const fillGeometry = alignGeometryWindingRules(
resolveGeometryPaths(nc.fillGeometry, blobs, resolveVectorStyleOverrideFills(nc)),
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index c8c25f754..f85d2e013 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -411,10 +411,10 @@ function serializeGeometry(node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Arra
let styleOverrides: StyleOverride[] = []
const vectorData: Record<string, unknown> = {}
if (node.vectorNetwork && node.type === 'VECTOR') {
- const { table, mirroringToId } = buildStyleOverrideTable(node.vectorNetwork)
+ const { table, styleToId } = buildStyleOverrideTable(node.vectorNetwork)
styleOverrides = table
const blobIdx = blobs.length
- blobs.push(encodeVectorNetworkBlob(node.vectorNetwork, mirroringToId))
+ blobs.push(encodeVectorNetworkBlob(node.vectorNetwork, styleToId))
vectorData.vectorNetworkBlob = blobIdx
vectorData.normalizedSize = { x: node.width, y: node.height }
}
diff --git a/packages/fig/src/node-change/vector-network.ts b/packages/fig/src/node-change/vector-network.ts
index 218ddeabf..d86f8bbea 100644
--- a/packages/fig/src/node-change/vector-network.ts
+++ b/packages/fig/src/node-change/vector-network.ts
@@ -11,6 +11,7 @@ import type {
export interface StyleOverride {
styleID: number
handleMirroring?: string
+ strokeCap?: string
fillPaints?: Paint[]
}
@@ -39,12 +40,14 @@ export function decodeVectorNetworkBlob(
offset += 4
const y = view.getFloat32(offset, true)
offset += 4
- vertices.push({
+ const style = styles.get(styleIndex)
+ const vertex: VectorVertex = {
x,
y,
- handleMirroring:
- (styles.get(styleIndex)?.handleMirroring as HandleMirroring | undefined) ?? 'NONE'
- })
+ handleMirroring: (style?.handleMirroring as HandleMirroring | undefined) ?? 'NONE'
+ }
+ if (style?.strokeCap) vertex.strokeCap = style.strokeCap
+ vertices.push(vertex)
}
const segments: VectorSegment[] = []
@@ -93,26 +96,35 @@ export function decodeVectorNetworkBlob(
return { vertices, segments, regions }
}
+function vertexStyleKey(vertex: VectorVertex): string {
+ return `${vertex.handleMirroring ?? 'NONE'}|${vertex.strokeCap ?? ''}`
+}
+
export function buildStyleOverrideTable(network: VectorNetwork): {
table: StyleOverride[]
- mirroringToId: Map<string, number>
+ styleToId: Map<string, number>
} {
- const mirroringToId = new Map<string, number>()
+ const styleToId = new Map<string, number>()
const table: StyleOverride[] = []
let nextId = 1
for (const vertex of network.vertices) {
const mirroring = vertex.handleMirroring ?? 'NONE'
- if (mirroring === 'NONE' || mirroringToId.has(mirroring)) continue
- mirroringToId.set(mirroring, nextId)
- table.push({ styleID: nextId, handleMirroring: mirroring })
+ if (mirroring === 'NONE' && !vertex.strokeCap) continue
+ const key = vertexStyleKey(vertex)
+ if (styleToId.has(key)) continue
+ styleToId.set(key, nextId)
+ const entry: StyleOverride = { styleID: nextId }
+ if (mirroring !== 'NONE') entry.handleMirroring = mirroring
+ if (vertex.strokeCap) entry.strokeCap = vertex.strokeCap
+ table.push(entry)
nextId++
}
- return { table, mirroringToId }
+ return { table, styleToId }
}
export function encodeVectorNetworkBlob(
network: VectorNetwork,
- mirroringToId?: Map<string, number>
+ styleToId?: Map<string, number>
): Uint8Array {
let regionBytes = 0
for (const region of network.regions) {
@@ -133,8 +145,7 @@ export function encodeVectorNetworkBlob(
offset += 4
for (const vertex of network.vertices) {
- const mirroring = vertex.handleMirroring ?? 'NONE'
- view.setUint32(offset, mirroring === 'NONE' ? 0 : (mirroringToId?.get(mirroring) ?? 0), true)
+ view.setUint32(offset, styleToId?.get(vertexStyleKey(vertex)) ?? 0, true)
offset += 4
view.setFloat32(offset, vertex.x, true)
offset += 4
diff --git a/packages/fig/tests/node-change.test.ts b/packages/fig/tests/node-change.test.ts
index a332c31c1..87a1b3358 100644
--- a/packages/fig/tests/node-change.test.ts
+++ b/packages/fig/tests/node-change.test.ts
@@ -214,8 +214,8 @@ describe('@open-pencil/fig NodeChange policy', () => {
],
regions: []
}
- const { table, mirroringToId } = buildStyleOverrideTable(network)
- expect(decodeVectorNetworkBlob(encodeVectorNetworkBlob(network, mirroringToId), table)).toEqual(
+ const { table, styleToId } = buildStyleOverrideTable(network)
+ expect(decodeVectorNetworkBlob(encodeVectorNetworkBlob(network, styleToId), table)).toEqual(
network
)
})
@@ -240,3 +240,28 @@ describe('@open-pencil/fig NodeChange policy', () => {
expect(fields.fillPaints).toEqual([{ type: 'SOLID', visible: true }])
})
})
+
+describe('one-ended arrow import', () => {
+ test('a per-vertex arrow cap does not become the node-wide cap', () => {
+ const network = {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0, strokeCap: 'ARROW_EQUILATERAL' }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ const { table, styleToId } = buildStyleOverrideTable(network)
+ const props = nodeChangeToProps(
+ {
+ type: 'VECTOR',
+ vectorData: { vectorNetworkBlob: 0, styleOverrideTable: table }
+ } as NodeChange,
+ [encodeVectorNetworkBlob(network, styleToId)]
+ )
+
+ expect(props.strokeCap).toBe('NONE')
+ expect(props.vectorNetwork?.vertices[1].strokeCap).toBe('ARROW_EQUILATERAL')
+ expect(props.vectorNetwork?.vertices[0].strokeCap).toBeUndefined()
+ })
+})
diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.json
index df0ff7416..913b70bc4 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -22,6 +22,12 @@
"import": "./dist/index.js",
"default": "./dist/index.js"
},
+ "./arrow-caps": {
+ "types": "./dist/arrow-caps.d.ts",
+ "bun": "./src/arrow-caps.ts",
+ "import": "./dist/arrow-caps.js",
+ "default": "./dist/arrow-caps.js"
+ },
"./copy": {
"types": "./dist/copy.d.ts",
"bun": "./src/copy.ts",
diff --git a/packages/scene-graph/src/arrow-caps.ts b/packages/scene-graph/src/arrow-caps.ts
new file mode 100644
index 000000000..ffdcb10ff
--- /dev/null
+++ b/packages/scene-graph/src/arrow-caps.ts
@@ -0,0 +1,146 @@
+import type { Vector } from './primitives'
+import type { Stroke, StrokeCap, VectorNetwork } from './types'
+
+export type ArrowCapKind = 'ARROW_LINES' | 'ARROW_EQUILATERAL'
+
+export interface ArrowEndpoint {
+ x: number
+ y: number
+ /** Direction the arrow points, in radians, away from the path. */
+ angle: number
+ cap: ArrowCapKind
+}
+
+export interface ArrowWing {
+ from: Vector
+ to: Vector
+}
+
+/** Arrow head side length relative to stroke weight, tuned to match Figma. */
+const ARROW_SIDE_PER_WEIGHT = 4
+const WING_SWEEP = Math.PI / 6
+
+export function isArrowCap(cap: string | undefined): cap is ArrowCapKind {
+ return cap === 'ARROW_LINES' || cap === 'ARROW_EQUILATERAL'
+}
+
+/**
+ * Worst-case reach of an arrow head past the path: a head's base corners sit
+ * one full head side from the tip, and line-arrow wings are stroked at the
+ * shaft weight on top of that. Used to widen visual bounds and render margins
+ * so heads are not cropped by caches, exports, or culling. Vertex-level caps
+ * in the network count even when no stroke or node cap is an arrow.
+ */
+export function arrowCapOverflow(
+ strokes?: Stroke[],
+ fallbackCap?: StrokeCap,
+ network?: VectorNetwork | null
+): number {
+ const networkHasArrow = network?.vertices.some((vertex) => isArrowCap(vertex.strokeCap)) ?? false
+ let overflow = 0
+ for (const stroke of strokes ?? []) {
+ if (!stroke.visible) continue
+ if (networkHasArrow || isArrowCap(stroke.cap ?? fallbackCap)) {
+ overflow = Math.max(overflow, (ARROW_SIDE_PER_WEIGHT + 0.5) * stroke.weight)
+ }
+ }
+ return overflow
+}
+
+/**
+ * Finds the open path ends that should carry an arrow head: vertices used by
+ * exactly one segment, with a per-vertex cap override falling back to the
+ * stroke cap. The returned angle points away from the path, following the
+ * terminal bezier tangent when the segment is curved.
+ */
+export function collectArrowEndpoints(
+ network: VectorNetwork,
+ fallbackCap: StrokeCap
+): ArrowEndpoint[] {
+ const degrees = Array.from({ length: network.vertices.length }, () => 0)
+ for (const segment of network.segments) {
+ degrees[segment.start]++
+ degrees[segment.end]++
+ }
+
+ const endpoints: ArrowEndpoint[] = []
+ for (const segment of network.segments) {
+ for (const side of ['start', 'end'] as const) {
+ const vertexIndex = segment[side]
+ if (degrees[vertexIndex] !== 1) continue
+ const vertex = network.vertices[vertexIndex]
+ const cap = (vertex.strokeCap as StrokeCap | undefined) ?? fallbackCap
+ if (!isArrowCap(cap)) continue
+
+ const tangent = side === 'start' ? segment.tangentStart : segment.tangentEnd
+ let controlX: number
+ let controlY: number
+ if (Math.abs(tangent.x) > 0.001 || Math.abs(tangent.y) > 0.001) {
+ controlX = vertex.x + tangent.x
+ controlY = vertex.y + tangent.y
+ } else {
+ const other = network.vertices[side === 'start' ? segment.end : segment.start]
+ controlX = other.x
+ controlY = other.y
+ }
+ const dx = vertex.x - controlX
+ const dy = vertex.y - controlY
+ if (dx === 0 && dy === 0) continue
+ endpoints.push({ x: vertex.x, y: vertex.y, angle: Math.atan2(dy, dx), cap })
+ }
+ }
+ return endpoints
+}
+
+/**
+ * Points of a filled equilateral arrow head: tip first, then the two base
+ * corners. The tip sits exactly on the endpoint and the head sweeps back
+ * along the path.
+ */
+export function equilateralArrowPoints(
+ x: number,
+ y: number,
+ angle: number,
+ weight: number
+): [Vector, Vector, Vector] {
+ const halfBase = (ARROW_SIDE_PER_WEIGHT / 2) * weight
+ const depth = halfBase * Math.sqrt(3)
+ const dirX = Math.cos(angle)
+ const dirY = Math.sin(angle)
+ const perpX = -dirY
+ const perpY = dirX
+ const baseX = x - depth * dirX
+ const baseY = y - depth * dirY
+ return [
+ { x, y },
+ { x: baseX - halfBase * perpX, y: baseY - halfBase * perpY },
+ { x: baseX + halfBase * perpX, y: baseY + halfBase * perpY }
+ ]
+}
+
+/** The two stroked wings of an open (lines-style) arrow head. */
+export function arrowLinesSegments(
+ x: number,
+ y: number,
+ angle: number,
+ weight: number
+): [ArrowWing, ArrowWing] {
+ const wingLength = ARROW_SIDE_PER_WEIGHT * weight
+ const tip = { x, y }
+ const makeWing = (wingAngle: number): ArrowWing => ({
+ from: tip,
+ to: { x: x + wingLength * Math.cos(wingAngle), y: y + wingLength * Math.sin(wingAngle) }
+ })
+ return [makeWing(angle + Math.PI - WING_SWEEP), makeWing(angle + Math.PI + WING_SWEEP)]
+}
+
+/** Arrow endpoints for a LINE node, whose local geometry runs (0,0) → (width,height). */
+export function lineArrowEndpoints(width: number, height: number, cap: StrokeCap): ArrowEndpoint[] {
+ if (!isArrowCap(cap)) return []
+ if (width === 0 && height === 0) return []
+ const angle = Math.atan2(height, width)
+ return [
+ { x: 0, y: 0, angle: Math.atan2(-height, -width), cap },
+ { x: width, y: height, angle, cap }
+ ]
+}
diff --git a/packages/scene-graph/src/geometry.ts b/packages/scene-graph/src/geometry.ts
index 093cf5733..d615a2157 100644
--- a/packages/scene-graph/src/geometry.ts
+++ b/packages/scene-graph/src/geometry.ts
@@ -1,4 +1,5 @@
-import type { Effect, Stroke } from './index'
+import { arrowCapOverflow } from './arrow-caps'
+import type { Effect, Stroke, StrokeCap, VectorNetwork } from './index'
import type { Rect, Vector } from './primitives'
export function degToRad(degrees: number): number {
@@ -137,7 +138,11 @@ export function polygonVertices(node: {
})
}
-export function strokeOverflow(strokes?: Stroke[]): number {
+export function strokeOverflow(
+ strokes?: Stroke[],
+ fallbackCap?: StrokeCap,
+ network?: VectorNetwork | null
+): number {
let overflow = 0
for (const stroke of strokes ?? []) {
if (!stroke.visible) continue
@@ -146,7 +151,7 @@ export function strokeOverflow(strokes?: Stroke[]): number {
else if (stroke.align === 'CENTER') extra = stroke.weight / 2
overflow = Math.max(overflow, extra)
}
- return overflow
+ return Math.max(overflow, arrowCapOverflow(strokes, fallbackCap, network))
}
export function effectOverflow(effects?: Effect[]) {
@@ -193,6 +198,8 @@ export function computeVisualBounds(
height: number
rotation?: number
strokes?: Stroke[]
+ strokeCap?: StrokeCap
+ vectorNetwork?: VectorNetwork | null
effects?: Effect[]
}>,
getAbsolutePosition: (id: string) => Vector
@@ -202,7 +209,7 @@ export function computeVisualBounds(
for (const n of nodes) {
const abs = getAbsolutePosition(n.id)
const bbox = rotatedBBox(abs.x, abs.y, n.width, n.height, n.rotation ?? 0)
- const stroke = strokeOverflow(n.strokes)
+ const stroke = strokeOverflow(n.strokes, n.strokeCap, n.vectorNetwork)
const effects = effectOverflow(n.effects)
includePoint(bounds, bbox.left - stroke - effects.left, bbox.top - stroke - effects.top)
includePoint(bounds, bbox.right + stroke + effects.right, bbox.bottom + stroke + effects.bottom)
diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.ts
index 3f61c0934..c44eb0196 100644
--- a/packages/scene-graph/tsdown.config.ts
+++ b/packages/scene-graph/tsdown.config.ts
@@ -3,6 +3,7 @@ import { defineConfig } from 'tsdown'
export default defineConfig({
entry: {
index: './src/index.ts',
+ 'arrow-caps': './src/arrow-caps.ts',
copy: './src/copy.ts',
'node-defaults': './src/node-defaults.ts',
'hit-test': './src/hit-test.ts',
diff --git a/packages/vue/src/controls/stroke/helpers.ts b/packages/vue/src/controls/stroke/helpers.ts
index f05b989c6..277d5e904 100644
--- a/packages/vue/src/controls/stroke/helpers.ts
+++ b/packages/vue/src/controls/stroke/helpers.ts
@@ -2,8 +2,10 @@ import { computed, type ComputedRef, type Ref } from 'vue'
import { BLACK } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
+import { cloneVectorNetwork } from '@open-pencil/scene-graph'
import type { SceneNode, Stroke, StrokeCap, StrokeJoin } from '@open-pencil/scene-graph'
+import { MIXED } from '#vue/controls/node-props/use'
import type { MixedValue } from '#vue/controls/node-props/use'
export type StrokeSides = 'ALL' | 'TOP' | 'BOTTOM' | 'LEFT' | 'RIGHT' | 'CUSTOM'
@@ -18,6 +20,18 @@ export const SIDE_OPTIONS: { value: StrokeSides; label: string }[] = [
]
export const BORDER_SIDES = ['top', 'right', 'bottom', 'left'] as const
+
+export const STROKE_CAP_VALUES: StrokeCap[] = [
+ 'NONE',
+ 'ROUND',
+ 'SQUARE',
+ 'ARROW_LINES',
+ 'ARROW_EQUILATERAL'
+]
+
+export function isStrokeCapValue(value: string): value is StrokeCap {
+ return (STROKE_CAP_VALUES as string[]).includes(value)
+}
export const DEFAULT_STROKE: Stroke = {
color: BLACK,
weight: 1,
@@ -43,7 +57,16 @@ export function createStrokeGeometryState({ nodes, merged }: StrokeGeometryState
advancedActive: computed(
() => nodes.value.length > 0 && nodes.value.every((node) => node.strokes.length > 0)
),
- cap: computed(() => merged('strokeCap')),
+ cap: computed(() => {
+ // A vertex cap differing from the node cap means the path shows more
+ // than one ending: report MIXED so any picker choice fires setCap.
+ const hasVertexOverride = nodes.value.some((node) =>
+ node.vectorNetwork?.vertices.some(
+ (vertex) => vertex.strokeCap && vertex.strokeCap !== node.strokeCap
+ )
+ )
+ return hasVertexOverride ? MIXED : merged('strokeCap')
+ }),
join: computed(() => merged('strokeJoin')),
miterLimit: computed(() => merged('strokeMiterLimit'))
}
@@ -64,11 +87,18 @@ export function createStrokeGeometryActions(
function setCap(value: StrokeCap) {
runForSelection('Change stroke cap', (node) => {
- editor.updateNodeWithUndo(
- node.id,
- { strokeCap: value, strokes: node.strokes.map((stroke) => ({ ...stroke, cap: value })) },
- 'Change stroke cap'
- )
+ const changes: Partial<SceneNode> = {
+ strokeCap: value,
+ strokes: node.strokes.map((stroke) => ({ ...stroke, cap: value }))
+ }
+ // The picker speaks for the whole path: stale per-vertex overrides would
+ // silently win over the chosen cap on imported one-ended arrows.
+ if (node.vectorNetwork?.vertices.some((vertex) => vertex.strokeCap)) {
+ const network = cloneVectorNetwork(node.vectorNetwork)
+ for (const vertex of network.vertices) delete vertex.strokeCap
+ changes.vectorNetwork = network
+ }
+ editor.updateNodeWithUndo(node.id, changes, 'Change stroke cap')
})
}
diff --git a/packages/vue/src/controls/stroke/use.ts b/packages/vue/src/controls/stroke/use.ts
index 7c2db5a71..1baa8b498 100644
--- a/packages/vue/src/controls/stroke/use.ts
+++ b/packages/vue/src/controls/stroke/use.ts
@@ -39,7 +39,9 @@ export function useStrokeControls() {
const capOptions = [
{ value: 'NONE' as const, label: panels.value.strokeCapButt },
{ value: 'ROUND' as const, label: panels.value.strokeCapRound },
- { value: 'SQUARE' as const, label: panels.value.strokeCapSquare }
+ { value: 'SQUARE' as const, label: panels.value.strokeCapSquare },
+ { value: 'ARROW_LINES' as const, label: panels.value.strokeCapArrowLines },
+ { value: 'ARROW_EQUILATERAL' as const, label: panels.value.strokeCapArrowEquilateral }
]
const joinOptions = [
{ value: 'MITER' as const, label: panels.value.strokeJoinMiter },
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index d8c583dfa..0ab266f39 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -173,6 +173,8 @@
"strokeCapButt": "Flaches Ende",
"strokeCapRound": "Rundes Ende",
"strokeCapSquare": "Quadratisches Ende",
+ "strokeCapArrowLines": "Linienpfeil",
+ "strokeCapArrowEquilateral": "Dreieckspfeil",
"strokeJoin": "Linienverbindung",
"strokeJoinMiter": "Gehrungsverbindung",
"strokeJoinBevel": "Abgeschrägte Verbindung",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 51b39d64a..b20ccbe98 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -190,6 +190,8 @@
"strokeCapButt": "Extremo plano",
"strokeCapRound": "Extremo redondo",
"strokeCapSquare": "Extremo cuadrado",
+ "strokeCapArrowLines": "Flecha de líneas",
+ "strokeCapArrowEquilateral": "Flecha triangular",
"strokeJoin": "Unión del trazo",
"strokeJoinMiter": "Unión en inglete",
"strokeJoinBevel": "Unión biselada",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 7e29548ab..1681a4c12 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -173,6 +173,8 @@
"strokeCapButt": "Extrémité plate",
"strokeCapRound": "Extrémité arrondie",
"strokeCapSquare": "Extrémité carrée",
+ "strokeCapArrowLines": "Flèche en lignes",
+ "strokeCapArrowEquilateral": "Flèche triangulaire",
"strokeJoin": "Jonction du trait",
"strokeJoinMiter": "Jonction en onglet",
"strokeJoinBevel": "Jonction biseautée",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index 5a77a9e04..adfcb0bca 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -173,6 +173,8 @@
"strokeCapButt": "Estremità piatta",
"strokeCapRound": "Estremità arrotondata",
"strokeCapSquare": "Estremità quadrata",
+ "strokeCapArrowLines": "Freccia a linee",
+ "strokeCapArrowEquilateral": "Freccia triangolare",
"strokeJoin": "Giunzione del tratto",
"strokeJoinMiter": "Giunzione a mitra",
"strokeJoinBevel": "Giunzione smussata",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index e968714b7..e92f4284b 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -190,6 +190,8 @@
"strokeCapButt": "フラット線端",
"strokeCapRound": "丸型線端",
"strokeCapSquare": "角型線端",
+ "strokeCapArrowLines": "ライン矢印",
+ "strokeCapArrowEquilateral": "三角矢印",
"strokeJoin": "線の結合",
"strokeJoinMiter": "マイター結合",
"strokeJoinBevel": "ベベル結合",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 64f56f16a..98463cec7 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -173,6 +173,8 @@
"strokeCapButt": "Płaskie zakończenie",
"strokeCapRound": "Okrągłe zakończenie",
"strokeCapSquare": "Kwadratowe zakończenie",
+ "strokeCapArrowLines": "Strzałka liniowa",
+ "strokeCapArrowEquilateral": "Strzałka trójkątna",
"strokeJoin": "Łączenie obrysu",
"strokeJoinMiter": "Łączenie ostre",
"strokeJoinBevel": "Łączenie ścięte",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 6d43ff533..3493ad250 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -173,6 +173,8 @@
"strokeCapButt": "Плоский конец",
"strokeCapRound": "Круглый конец",
"strokeCapSquare": "Квадратный конец",
+ "strokeCapArrowLines": "Линейная стрелка",
+ "strokeCapArrowEquilateral": "Треугольная стрелка",
"strokeJoin": "Соединение обводки",
"strokeJoinMiter": "Острое соединение",
"strokeJoinBevel": "Скошенное соединение",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 0becebfe0..77429c9ac 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -173,6 +173,8 @@
"strokeCapButt": "平直端点",
"strokeCapRound": "圆形端点",
"strokeCapSquare": "方形端点",
+ "strokeCapArrowLines": "线条箭头",
+ "strokeCapArrowEquilateral": "三角箭头",
"strokeJoin": "描边连接",
"strokeJoinMiter": "尖角连接",
"strokeJoinBevel": "斜角连接",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 89230a3e5..964ca3225 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -246,6 +246,8 @@ export const panelMessageDefaults = {
strokeCapButt: 'Butt cap',
strokeCapRound: 'Round cap',
strokeCapSquare: 'Square cap',
+ strokeCapArrowLines: 'Line arrow',
+ strokeCapArrowEquilateral: 'Triangle arrow',
strokeJoin: 'Stroke join',
strokeJoinMiter: 'Miter join',
strokeJoinBevel: 'Bevel join',
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index af7c340cf..328f2624f 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -103,6 +103,7 @@ export type {
export { useEffectsControls } from '#vue/controls/effects/use'
export { useSharedStyleBinding } from '#vue/controls/shared-style/use'
export { useStrokeControls } from '#vue/controls/stroke/use'
+export { isStrokeCapValue } from '#vue/controls/stroke/helpers'
export {
applySolidFillColor,
applySolidStrokeColor,
diff --git a/src/components/properties/StrokeSection.vue b/src/components/properties/StrokeSection.vue
index 7e6e43dc8..488949f6a 100644
--- a/src/components/properties/StrokeSection.vue
+++ b/src/components/properties/StrokeSection.vue
@@ -4,6 +4,7 @@ import { ref } from 'vue'
import {
applySolidStrokeColor,
BindableValueRoot,
+ isStrokeCapValue,
MIXED,
useColorBindingProvider,
useI18n,
@@ -67,7 +68,7 @@ function updateStrokeColor(
}
function setCap(value: string) {
- if (value === 'NONE' || value === 'ROUND' || value === 'SQUARE') {
+ if (isStrokeCapValue(value)) {
strokeCtx.setCap(value)
}
}
diff --git a/tests/e2e/canvas/arrow-caps-visual.spec.ts b/tests/e2e/canvas/arrow-caps-visual.spec.ts
new file mode 100644
index 000000000..81ddf5d45
--- /dev/null
+++ b/tests/e2e/canvas/arrow-caps-visual.spec.ts
@@ -0,0 +1,183 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+async function expectCanvas(name: string) {
+ editor.canvas.assertNoErrors()
+ const buffer = await editor.canvas.screenshotCanvasRegion()
+ // Heads are small relative to the canvas: the default percentage
+ // tolerance could absorb a lost head, so pin an absolute pixel budget
+ // below the footprint of the smallest head in the scene.
+ expect(buffer).toMatchSnapshot(`${name}.png`, { maxDiffPixels: 24 })
+}
+
+test('arrow stroke caps', async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+ const ink = { r: 0.08, g: 0.1, b: 0.18, a: 1 }
+ const solidStroke = (
+ weight: number,
+ dashPattern?: number[],
+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE' = 'CENTER'
+ ) => [{ color: ink, weight, visible: true, opacity: 1, align, dashPattern }]
+
+ store.graph.createNode('LINE', pageId, {
+ name: 'Equilateral line',
+ x: 60,
+ y: 60,
+ width: 220,
+ height: 0,
+ strokeCap: 'ARROW_EQUILATERAL',
+ strokes: solidStroke(2)
+ })
+ store.graph.createNode('LINE', pageId, {
+ name: 'Lines-cap line',
+ x: 60,
+ y: 110,
+ width: 220,
+ height: 0,
+ strokeCap: 'ARROW_LINES',
+ strokes: solidStroke(2)
+ })
+ store.graph.createNode('LINE', pageId, {
+ name: 'Heavy equilateral line',
+ x: 60,
+ y: 160,
+ width: 220,
+ height: 0,
+ strokeCap: 'ARROW_EQUILATERAL',
+ strokes: solidStroke(5)
+ })
+ store.graph.createNode('LINE', pageId, {
+ name: 'Dashed arrow line',
+ x: 60,
+ y: 216,
+ width: 220,
+ height: 0,
+ strokeCap: 'ARROW_EQUILATERAL',
+ strokes: solidStroke(2, [10, 6])
+ })
+ store.graph.createNode('LINE', pageId, {
+ name: 'Rotated arrow line',
+ x: 330,
+ y: 60,
+ width: 150,
+ height: 0,
+ rotation: 32,
+ strokeCap: 'ARROW_LINES',
+ strokes: solidStroke(3)
+ })
+
+ store.graph.createNode('VECTOR', pageId, {
+ name: 'Open polyline with node cap',
+ x: 330,
+ y: 170,
+ width: 150,
+ height: 70,
+ strokeCap: 'ARROW_EQUILATERAL',
+ strokes: solidStroke(2),
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 70 },
+ { x: 75, y: 0 },
+ { x: 150, y: 70 }
+ ],
+ 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: []
+ }
+ })
+ store.graph.createNode('VECTOR', pageId, {
+ name: 'Curved one-ended arrow',
+ x: 60,
+ y: 270,
+ width: 200,
+ height: 60,
+ strokes: solidStroke(2),
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 60 },
+ { x: 200, y: 60, strokeCap: 'ARROW_EQUILATERAL' }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: { x: 90, y: -70 }, tangentEnd: { x: -90, y: -70 } }
+ ],
+ regions: []
+ }
+ })
+ store.graph.createNode('VECTOR', pageId, {
+ name: 'Closed path keeps no heads',
+ x: 330,
+ y: 270,
+ width: 90,
+ height: 70,
+ strokeCap: 'ARROW_EQUILATERAL',
+ strokes: solidStroke(2),
+ vectorNetwork: {
+ vertices: [
+ { x: 45, y: 0 },
+ { x: 90, y: 70 },
+ { x: 0, y: 70 }
+ ],
+ 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: []
+ }
+ })
+ store.graph.createNode('VECTOR', pageId, {
+ name: 'Filled open vector keeps heads',
+ x: 60,
+ y: 380,
+ width: 200,
+ height: 60,
+ strokeCap: 'ARROW_EQUILATERAL',
+ strokes: solidStroke(2),
+ fills: [
+ { type: 'SOLID', color: { r: 0.55, g: 0.75, b: 0.95, a: 1 }, visible: true, opacity: 0.4 }
+ ],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 60 },
+ { x: 200, y: 60 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: { x: 90, y: -70 }, tangentEnd: { x: -90, y: -70 } }
+ ],
+ regions: []
+ }
+ })
+ store.graph.createNode('VECTOR', pageId, {
+ name: 'Outside-aligned stroke keeps heads',
+ x: 330,
+ y: 390,
+ width: 150,
+ height: 50,
+ strokeCap: 'ARROW_LINES',
+ strokes: solidStroke(2, undefined, 'OUTSIDE'),
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 50 },
+ { x: 75, y: 0 },
+ { x: 150, 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 } }
+ ],
+ regions: []
+ }
+ })
+
+ store.clearSelection()
+ store.requestRender()
+ })
+ await editor.canvas.waitForRender()
+ await expectCanvas('arrow-stroke-caps')
+})
diff --git a/tests/e2e/canvas/arrow-caps-visual.spec.ts-snapshots/arrow-stroke-caps-openpencil-darwin.png b/tests/e2e/canvas/arrow-caps-visual.spec.ts-snapshots/arrow-stroke-caps-openpencil-darwin.png
new file mode 100644
index 000000000..723c90ce7
Binary files /dev/null and b/tests/e2e/canvas/arrow-caps-visual.spec.ts-snapshots/arrow-stroke-caps-openpencil-darwin.png differ
diff --git a/tests/engine/geometry/arrow-caps.test.ts b/tests/engine/geometry/arrow-caps.test.ts
new file mode 100644
index 000000000..1399b7d72
--- /dev/null
+++ b/tests/engine/geometry/arrow-caps.test.ts
@@ -0,0 +1,289 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { Stroke, VectorNetwork } from '@open-pencil/scene-graph'
+import type { ArrowEndpoint } from '@open-pencil/scene-graph/arrow-caps'
+import {
+ arrowCapOverflow,
+ arrowLinesSegments,
+ collectArrowEndpoints,
+ equilateralArrowPoints,
+ isArrowCap,
+ lineArrowEndpoints
+} from '@open-pencil/scene-graph/arrow-caps'
+import { strokeOverflow } from '@open-pencil/scene-graph/geometry'
+
+const SQRT3 = Math.sqrt(3)
+
+function endpointAt(endpoints: ArrowEndpoint[], x: number): ArrowEndpoint {
+ const match = endpoints.find((endpoint) => endpoint.x === x)
+ if (!match) throw new Error(`no endpoint at x=${x}`)
+ return match
+}
+
+function straightOpenLine(): VectorNetwork {
+ return {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+}
+
+describe('isArrowCap', () => {
+ test('recognizes both arrow cap kinds and nothing else', () => {
+ expect(isArrowCap('ARROW_LINES')).toBe(true)
+ expect(isArrowCap('ARROW_EQUILATERAL')).toBe(true)
+ expect(isArrowCap('ROUND')).toBe(false)
+ expect(isArrowCap('SQUARE')).toBe(false)
+ expect(isArrowCap('NONE')).toBe(false)
+ expect(isArrowCap(undefined)).toBe(false)
+ })
+})
+
+describe('collectArrowEndpoints', () => {
+ test('returns both open ends of a straight segment pointing outward', () => {
+ const endpoints = collectArrowEndpoints(straightOpenLine(), 'ARROW_EQUILATERAL')
+
+ expect(endpoints).toHaveLength(2)
+ const start = endpointAt(endpoints, 0)
+ const end = endpointAt(endpoints, 100)
+ expect(start.y).toBe(0)
+ expect(Math.abs(start.angle)).toBeCloseTo(Math.PI, 5)
+ expect(start.cap).toBe('ARROW_EQUILATERAL')
+ expect(end.y).toBe(0)
+ expect(end.angle).toBeCloseTo(0, 5)
+ expect(end.cap).toBe('ARROW_EQUILATERAL')
+ })
+
+ test('returns nothing when the effective cap is not an arrow', () => {
+ expect(collectArrowEndpoints(straightOpenLine(), 'ROUND')).toHaveLength(0)
+ expect(collectArrowEndpoints(straightOpenLine(), 'NONE')).toHaveLength(0)
+ })
+
+ test('per-vertex caps override the fallback cap', () => {
+ const network = straightOpenLine()
+ network.vertices[0] = { x: 0, y: 0, strokeCap: 'ROUND' }
+ const endpoints = collectArrowEndpoints(network, 'ARROW_LINES')
+
+ expect(endpoints).toHaveLength(1)
+ expect(endpoints[0].x).toBe(100)
+ expect(endpoints[0].cap).toBe('ARROW_LINES')
+ })
+
+ test('a per-vertex arrow cap applies even when the fallback is NONE', () => {
+ const network = straightOpenLine()
+ network.vertices[1] = { x: 100, y: 0, strokeCap: 'ARROW_EQUILATERAL' }
+ const endpoints = collectArrowEndpoints(network, 'NONE')
+
+ expect(endpoints).toHaveLength(1)
+ expect(endpoints[0].x).toBe(100)
+ expect(endpoints[0].cap).toBe('ARROW_EQUILATERAL')
+ })
+
+ test('closed loops have no arrow endpoints', () => {
+ const closedTriangle: VectorNetwork = {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 50, y: 80 }
+ ],
+ 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: []
+ }
+
+ expect(collectArrowEndpoints(closedTriangle, 'ARROW_EQUILATERAL')).toHaveLength(0)
+ })
+
+ test('interior polyline vertices are not endpoints', () => {
+ const polyline: VectorNetwork = {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 50, y: 0 },
+ { x: 50, y: 40 }
+ ],
+ 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: []
+ }
+
+ const endpoints = collectArrowEndpoints(polyline, 'ARROW_LINES')
+ expect(endpoints).toHaveLength(2)
+ const coordinates = endpoints.map((endpoint) => [endpoint.x, endpoint.y]).sort()
+ expect(coordinates).toEqual([
+ [0, 0],
+ [50, 40]
+ ])
+ })
+
+ test('curved terminal segments take their angle from the bezier tangent', () => {
+ const curve: VectorNetwork = {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 20 }, tangentEnd: { x: 0, y: -20 } }],
+ regions: []
+ }
+
+ const endpoints = collectArrowEndpoints(curve, 'ARROW_EQUILATERAL')
+ const start = endpointAt(endpoints, 0)
+ const end = endpointAt(endpoints, 100)
+ expect(start.angle).toBeCloseTo(-Math.PI / 2, 5)
+ expect(end.angle).toBeCloseTo(Math.PI / 2, 5)
+ })
+})
+
+describe('equilateralArrowPoints', () => {
+ test('builds a weight-scaled equilateral head with the tip at the endpoint', () => {
+ const [tip, left, right] = equilateralArrowPoints(10, 5, 0, 1)
+
+ expect(tip.x).toBeCloseTo(10, 5)
+ expect(tip.y).toBeCloseTo(5, 5)
+ expect(left.x).toBeCloseTo(10 - 2 * SQRT3, 5)
+ expect(left.y).toBeCloseTo(5 - 2, 5)
+ expect(right.x).toBeCloseTo(10 - 2 * SQRT3, 5)
+ expect(right.y).toBeCloseTo(5 + 2, 5)
+ })
+
+ test('rotates with the endpoint angle', () => {
+ const [tip, left, right] = equilateralArrowPoints(0, 0, Math.PI / 2, 1)
+
+ expect(tip.x).toBeCloseTo(0, 5)
+ expect(tip.y).toBeCloseTo(0, 5)
+ expect(left.y).toBeCloseTo(-2 * SQRT3, 5)
+ expect(right.y).toBeCloseTo(-2 * SQRT3, 5)
+ expect([left.x, right.x].sort((a, b) => a - b)[0]).toBeCloseTo(-2, 5)
+ expect([left.x, right.x].sort((a, b) => a - b)[1]).toBeCloseTo(2, 5)
+ })
+
+ test('scales linearly with stroke weight', () => {
+ const [, left] = equilateralArrowPoints(0, 0, 0, 3)
+
+ expect(left.x).toBeCloseTo(-6 * SQRT3, 5)
+ expect(left.y).toBeCloseTo(-6, 5)
+ })
+})
+
+describe('arrowLinesSegments', () => {
+ test('builds two wings sweeping back from the tip', () => {
+ const [first, second] = arrowLinesSegments(10, 5, 0, 1)
+
+ expect(first.from.x).toBeCloseTo(10, 5)
+ expect(first.from.y).toBeCloseTo(5, 5)
+ expect(second.from.x).toBeCloseTo(10, 5)
+ expect(second.from.y).toBeCloseTo(5, 5)
+ const tips = [first.to, second.to].sort((a, b) => a.y - b.y)
+ expect(tips[0].x).toBeCloseTo(10 - 2 * SQRT3, 5)
+ expect(tips[0].y).toBeCloseTo(5 - 2, 5)
+ expect(tips[1].x).toBeCloseTo(10 - 2 * SQRT3, 5)
+ expect(tips[1].y).toBeCloseTo(5 + 2, 5)
+ })
+
+ test('scales linearly with stroke weight', () => {
+ const [first] = arrowLinesSegments(0, 0, 0, 2)
+ const length = Math.hypot(first.to.x - first.from.x, first.to.y - first.from.y)
+
+ expect(length).toBeCloseTo(8, 5)
+ })
+})
+
+describe('lineArrowEndpoints', () => {
+ test('a horizontal line gets outward endpoints at both ends', () => {
+ const endpoints = lineArrowEndpoints(100, 0, 'ARROW_EQUILATERAL')
+
+ expect(endpoints).toHaveLength(2)
+ const start = endpointAt(endpoints, 0)
+ const end = endpointAt(endpoints, 100)
+ expect(Math.abs(start.angle)).toBeCloseTo(Math.PI, 5)
+ expect(end.angle).toBeCloseTo(0, 5)
+ })
+
+ test('a diagonal line points its endpoints along the line direction', () => {
+ const endpoints = lineArrowEndpoints(30, 40, 'ARROW_LINES')
+ const end = endpointAt(endpoints, 30)
+
+ expect(end.y).toBe(40)
+ expect(end.angle).toBeCloseTo(Math.atan2(40, 30), 5)
+ })
+
+ test('returns nothing for non-arrow caps', () => {
+ expect(lineArrowEndpoints(100, 0, 'ROUND')).toHaveLength(0)
+ expect(lineArrowEndpoints(100, 0, 'NONE')).toHaveLength(0)
+ })
+})
+
+function stroke(overrides: Partial<Stroke> = {}): Stroke {
+ return {
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ weight: 4,
+ opacity: 1,
+ visible: true,
+ align: 'CENTER',
+ ...overrides
+ }
+}
+
+describe('arrowCapOverflow', () => {
+ test('an arrow cap reserves the full head reach plus wing stroke width', () => {
+ expect(arrowCapOverflow([stroke({ cap: 'ARROW_EQUILATERAL', weight: 3 })])).toBe(13.5)
+ expect(arrowCapOverflow([stroke({ cap: 'ARROW_LINES', weight: 2 })])).toBe(9)
+ })
+
+ test('the fallback cap applies when the stroke has none', () => {
+ expect(arrowCapOverflow([stroke({ weight: 2 })], 'ARROW_LINES')).toBe(9)
+ })
+
+ test('a vertex-only arrow cap still reserves overflow', () => {
+ const network: VectorNetwork = {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0, strokeCap: 'ARROW_EQUILATERAL' }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ expect(arrowCapOverflow([stroke({ weight: 2 })], 'NONE', network)).toBe(9)
+ expect(arrowCapOverflow([stroke({ weight: 2 })], 'NONE')).toBe(0)
+ })
+
+ test('an explicit non-arrow cap beats an arrow fallback', () => {
+ expect(arrowCapOverflow([stroke({ cap: 'ROUND' })], 'ARROW_EQUILATERAL')).toBe(0)
+ })
+
+ test('invisible and capless strokes contribute nothing', () => {
+ expect(arrowCapOverflow([stroke({ cap: 'ARROW_LINES', visible: false })])).toBe(0)
+ expect(arrowCapOverflow([stroke()])).toBe(0)
+ expect(arrowCapOverflow(undefined)).toBe(0)
+ })
+})
+
+describe('strokeOverflow with arrow caps', () => {
+ test('arrow heads widen the stroke overflow past the weight pad', () => {
+ expect(strokeOverflow([stroke({ cap: 'ARROW_EQUILATERAL' })])).toBe(18)
+ expect(strokeOverflow([stroke({ weight: 4 })], 'ARROW_LINES')).toBe(18)
+ })
+
+ test('a vertex-only arrow cap widens overflow through the network parameter', () => {
+ const network: VectorNetwork = {
+ vertices: [
+ { x: 0, y: 0, strokeCap: 'ARROW_LINES' },
+ { x: 100, y: 0 }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ expect(strokeOverflow([stroke({ weight: 4 })], 'NONE', network)).toBe(18)
+ })
+
+ test('non-arrow strokes keep the align-based overflow', () => {
+ expect(strokeOverflow([stroke()])).toBe(2)
+ })
+})
diff --git a/tests/engine/render/canvas/arrow-heads-draw.test.ts b/tests/engine/render/canvas/arrow-heads-draw.test.ts
new file mode 100644
index 000000000..a48719d94
--- /dev/null
+++ b/tests/engine/render/canvas/arrow-heads-draw.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, mock, test } from 'bun:test'
+
+import type { Canvas } from 'canvaskit-wasm'
+
+import type { SkiaRenderer } from '#core/canvas/renderer'
+import { drawArrowHeads } from '#core/canvas/strokes'
+
+const SQRT3 = Math.sqrt(3)
+
+function createHarness() {
+ const moveToCalls: Array<[number, number]> = []
+ const lineToCalls: Array<[number, number]> = []
+ const drawLineCalls: Array<[number, number, number, number]> = []
+ let pathsBuilt = 0
+ let closeCalls = 0
+ const detached = { delete: mock(() => undefined) }
+
+ class MockPathBuilder {
+ constructor() {
+ pathsBuilt++
+ }
+
+ moveTo(x: number, y: number) {
+ moveToCalls.push([x, y])
+ return this
+ }
+
+ lineTo(x: number, y: number) {
+ lineToCalls.push([x, y])
+ return this
+ }
+
+ close() {
+ closeCalls++
+ return this
+ }
+
+ detachAndDelete() {
+ return detached
+ }
+ }
+
+ const renderer = {
+ ck: {
+ PathBuilder: MockPathBuilder,
+ Color4f: mock((r: number, g: number, b: number, a: number) => ['color', r, g, b, a]),
+ StrokeCap: { Butt: 'butt-cap' }
+ },
+ fillPaint: {
+ setColor: mock(() => undefined),
+ setAlphaf: mock(() => undefined),
+ setShader: mock(() => undefined)
+ },
+ strokePaint: {
+ setColor: mock(() => undefined),
+ setStrokeWidth: mock(() => undefined),
+ setAlphaf: mock(() => undefined),
+ setStrokeCap: mock(() => undefined),
+ setPathEffect: mock(() => undefined),
+ setShader: mock(() => undefined)
+ }
+ } as SkiaRenderer
+
+ const drawPath = mock(() => undefined)
+ const canvas = {
+ drawPath,
+ drawLine: (x1: number, y1: number, x2: number, y2: number) => {
+ drawLineCalls.push([x1, y1, x2, y2])
+ }
+ } as Canvas
+
+ return {
+ renderer,
+ canvas,
+ detached,
+ drawPath,
+ counters: () => ({ pathsBuilt, closeCalls }),
+ moveToCalls,
+ lineToCalls,
+ drawLineCalls
+ }
+}
+
+const color = { r: 0.1, g: 0.2, b: 0.3, a: 1 }
+
+describe('drawArrowHeads', () => {
+ test('fills a closed triangle for an equilateral endpoint', () => {
+ const harness = createHarness()
+
+ drawArrowHeads(
+ harness.renderer,
+ harness.canvas,
+ [{ x: 10, y: 5, angle: 0, cap: 'ARROW_EQUILATERAL' }],
+ 2,
+ color,
+ 0.8
+ )
+
+ expect(harness.counters()).toEqual({ pathsBuilt: 1, closeCalls: 1 })
+ expect(harness.moveToCalls).toEqual([[10, 5]])
+ expect(harness.lineToCalls).toHaveLength(2)
+ const corners = [...harness.lineToCalls].sort((a, b) => a[1] - b[1])
+ expect(corners[0][0]).toBeCloseTo(10 - 4 * SQRT3, 5)
+ expect(corners[0][1]).toBeCloseTo(1, 5)
+ expect(corners[1][0]).toBeCloseTo(10 - 4 * SQRT3, 5)
+ expect(corners[1][1]).toBeCloseTo(9, 5)
+ expect(harness.renderer.fillPaint.setColor).toHaveBeenCalledWith(['color', 0.1, 0.2, 0.3, 1])
+ expect(harness.renderer.fillPaint.setAlphaf).toHaveBeenCalledWith(0.8)
+ expect(harness.drawPath).toHaveBeenCalledWith(harness.detached, harness.renderer.fillPaint)
+ expect(harness.detached.delete).toHaveBeenCalled()
+ expect(harness.drawLineCalls).toHaveLength(0)
+ })
+
+ test('strokes two wings for a lines endpoint without a dash effect', () => {
+ const harness = createHarness()
+
+ drawArrowHeads(
+ harness.renderer,
+ harness.canvas,
+ [{ x: 0, y: 0, angle: 0, cap: 'ARROW_LINES' }],
+ 1,
+ color,
+ 1
+ )
+
+ expect(harness.drawLineCalls).toHaveLength(2)
+ const wings = [...harness.drawLineCalls].sort((a, b) => a[3] - b[3])
+ expect(wings[0][0]).toBeCloseTo(0, 5)
+ expect(wings[0][1]).toBeCloseTo(0, 5)
+ expect(wings[0][2]).toBeCloseTo(-2 * SQRT3, 5)
+ expect(wings[0][3]).toBeCloseTo(-2, 5)
+ expect(wings[1][2]).toBeCloseTo(-2 * SQRT3, 5)
+ expect(wings[1][3]).toBeCloseTo(2, 5)
+ expect(harness.renderer.strokePaint.setStrokeWidth).toHaveBeenCalledWith(1)
+ expect(harness.renderer.strokePaint.setStrokeCap).toHaveBeenCalledWith('butt-cap')
+ expect(harness.renderer.strokePaint.setPathEffect).toHaveBeenCalledWith(null)
+ expect(harness.drawPath).not.toHaveBeenCalled()
+ })
+
+ test('draws nothing for an empty endpoint list', () => {
+ const harness = createHarness()
+
+ drawArrowHeads(harness.renderer, harness.canvas, [], 2, color, 1)
+
+ expect(harness.counters()).toEqual({ pathsBuilt: 0, closeCalls: 0 })
+ expect(harness.drawPath).not.toHaveBeenCalled()
+ expect(harness.drawLineCalls).toHaveLength(0)
+ })
+})
diff --git a/tests/engine/vector/blob/roundtrip.test.ts b/tests/engine/vector/blob/roundtrip.test.ts
index aefa3350c..aac948f63 100644
--- a/tests/engine/vector/blob/roundtrip.test.ts
+++ b/tests/engine/vector/blob/roundtrip.test.ts
@@ -1,6 +1,7 @@
import { describe, test, expect } from 'bun:test'
import {
+ buildStyleOverrideTable,
encodeVectorNetworkBlob,
decodeVectorNetworkBlob,
type VectorNetwork
@@ -105,3 +106,34 @@ describe('vectorNetworkBlob round-trip', () => {
expect(decoded.regions[1].loops).toEqual([[0, 2]])
})
})
+
+describe('vertex stroke caps in the style override table', () => {
+ test('a per-vertex arrow cap round-trips', () => {
+ const network = vectorNetwork(
+ [{ ...vectorVertex(0, 0), strokeCap: 'ARROW_EQUILATERAL' }, vectorVertex(100, 0)],
+ [vectorSegment(0, 1)]
+ )
+ const { table, styleToId } = buildStyleOverrideTable(network)
+ const blob = encodeVectorNetworkBlob(network, styleToId)
+ const decoded = decodeVectorNetworkBlob(blob, table)
+ expect(decoded.vertices[0].strokeCap).toBe('ARROW_EQUILATERAL')
+ expect(decoded.vertices[1].strokeCap).toBeUndefined()
+ })
+
+ test('stroke cap and handle mirroring survive together on one vertex', () => {
+ const network = vectorNetwork(
+ [
+ { ...vectorVertex(0, 0), strokeCap: 'ARROW_LINES', handleMirroring: 'ANGLE' },
+ { ...vectorVertex(50, 50), handleMirroring: 'ANGLE' }
+ ],
+ [vectorSegment(0, 1, { x: 10, y: 0 }, { x: -10, y: 0 })]
+ )
+ const { table, styleToId } = buildStyleOverrideTable(network)
+ const blob = encodeVectorNetworkBlob(network, styleToId)
+ const decoded = decodeVectorNetworkBlob(blob, table)
+ expect(decoded.vertices[0].strokeCap).toBe('ARROW_LINES')
+ expect(decoded.vertices[0].handleMirroring).toBe('ANGLE')
+ expect(decoded.vertices[1].strokeCap).toBeUndefined()
+ expect(decoded.vertices[1].handleMirroring).toBe('ANGLE')
+ })
+})
diff --git a/tests/engine/vue/controls/stroke.test.ts b/tests/engine/vue/controls/stroke.test.ts
index 973718427..bf2a5d03a 100644
--- a/tests/engine/vue/controls/stroke.test.ts
+++ b/tests/engine/vue/controls/stroke.test.ts
@@ -9,7 +9,8 @@ import { MIXED, type MixedValue } from '#vue/controls/node-props/use'
import {
DEFAULT_STROKE,
createStrokeGeometryActions,
- createStrokeGeometryState
+ createStrokeGeometryState,
+ isStrokeCapValue
} from '#vue/controls/stroke/helpers'
import { firstPageId, makeSceneGraph } from '#tests/helpers/scene'
@@ -101,3 +102,111 @@ describe('stroke geometry controls', () => {
expect(graph.getNode(second.id)?.strokeMiterLimit).toBe(8)
})
})
+
+describe('stroke cap values', () => {
+ test('isStrokeCapValue accepts every cap the picker offers and rejects junk', () => {
+ for (const value of ['NONE', 'ROUND', 'SQUARE', 'ARROW_LINES', 'ARROW_EQUILATERAL']) {
+ expect(isStrokeCapValue(value)).toBe(true)
+ }
+ expect(isStrokeCapValue('MITER')).toBe(false)
+ expect(isStrokeCapValue('')).toBe(false)
+ })
+})
+
+describe('setCap with per-vertex overrides', () => {
+ test('applying a node-wide cap clears per-vertex overrides', () => {
+ const graph = makeSceneGraph()
+ const pageId = firstPageId(graph)
+ const vector = graph.createNode('VECTOR', pageId, {
+ strokes: [{ ...DEFAULT_STROKE }],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0, strokeCap: 'ARROW_EQUILATERAL' }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ })
+ const editor = createEditor({ graph })
+ const nodes = computed(() => [graph.getNode(vector.id)].filter(Boolean))
+ const actions = createStrokeGeometryActions(editor, nodes)
+
+ actions.setCap('ROUND')
+ const updated = graph.getNode(vector.id)
+ expect(updated?.strokeCap).toBe('ROUND')
+ expect(updated?.vectorNetwork?.vertices.some((vertex) => vertex.strokeCap)).toBe(false)
+ })
+})
+
+describe('cap state with per-vertex overrides', () => {
+ test('differing vertex caps report MIXED so the picker always fires', () => {
+ const graph = makeSceneGraph()
+ const vector = graph.createNode('VECTOR', firstPageId(graph), {
+ strokes: [{ ...DEFAULT_STROKE }],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0, strokeCap: 'ARROW_EQUILATERAL' }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ })
+ const nodes = ref([vector])
+ const state = createStrokeGeometryState({
+ nodes: computed(() => nodes.value),
+ merged: (key) => merged(nodes.value)(key)
+ })
+
+ expect(state.cap.value).toBe(MIXED)
+ })
+
+ test('a vertex cap equal to the node cap is not MIXED', () => {
+ const graph = makeSceneGraph()
+ const vector = graph.createNode('VECTOR', firstPageId(graph), {
+ strokeCap: 'ARROW_EQUILATERAL',
+ strokes: [{ ...DEFAULT_STROKE }],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0, strokeCap: 'ARROW_EQUILATERAL' },
+ { x: 100, y: 0, strokeCap: 'ARROW_EQUILATERAL' }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ })
+ const nodes = ref([vector])
+ const state = createStrokeGeometryState({
+ nodes: computed(() => nodes.value),
+ merged: (key) => merged(nodes.value)(key)
+ })
+
+ expect(state.cap.value).toBe('ARROW_EQUILATERAL')
+ })
+
+ test('setCap resolves MIXED to a concrete cap and undo restores it', () => {
+ const graph = makeSceneGraph()
+ const vector = graph.createNode('VECTOR', firstPageId(graph), {
+ strokes: [{ ...DEFAULT_STROKE }],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0, strokeCap: 'ARROW_LINES' }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ })
+ const editor = createEditor({ graph })
+ const nodes = computed(() => [graph.getNode(vector.id)].filter(Boolean))
+ const capState = () =>
+ createStrokeGeometryState({ nodes, merged: (key) => merged(nodes.value)(key) }).cap.value
+
+ expect(capState()).toBe(MIXED)
+ createStrokeGeometryActions(editor, nodes).setCap('ROUND')
+ expect(capState()).toBe('ROUND')
+ editor.undo.undo()
+ expect(capState()).toBe(MIXED)
+ })
+})