Skip to content

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

feat: draw arrow heads at Figma's size and drag lines by their ends (#1248)

Danila Poyarkovccb101fc5d1f
diff --git a/changes/1248/changed.md b/changes/1248/changed.md
new file mode 100644
index 000000000..6bc825c86
--- /dev/null
+++ b/changes/1248/changed.md
@@ -0,0 +1 @@
+- Lines and arrows select by their two ends, as in Figma: dragging an end turns and stretches the line, Shift holds it to 45° steps, and Alt keeps its midpoint.
diff --git a/changes/1248/fixed.md b/changes/1248/fixed.md
new file mode 100644
index 000000000..0c429402c
--- /dev/null
+++ b/changes/1248/fixed.md
@@ -0,0 +1 @@
+- Line arrow and triangle arrow heads draw at Figma's size and shape.
diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.ts
index a1a796cd2..bc3c294e1 100644
--- a/packages/core/src/canvas/overlays/selection.ts
+++ b/packages/core/src/canvas/overlays/selection.ts
@@ -18,6 +18,7 @@ import {
import {
createSceneGeometry,
hasTransformHandles,
+ isLineLike,
viewportMatrix,
selectionPath,
rotationHandleLayout,
@@ -362,8 +363,8 @@ export function drawNodeSelection(
y1,
x2,
y2,
- // A generated frame such as a sticky note may stay upright.
- !layerRotates(node)
+ // A generated frame such as a sticky note may stay upright, and a line turns by its ends.
+ !layerRotates(node) || isLineLike(node)
? null
: rotationHandleLayout(node, createSceneGeometry(graph, preview), r.zoom, {
x: x1,
diff --git a/packages/core/src/canvas/strokes.ts b/packages/core/src/canvas/strokes.ts
index 1cc8d96a0..04af99c0c 100644
--- a/packages/core/src/canvas/strokes.ts
+++ b/packages/core/src/canvas/strokes.ts
@@ -1,7 +1,7 @@
import type { Canvas, EmbindEnumEntity, Paint } from 'canvaskit-wasm'
import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
-import type { ArrowEndpoint } from '@open-pencil/scene-graph/arrow-caps'
+import type { ArrowEndpoint, ArrowWing } from '@open-pencil/scene-graph/arrow-caps'
import {
arrowLinesSegments,
circleCapRadius,
@@ -131,11 +131,11 @@ export function drawArrowHeads(
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)
+ // One path, so the wings meet in a round join rather than overlapping at the tip.
+ r.strokePaint.setStrokeCap(r.ck.StrokeCap.Round)
+ r.strokePaint.setStrokeJoin(r.ck.StrokeJoin.Round)
r.strokePaint.setPathEffect(null)
- for (const wing of arrowLinesSegments(x, y, angle, weight)) {
- canvas.drawLine(wing.from.x, wing.from.y, wing.to.x, wing.to.y, r.strokePaint)
- }
+ strokeWings(r, canvas, arrowLinesSegments(x, y, angle, weight))
break
case 'CIRCLE_FILLED':
setHeadPaint(r, color, opacity)
@@ -154,6 +154,16 @@ export function drawArrowHeads(
}
}
+function strokeWings(r: SkiaRenderer, canvas: Canvas, [first, second]: [ArrowWing, ArrowWing]) {
+ const builder = new r.ck.PathBuilder()
+ builder.moveTo(first.to.x, first.to.y)
+ builder.lineTo(first.from.x, first.from.y)
+ builder.lineTo(second.to.x, second.to.y)
+ const path = builder.detachAndDelete()
+ canvas.drawPath(path, r.strokePaint)
+ path.delete()
+}
+
function setHeadPaint(r: SkiaRenderer, color: Color, opacity: number) {
r.fillPaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
r.fillPaint.setAlphaf(opacity)
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 2ddc5eeec..68ded0774 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -44,6 +44,7 @@ import { createGraphReadActions } from './graph-reads'
import { createGuideActions } from './guides'
import { createIconActions } from './icons'
import { createDesignIssueActions } from './issues'
+import { createLineEndActions } from './line-ends'
import { createNodeActions } from './nodes'
import { createPageActions } from './pages'
import { createPlayActions } from './play/actions'
@@ -306,6 +307,7 @@ export function createEditor(options?: EditorOptions) {
clipboard.deleteNodes
)
const connectorStyles = createConnectorStyleActions(ctx)
+ const lineEnds = createLineEndActions(ctx, nodes.beginNodePreview)
const shaders = createShaderActions(ctx, nodes)
const alignment = createAlignmentActions(ctx)
const preview = createPlayActions(ctx)
@@ -479,6 +481,7 @@ export function createEditor(options?: EditorOptions) {
setStatusWorkflow: statuses.setStatusWorkflow,
...connectorDrawing,
...connectorEndpoints,
+ ...lineEnds,
...connectorStyles,
...shaders,
...shaderFrames,
diff --git a/packages/core/src/editor/line-ends.ts b/packages/core/src/editor/line-ends.ts
new file mode 100644
index 000000000..78ae0976a
--- /dev/null
+++ b/packages/core/src/editor/line-ends.ts
@@ -0,0 +1,67 @@
+import { layerRotates, type SceneNode } from '@open-pencil/scene-graph'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+import type { NodePreview } from '#core/editor/node-preview'
+import type { EditorContext } from '#core/editor/types'
+import {
+ aimLine,
+ draggedLineEnds,
+ isLineLike,
+ lineWorldEnds,
+ type LineEnd
+} from '#core/geometry/line-ends'
+
+type BeginNodePreview = (label?: string) => NodePreview
+
+/**
+ * Drags an end of a line, as Figma does for lines and arrows: the end follows the pointer and the
+ * other stays, turning and stretching the line as one undo step. Shift holds it to 45° steps and
+ * Alt keeps its midpoint.
+ */
+export function createLineEndActions(ctx: EditorContext, beginNodePreview: BeginNodePreview) {
+ let drag: {
+ line: SceneNode
+ end: LineEnd
+ ends: [Vector, Vector]
+ press: Vector
+ preview: NodePreview
+ } | null = null
+
+ function lineEndBegin(nodeId: string, end: LineEnd, x: number, y: number) {
+ lineEndCancel()
+ const line = ctx.graph.getNode(nodeId)
+ if (!line || !isLineLike(line) || !layerRotates(line)) return
+ drag = {
+ line: { ...line },
+ end,
+ ends: lineWorldEnds(ctx.graph, line),
+ press: { x, y },
+ preview: beginNodePreview('Move line end')
+ }
+ }
+
+ function lineEndDrag(x: number, y: number, modifiers: { shift?: boolean; alt?: boolean } = {}) {
+ if (!drag) return
+ const delta = { x: x - drag.press.x, y: y - drag.press.y }
+ const [start, end] = draggedLineEnds(drag.ends, drag.end, delta, modifiers)
+ const changes = aimLine(ctx.graph, drag.line, start, end)
+ if (changes) drag.preview.update(drag.line.id, changes)
+ ctx.requestRender()
+ }
+
+ function lineEndCommit() {
+ const current = drag
+ drag = null
+ current?.preview.commit()
+ ctx.requestRender()
+ }
+
+ function lineEndCancel() {
+ const current = drag
+ drag = null
+ current?.preview.cancel()
+ ctx.requestRender()
+ }
+
+ return { lineEndBegin, lineEndDrag, lineEndCommit, lineEndCancel }
+}
diff --git a/packages/core/src/geometry/index.ts b/packages/core/src/geometry/index.ts
index 09f664fe1..a70e82113 100644
--- a/packages/core/src/geometry/index.ts
+++ b/packages/core/src/geometry/index.ts
@@ -38,6 +38,14 @@ export type {
GradientStopLayout
} from './gradient'
export { connectorScreenEnds } from './connectors'
+export {
+ aimLine,
+ draggedLineEnds,
+ isLineLike,
+ lineEndPoints,
+ lineWorldEnds,
+ type LineEnd
+} from './line-ends'
export { createSceneGeometry, nodeOrientationMatrix, projectedNode, viewportMatrix } from './scene'
export type { SceneGeometry } from './scene'
export { selectionPath, selectionHandleRect, rotationHandleLayout } from './selection'
diff --git a/packages/core/src/geometry/line-ends.ts b/packages/core/src/geometry/line-ends.ts
new file mode 100644
index 000000000..804d5310e
--- /dev/null
+++ b/packages/core/src/geometry/line-ends.ts
@@ -0,0 +1,115 @@
+import type { SceneGraph, SceneNode, Vector } from '@open-pencil/scene-graph'
+import {
+ getParentWorldMatrix,
+ getWorldMatrix,
+ localTransformFromWorld
+} from '@open-pencil/scene-graph/coordinate'
+import Matrix, { type Mat3 } from '@open-pencil/scene-graph/matrix'
+import { scaleVectorNetworkForResize } from '@open-pencil/scene-graph/resize'
+
+/** Which end of a line a handle drags: its origin or the far end along its length. */
+export type LineEnd = 'start' | 'end'
+
+/** Shift holds a dragged line to these steps, as Figma does. */
+const SNAP_STEP = Math.PI / 4
+
+/**
+ * Whether a layer is a line: one of its sides is zero, as a line's or a straight vector's is.
+ * Figma selects such a layer by its two ends rather than a box, and dragging an end aims it.
+ */
+export function isLineLike(node: Pick<SceneNode, 'width' | 'height'>): boolean {
+ return (node.width === 0) !== (node.height === 0)
+}
+
+/** A line's two ends in its own frame, start first. */
+export function lineEndPoints(node: Pick<SceneNode, 'width' | 'height'>): [Vector, Vector] {
+ return node.height === 0
+ ? [
+ { x: 0, y: 0 },
+ { x: node.width, y: 0 }
+ ]
+ : [
+ { x: 0, y: 0 },
+ { x: 0, y: node.height }
+ ]
+}
+
+/** A line's two ends in world space, start first. */
+export function lineWorldEnds(graph: SceneGraph, node: SceneNode): [Vector, Vector] {
+ const world = getWorldMatrix(node, graph)
+ const [start, end] = lineEndPoints(node)
+ return [Matrix.mapPoint(world, start), Matrix.mapPoint(world, end)]
+}
+
+/** `vector` along the nearest 45° direction, as far as it reaches along it. */
+function snapped(vector: Vector): Vector {
+ const angle = Math.round(Math.atan2(vector.y, vector.x) / SNAP_STEP) * SNAP_STEP
+ const direction = { x: Math.cos(angle), y: Math.sin(angle) }
+ const reach = vector.x * direction.x + vector.y * direction.y
+ return { x: direction.x * reach, y: direction.y * reach }
+}
+
+/**
+ * Where a line's ends land when one is dragged by `delta` in world space, as Figma moves them:
+ * the dragged end follows the pointer and the other stays; Shift holds the line to 45° steps
+ * and Alt keeps its midpoint, moving the other end opposite.
+ */
+export function draggedLineEnds(
+ ends: readonly [Vector, Vector],
+ end: LineEnd,
+ delta: Vector,
+ modifiers: { shift?: boolean; alt?: boolean } = {}
+): [Vector, Vector] {
+ const moving = end === 'end' ? 1 : 0
+ const fixed = ends[1 - moving]
+ const anchor = modifiers.alt
+ ? { x: (ends[0].x + ends[1].x) / 2, y: (ends[0].y + ends[1].y) / 2 }
+ : fixed
+ let reach = {
+ x: ends[moving].x + delta.x - anchor.x,
+ y: ends[moving].y + delta.y - anchor.y
+ }
+ if (modifiers.shift) reach = snapped(reach)
+ const dragged = { x: anchor.x + reach.x, y: anchor.y + reach.y }
+ const other = modifiers.alt ? { x: anchor.x - reach.x, y: anchor.y - reach.y } : fixed
+ return moving === 1 ? [other, dragged] : [dragged, other]
+}
+
+/**
+ * The changes that run `line` from `start` to `end`, given in world space: its length along its
+ * own axis, its turn, its position, and a vector's path stretched to the new length. A line
+ * keeps its zero side. Null when the ends meet.
+ */
+export function aimLine(
+ graph: SceneGraph,
+ line: SceneNode,
+ start: Vector,
+ end: Vector
+): Partial<SceneNode> | null {
+ const dx = end.x - start.x
+ const dy = end.y - start.y
+ const length = Math.hypot(dx, dy)
+ if (length < 1e-6) return null
+ const alongWidth = line.height === 0
+ // The world matrix whose local axis runs from start to end.
+ const angle = alongWidth ? Math.atan2(dy, dx) : Math.atan2(-dx, dy)
+ const cos = Math.cos(angle)
+ const sin = Math.sin(angle)
+ const world: Mat3 = [cos, -sin, start.x, sin, cos, start.y, 0, 0, 1]
+ const size = alongWidth ? { width: length, height: 0 } : { width: 0, height: length }
+ const parent = line.parentId ? graph.getNode(line.parentId) : undefined
+ const transform = localTransformFromWorld(
+ { ...line, ...size },
+ world,
+ getParentWorldMatrix(parent, graph)
+ )
+ if (!transform) return null
+ const vectorNetwork = scaleVectorNetworkForResize(
+ line.vectorNetwork,
+ line.width,
+ line.height,
+ size.width,
+ size.height
+ )
+ return { ...transform, ...size, ...(vectorNetwork && { vectorNetwork }) }
+}
diff --git a/packages/core/tests/geometry/line-ends.test.ts b/packages/core/tests/geometry/line-ends.test.ts
new file mode 100644
index 000000000..09a4376fd
--- /dev/null
+++ b/packages/core/tests/geometry/line-ends.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ aimLine,
+ draggedLineEnds,
+ isLineLike,
+ lineWorldEnds,
+ type LineEnd
+} from '@open-pencil/core/geometry'
+import { createEditor } from '@open-pencil/core/editor'
+import {
+ createConnector,
+ freeEndpoint,
+ SceneGraph,
+ type SceneNode,
+ type Vector
+} from '@open-pencil/scene-graph'
+
+/** An arrow as Figma's Arrow tool draws one: a flat vector along its width, aimed by rotation. */
+function arrow(graph: SceneGraph, start: Vector, end: Vector): SceneNode {
+ const page = graph.getPages()[0].id
+ const line = graph.createNode('VECTOR', page, {
+ width: 1,
+ height: 0,
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 1, y: 0, strokeCap: 'ARROW_LINES' }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ })
+ return aimAt(graph, line, start, end)
+}
+
+function aimAt(graph: SceneGraph, line: SceneNode, start: Vector, end: Vector): SceneNode {
+ const changes = aimLine(graph, line, start, end)
+ if (!changes) throw new Error('The ends meet')
+ graph.updateNode(line.id, changes)
+ const aimed = graph.getNode(line.id)
+ if (!aimed) throw new Error('The line is gone')
+ return aimed
+}
+
+/** Drags one end of `line` by `delta` and returns its ends after, rounded as Figma reports them. */
+function drag(
+ graph: SceneGraph,
+ line: SceneNode,
+ end: LineEnd,
+ delta: Vector,
+ modifiers: { shift?: boolean; alt?: boolean } = {}
+) {
+ const [start, finish] = draggedLineEnds(lineWorldEnds(graph, line), end, delta, modifiers)
+ const aimed = aimAt(graph, line, start, finish)
+ const round = ({ x, y }: Vector) => [Math.round(x * 100) / 100 + 0, Math.round(y * 100) / 100 + 0]
+ return {
+ ends: lineWorldEnds(graph, aimed).map(round),
+ length: Math.round(Math.max(aimed.width, aimed.height) * 100) / 100,
+ rotation: Math.round(aimed.rotation * 100) / 100,
+ aimed
+ }
+}
+
+// Measured in Figma by dragging an arrow's end handle on 2026-10-16. Figma turns y up, so its
+// rotations here have the opposite sign.
+describe('dragging a line by an end', () => {
+ test('the end follows the pointer and the other end stays', () => {
+ const graph = new SceneGraph()
+ const line = arrow(graph, { x: 0, y: 0 }, { x: 225.17, y: -130 })
+ const result = drag(graph, line, 'end', { x: 16.83, y: 160 })
+ expect(result.ends).toEqual([
+ [0, 0],
+ [242, 30]
+ ])
+ expect(result.length).toBe(243.85)
+ expect(result.rotation).toBe(7.07)
+ expect(result.aimed.height).toBe(0)
+ expect(result.aimed.vectorNetwork?.vertices.map((vertex) => vertex.x)).toEqual([0, result.aimed.width])
+ })
+
+ test('Shift holds it to 45° steps, as far as the pointer reaches along them', () => {
+ const cases: Array<[Vector, number[], number]> = [
+ [{ x: 122, y: -30 }, [382, 0], 382],
+ [{ x: 82, y: -150 }, [246, -246], 347.9],
+ [{ x: -18, y: 150 }, [196, 196], 277.19]
+ ]
+ for (const [delta, end, length] of cases) {
+ const graph = new SceneGraph()
+ const line = arrow(graph, { x: 0, y: 0 }, { x: 260, y: 0 })
+ const result = drag(graph, line, 'end', delta, { shift: true })
+ expect(result.ends).toEqual([[0, 0], end])
+ expect(result.length).toBe(length)
+ }
+ })
+
+ test('Alt keeps the midpoint and moves the other end opposite', () => {
+ const graph = new SceneGraph()
+ const line = arrow(graph, { x: 0, y: 0 }, { x: 302, y: 0 })
+ expect(drag(graph, line, 'end', { x: 40, y: -50 }, { alt: true }).ends).toEqual([
+ [-40, 50],
+ [342, -50]
+ ])
+ })
+
+ test('dragging the start moves the layer to it', () => {
+ const graph = new SceneGraph()
+ const line = arrow(graph, { x: 0, y: 0 }, { x: 200, y: 0 })
+ const result = drag(graph, line, 'start', { x: -30, y: 110 })
+ expect(result.ends).toEqual([
+ [-30, 110],
+ [200, 0]
+ ])
+ })
+
+ test('a vertical line keeps its axis and turns', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const line = graph.createNode('LINE', page, { width: 0, height: 160 })
+ const result = drag(graph, line, 'end', { x: 72, y: 40 })
+ expect(result.ends).toEqual([
+ [0, 0],
+ [72, 200]
+ ])
+ expect([result.aimed.width, result.length, result.rotation]).toEqual([0, 212.57, -19.8])
+ })
+
+ test('only a layer with one zero side is a line', () => {
+ expect(isLineLike({ width: 200, height: 0 })).toBe(true)
+ expect(isLineLike({ width: 0, height: 160 })).toBe(true)
+ expect(isLineLike({ width: 80, height: 60 })).toBe(false)
+ expect(isLineLike({ width: 0, height: 0 })).toBe(false)
+ })
+})
+
+test('the editor aims a line from a dragged end in one undo step', () => {
+ const editor = createEditor()
+ const line = editor.graph.createNode('LINE', editor.state.currentPageId, { width: 200, height: 0 })
+ editor.lineEndBegin(line.id, 'end', 200, 0)
+ editor.lineEndDrag(200, 100)
+ editor.lineEndDrag(200, 200, { shift: true })
+ editor.lineEndCommit()
+ const aimed = editor.graph.getNode(line.id)
+ expect(lineWorldEnds(editor.graph, aimed ?? line).map(({ x, y }) => [Math.round(x), Math.round(y)])).toEqual([
+ [0, 0],
+ [200, 200]
+ ])
+ editor.undoAction()
+ expect(editor.graph.getNode(line.id)).toMatchObject({ width: 200, height: 0, rotation: 0 })
+ editor.dispose()
+})
+
+test('a connector is never aimed as a line, though its box is flat', () => {
+ const editor = createEditor()
+ const page = editor.state.currentPageId
+ const connector = createConnector(editor.graph, page, {
+ start: freeEndpoint(0, 0),
+ end: freeEndpoint(200, 0)
+ })
+ editor.graph.updateNode(connector.id, { width: 200, height: 0 })
+ editor.lineEndBegin(connector.id, 'end', 200, 0)
+ editor.lineEndDrag(200, 100)
+ editor.lineEndCommit()
+ expect(editor.graph.getNode(connector.id)).toMatchObject({ width: 200, height: 0, rotation: 0 })
+ editor.dispose()
+})
+
diff --git a/packages/scene-graph/src/arrow-caps.ts b/packages/scene-graph/src/arrow-caps.ts
index 8269ade9d..d9a6dd582 100644
--- a/packages/scene-graph/src/arrow-caps.ts
+++ b/packages/scene-graph/src/arrow-caps.ts
@@ -21,17 +21,29 @@ export interface ArrowWing {
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
/**
- * Filled triangle, diamond, and circle heads relative to stroke weight, from the stroke outlines
- * Figma gives for them: the triangle runs 5 back from the end and spreads to 5/√3 on either side
- * at it, the diamond reaches 5/√3 from the end every way, and the circle has radius 8/3.
+ * Arrow heads relative to stroke weight, from the stroke outlines Figma gives for them. The
+ * triangle heads run 5 back from the end and spread to 5/√3 on either side: the equilateral
+ * arrow comes to its point at the end, and the filled triangle has its base across it. The
+ * diamond reaches 5/√3 from the end every way, and the circle has radius 8/3. A line arrow's
+ * wings meet at the end and run 4.5 back at 45°, stroked at the line's weight with round ends.
*/
-const FILLED_HEAD_DEPTH = 5
-const FILLED_HEAD_HALF_WIDTH = 5 / Math.sqrt(3)
+const TRIANGLE_HEAD_DEPTH = 5
+const TRIANGLE_HEAD_HALF_WIDTH = 5 / Math.sqrt(3)
const CIRCLE_HEAD_RADIUS = 8 / 3
+const WING_LENGTH = 4.5
+const WING_SWEEP = Math.PI / 4
+/** How far a line stops short of its end under a triangle head: half a weight inside its base. */
+const SHAFT_TRIM = TRIANGLE_HEAD_DEPTH - 0.5
+/**
+ * The furthest any head reaches past its line's box. On a line shorter than its head, a triangle
+ * reaches back from the end to its base corners, and a line arrow's wings their full length.
+ */
+const HEAD_REACH = Math.max(
+ WING_LENGTH + 0.5,
+ Math.hypot(TRIANGLE_HEAD_DEPTH, TRIANGLE_HEAD_HALF_WIDTH),
+ CIRCLE_HEAD_RADIUS
+)
const ARROW_CAPS: ReadonlySet<string> = new Set<ArrowCapKind>([
'ARROW_LINES',
@@ -46,11 +58,9 @@ export function isArrowCap(cap: string | undefined): cap is ArrowCapKind {
}
/**
- * 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.
+ * Worst-case reach of an arrow head past the path. 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[],
@@ -62,7 +72,7 @@ export function arrowCapOverflow(
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)
+ overflow = Math.max(overflow, HEAD_REACH * stroke.weight)
}
}
return overflow
@@ -128,9 +138,8 @@ export function collectArrowEndpoints(
}
/**
- * 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.
+ * 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,
@@ -138,29 +147,25 @@ export function equilateralArrowPoints(
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
+ const { dir, perp } = headAxes(angle)
+ const half = TRIANGLE_HEAD_HALF_WIDTH * weight
+ const baseX = x - TRIANGLE_HEAD_DEPTH * weight * dir.x
+ const baseY = y - TRIANGLE_HEAD_DEPTH * weight * dir.y
return [
{ x, y },
- { x: baseX - halfBase * perpX, y: baseY - halfBase * perpY },
- { x: baseX + halfBase * perpX, y: baseY + halfBase * perpY }
+ { x: baseX - half * perp.x, y: baseY - half * perp.y },
+ { x: baseX + half * perp.x, y: baseY + half * perp.y }
]
}
-/** The two stroked wings of an open (lines-style) arrow head. */
+/** The two wings of an open (lines-style) arrow head, each from the tip to its end. */
export function arrowLinesSegments(
x: number,
y: number,
angle: number,
weight: number
): [ArrowWing, ArrowWing] {
- const wingLength = ARROW_SIDE_PER_WEIGHT * weight
+ const wingLength = WING_LENGTH * weight
const tip = { x, y }
const makeWing = (wingAngle: number): ArrowWing => ({
from: tip,
@@ -186,14 +191,14 @@ export function triangleCapPoints(
): [Vector, Vector, Vector, Vector] {
const { dir, perp } = headAxes(angle)
const back = {
- x: x - FILLED_HEAD_DEPTH * weight * dir.x,
- y: y - FILLED_HEAD_DEPTH * weight * dir.y
+ x: x - TRIANGLE_HEAD_DEPTH * weight * dir.x,
+ y: y - TRIANGLE_HEAD_DEPTH * weight * dir.y
}
const at = (point: Vector, side: number) => ({
x: point.x + side * perp.x,
y: point.y + side * perp.y
})
- const half = FILLED_HEAD_HALF_WIDTH * weight
+ const half = TRIANGLE_HEAD_HALF_WIDTH * weight
return [at(back, weight / 2), at({ x, y }, half), at({ x, y }, -half), at(back, -weight / 2)]
}
@@ -205,7 +210,7 @@ export function diamondCapPoints(
weight: number
): [Vector, Vector, Vector, Vector] {
const { dir, perp } = headAxes(angle)
- const reach = FILLED_HEAD_HALF_WIDTH * weight
+ const reach = TRIANGLE_HEAD_HALF_WIDTH * weight
return [
{ x: x + reach * dir.x, y: y + reach * dir.y },
{ x: x + reach * perp.x, y: y + reach * perp.y },
@@ -219,15 +224,6 @@ export function circleCapRadius(weight: number): number {
return CIRCLE_HEAD_RADIUS * weight
}
-/**
- * How far a line stops short of its end under a triangle or equilateral head, in stroke weights:
- * half a weight inside the head's base, as Figma draws its triangle 5 weights deep.
- */
-function shaftTrim(cap: StrokeCap): number {
- if (cap === 'TRIANGLE_FILLED') return FILLED_HEAD_DEPTH - 0.5
- return (ARROW_SIDE_PER_WEIGHT / 2) * Math.sqrt(3) - 0.5
-}
-
function trimsShaft(cap: StrokeCap | undefined): boolean {
return cap === 'TRIANGLE_FILLED' || cap === 'ARROW_EQUILATERAL'
}
@@ -252,7 +248,7 @@ export function trimArrowShafts(
// By segment and side, not position: an open path's two ends may meet at one point.
for (const { segment, side, cap } of openArrowEnds(network, fallbackCap)) {
if (!trimsShaft(cap)) continue
- trimSegmentEnd(trimmed, trimmed.segments[segment], side === 'end', shaftTrim(cap) * weight)
+ trimSegmentEnd(trimmed, trimmed.segments[segment], side === 'end', SHAFT_TRIM * weight)
}
return trimmed
}
diff --git a/packages/scene-graph/src/resize.ts b/packages/scene-graph/src/resize.ts
index 92fb7ad7c..d81a97ee8 100644
--- a/packages/scene-graph/src/resize.ts
+++ b/packages/scene-graph/src/resize.ts
@@ -180,10 +180,11 @@ export function scaleVectorNetworkForResize(
width: number,
height: number
): VectorNetwork | null {
- if (!vectorNetwork || originalWidth <= 0 || originalHeight <= 0) return null
+ if (!vectorNetwork || (originalWidth <= 0 && originalHeight <= 0)) return null
- const scaleX = width / originalWidth
- const scaleY = height / originalHeight
+ // A flat side, as a straight line's, has nothing to scale along it.
+ const scaleX = originalWidth > 0 ? width / originalWidth : 1
+ const scaleY = originalHeight > 0 ? height / originalHeight : 1
if (scaleX === 1 && scaleY === 1) return null
return {
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index 9ea596cd4..40a4ffd7d 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -47,7 +47,8 @@ const ESCAPABLE_DRAGS: ReadonlySet<DragState['type']> = new Set<DragState['type'
'gradient',
'rotate',
'connector-draw',
- 'connector-end'
+ 'connector-end',
+ 'line-end'
])
export function useCanvasInput(
@@ -375,6 +376,11 @@ export function useCanvasInput(
return
}
+ if (d.type === 'line-end') {
+ editor.lineEndDrag(cx, cy, { shift: e.shiftKey, alt: e.altKey })
+ return
+ }
+
if (d.type === 'sticky-scale') {
applyStickyScale(d, cx, cy, editor)
return
@@ -431,16 +437,10 @@ export function useCanvasInput(
guideInput.clearHoverAndPreview()
}
- /** Drops what a resize or pencil stroke showed without changing the document. */
+ /** Drops what a drag showed without changing the document. */
function discardDrawnPreview(d: DragState) {
if (d.type === 'resize') cancelResizePreview(d, editor)
- else if (
- d.type === 'sticky-scale' ||
- d.type === 'sticky-draw' ||
- d.type === 'connector-draw' ||
- d.type === 'connector-end'
- )
- d.cancel()
+ else if ('cancel' in d) d.cancel()
else if (d.type === 'pencil-drag') editor.pencilCancel()
}
@@ -450,8 +450,7 @@ export function useCanvasInput(
if (d.type === 'move') cancelMove(d, editor)
else if (d.type === 'rotate') {
if (editor.state.rotationPreview?.nodeId === d.nodeId) editor.setRotationPreview(null)
- } else if (d.type === 'draw' || d.type === 'gradient' || d.type === 'shape-handle') d.cancel()
- else cancelNodeEditDrag(d, editor)
+ } else cancelNodeEditDrag(d, editor)
}
function cancelPointerInteraction() {
diff --git a/packages/vue/src/shared/assets/cursors/move.svg b/packages/vue/src/shared/assets/cursors/move.svg
new file mode 100644
index 000000000..81619e7d0
--- /dev/null
+++ b/packages/vue/src/shared/assets/cursors/move.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
+ <path d="M12 2 15.5 5.5 13 5.5 13 11 18.5 11 18.5 8.5 22 12 18.5 15.5 18.5 13 13 13 13 18.5 15.5 18.5 12 22 8.5 18.5 11 18.5 11 13 5.5 13 5.5 15.5 2 12 5.5 8.5 5.5 11 11 11 11 5.5 8.5 5.5Z" fill="black" stroke="white" stroke-width="0.8" stroke-linejoin="round"/>
+</svg>
diff --git a/packages/vue/src/shared/input/geometry.ts b/packages/vue/src/shared/input/geometry.ts
index b1817a731..580fd020a 100644
--- a/packages/vue/src/shared/input/geometry.ts
+++ b/packages/vue/src/shared/input/geometry.ts
@@ -2,6 +2,7 @@ import { HANDLE_HIT_RADIUS, LAYER_HIT_PAD } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
import {
createSceneGeometry,
+ isLineLike,
selectionHandleRect,
hasTransformHandles,
rotationHandleLayout,
@@ -15,9 +16,13 @@ import {
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { Vector } from '@open-pencil/scene-graph/primitives'
+import moveCursorSVG from '#vue/shared/assets/cursors/move.svg?raw'
import resizeCursorSVG from '#vue/shared/assets/cursors/resize.svg?raw'
import rotateCursorSVG from '#vue/shared/assets/cursors/rotate.svg?raw'
+/** Figma's four-way cursor over a handle that moves a point, such as a line's end. */
+export const MOVE_CURSOR = `url("data:image/svg+xml,${encodeURIComponent(moveCursorSVG)}") 12 12, auto`
+
export function getPointerCoords(e: MouseEvent, canvas: HTMLCanvasElement | null, editor: Editor) {
if (!canvas) return { sx: 0, sy: 0, cx: 0, cy: 0 }
const rect = canvas.getBoundingClientRect()
@@ -169,7 +174,9 @@ function transformZoneOf(
zoom: number
): TransformZone | null {
const pointer = geometry.toLocal(node, { x: cx, y: cy })
- return pointer ? transformZoneAt(pointer, selectionHandleRect(node), zoom) : null
+ const zone = pointer ? transformZoneAt(pointer, selectionHandleRect(node), zoom) : null
+ // A line is aimed by its two end handles, not resized: see `lineEndAt`.
+ return zone?.kind === 'resize' && isLineLike(node) ? null : zone
}
export function getHitHandleByMatrix(
@@ -198,7 +205,7 @@ export function hitTestTopRotationHandleByMatrix(
preview?: RotationPreview | null
): boolean {
const rect = selectionHandleRect(node)
- if (!hasTransformHandles(rect.width * zoom, rect.height * zoom)) return false
+ if (isLineLike(node) || !hasTransformHandles(rect.width * zoom, rect.height * zoom)) return false
const geometry = createSceneGeometry(graph, preview)
const handle = geometry.toWorld(node, rotationHandleLayout(node, geometry, zoom).handle)
const radius = HANDLE_HIT_RADIUS / zoom
diff --git a/packages/vue/src/shared/input/line/end.ts b/packages/vue/src/shared/input/line/end.ts
new file mode 100644
index 000000000..4bc7097d4
--- /dev/null
+++ b/packages/vue/src/shared/input/line/end.ts
@@ -0,0 +1,46 @@
+import type { Editor } from '@open-pencil/core/editor'
+import { isLineLike, lineWorldEnds, TRANSFORM_ZONE, type LineEnd } from '@open-pencil/core/geometry'
+import { layerRotates } from '@open-pencil/scene-graph'
+
+import type { DragState } from '#vue/shared/input/types'
+
+/**
+ * The end handle of the only selected line under a canvas point: an end within the reach Figma
+ * gives a corner handle, the nearer end winning on a short line.
+ */
+export function lineEndAt(
+ editor: Editor,
+ cx: number,
+ cy: number
+): { nodeId: string; end: LineEnd } | null {
+ const { state } = editor
+ if (state.selectedIds.size !== 1) return null
+ const [id] = state.selectedIds
+ const line = editor.graph.getNode(id)
+ // A connector or sticky note is shaped by its own handles, never aimed as a line.
+ if (!line || line.locked || !isLineLike(line) || !layerRotates(line)) return null
+ const reach = TRANSFORM_ZONE.resizeReach / (editor.renderer?.zoom ?? state.zoom)
+ const [start, end] = lineWorldEnds(editor.graph, line)
+ const toStart = Math.hypot(start.x - cx, start.y - cy)
+ const toEnd = Math.hypot(end.x - cx, end.y - cy)
+ if (Math.min(toStart, toEnd) > reach) return null
+ return { nodeId: id, end: toEnd <= toStart ? 'end' : 'start' }
+}
+
+/** Drags a selected line's end handle, aiming the line at the pointer. */
+export function tryStartLineEndDrag(
+ editor: Editor,
+ cx: number,
+ cy: number,
+ setDrag: (drag: DragState) => void
+): boolean {
+ const hit = lineEndAt(editor, cx, cy)
+ if (!hit) return false
+ editor.lineEndBegin(hit.nodeId, hit.end, cx, cy)
+ setDrag({
+ type: 'line-end',
+ commit: () => editor.lineEndCommit(),
+ cancel: () => editor.lineEndCancel()
+ })
+ return true
+}
diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.ts
index 509ec1acc..e8c3ec5bb 100644
--- a/packages/vue/src/shared/input/select.ts
+++ b/packages/vue/src/shared/input/select.ts
@@ -7,6 +7,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'
import { tryStartConnectorEndDrag } from '#vue/shared/input/connector/end'
import { tryStartGradientDrag } from '#vue/shared/input/gradient'
+import { tryStartLineEndDrag } from '#vue/shared/input/line/end'
import { tryStartResize } from '#vue/shared/input/resize'
import {
createSelectionMoveDrag,
@@ -55,6 +56,7 @@ function tryStartHandleDrag(
if (editedGradient(editor.graph, editor.state.gradientEdit)) return false
if (tryStartShapeHandleDrag(editor, sx, sy, altKey, setDrag)) return true
if (tryStartConnectorEndDrag(editor, sx, sy, setDrag)) return true
+ if (tryStartLineEndDrag(editor, cx, cy, setDrag)) return true
const scaleDrag = tryStartStickyScale(cx, cy, editor)
if (scaleDrag) {
setDrag(scaleDrag)
diff --git a/packages/vue/src/shared/input/select/hover.ts b/packages/vue/src/shared/input/select/hover.ts
index 250d83455..7c4eb6e29 100644
--- a/packages/vue/src/shared/input/select/hover.ts
+++ b/packages/vue/src/shared/input/select/hover.ts
@@ -2,11 +2,13 @@ import type { Editor } from '@open-pencil/core/editor'
import { layerResizes, layerRotates } from '@open-pencil/scene-graph'
import {
+ MOVE_CURSOR,
buildResizeCursor,
cornerRotationCursor,
getHitHandleByMatrix,
hitTestCornerRotationByMatrix
} from '#vue/shared/input/geometry'
+import { lineEndAt } from '#vue/shared/input/line/end'
import type { HitTestFns } from '#vue/shared/input/select'
import { hitTestLabel } from '#vue/shared/input/select/hit'
import { scalesByHandles } from '#vue/shared/input/sticky/scale'
@@ -85,10 +87,12 @@ export function updateHoverCursor(
return null
}
- // As a press does: resizing first, then a label, then rotation; a read-only document has none.
+ // As a press does: a line's ends, then resizing, then a label, then rotation; a read-only
+ // document has none.
const cursor = editor.state.readOnly
? null
- : (getResizeCursorForSelection(cx, cy, editor) ??
+ : ((lineEndAt(editor, cx, cy) ? MOVE_CURSOR : null) ??
+ getResizeCursorForSelection(cx, cy, editor) ??
(hitTestLabel(cx, cy, fns) ? null : getRotationCursorForSelection(cx, cy, editor)))
updateHoveredNode(cx, cy, editor, fns, deep)
return cursor
diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.ts
index 570aaf417..0ba9d2534 100644
--- a/packages/vue/src/shared/input/types.ts
+++ b/packages/vue/src/shared/input/types.ts
@@ -55,6 +55,13 @@ export interface DragConnectorEnd {
cancel: () => void
}
+/** An end of a selected line or arrow dragged to aim it. */
+export interface DragLineEnd {
+ type: 'line-end'
+ commit: () => void
+ cancel: () => void
+}
+
/** A sticky note being drawn: it grows from the press corner with the drag, as a frame does. */
export interface DragStickyDraw {
type: 'sticky-draw'
@@ -279,6 +286,7 @@ export type DragState =
| DragStickyDraw
| DragConnectorDraw
| DragConnectorEnd
+ | DragLineEnd
| DragGradient
| DragMove
| DragPan
diff --git a/packages/vue/tests/shared/input/select/hover.test.ts b/packages/vue/tests/shared/input/select/hover.test.ts
index 9aed5af67..b1c05c168 100644
--- a/packages/vue/tests/shared/input/select/hover.test.ts
+++ b/packages/vue/tests/shared/input/select/hover.test.ts
@@ -4,6 +4,7 @@ import { createEditor, type Editor } from '@open-pencil/core/editor'
import { boundEndpoint, createConnector, createSticky, type SceneNode } from '@open-pencil/scene-graph'
import {
+ MOVE_CURSOR,
cornerRotationCursor,
getHitHandleByMatrix,
buildResizeCursor
@@ -80,3 +81,12 @@ test("a sticky note's handles keep their cursor, since they scale it", () => {
)
})
+test("a line's ends show the move cursor, and its length takes no resize", () => {
+ editor = createEditor()
+ const line = editor.graph.createNode('LINE', editor.state.currentPageId, { width: 200, height: 0 })
+ editor.select([line.id])
+ expect(updateHoverCursor(200, 0, editor, NO_HITS)).toBe(MOVE_CURSOR)
+ expect(updateHoverCursor(0, 2, editor, NO_HITS)).toBe(MOVE_CURSOR)
+ expect(updateHoverCursor(100, 3, editor, NO_HITS)).toBeNull()
+})
+
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
index ac0e58add..7f529199c 100644
Binary files a/tests/e2e/canvas/arrow-caps-visual.spec.ts-snapshots/arrow-stroke-caps-openpencil-darwin.png and b/tests/e2e/canvas/arrow-caps-visual.spec.ts-snapshots/arrow-stroke-caps-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-caps-and-handles-openpencil-darwin.png b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-caps-and-handles-openpencil-darwin.png
index 1cf98b3d9..63f77876a 100644
Binary files a/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-caps-and-handles-openpencil-darwin.png and b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-caps-and-handles-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/figjam-connectors-moved-openpencil-darwin.png b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/figjam-connectors-moved-openpencil-darwin.png
index f079307e7..67743af98 100644
Binary files a/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/figjam-connectors-moved-openpencil-darwin.png and b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/figjam-connectors-moved-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/figjam-connectors-openpencil-darwin.png b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/figjam-connectors-openpencil-darwin.png
index b07ba103d..69f582dbc 100644
Binary files a/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/figjam-connectors-openpencil-darwin.png and b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/figjam-connectors-openpencil-darwin.png differ
diff --git a/tests/engine/geometry/arrow-caps.test.ts b/tests/engine/geometry/arrow-caps.test.ts
index 411ceec68..b70171908 100644
--- a/tests/engine/geometry/arrow-caps.test.ts
+++ b/tests/engine/geometry/arrow-caps.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import type { Stroke, VectorNetwork } from '@open-pencil/scene-graph'
+import { SceneGraph, type Stroke, type VectorNetwork } from '@open-pencil/scene-graph'
import type { ArrowEndpoint } from '@open-pencil/scene-graph/arrow-caps'
import {
arrowCapOverflow,
@@ -149,57 +149,54 @@ describe('collectArrowEndpoints', () => {
})
})
+// Figma's stroke outlines for a line from (0, 0) to (200, 0), measured on 2026-10-16.
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('comes to its point at the end and spreads 5/√3 weights either side, 5 back', () => {
+ const [tip, left, right] = equilateralArrowPoints(200, 0, 0, 4)
+
+ expect(tip).toEqual({ x: 200, y: 0 })
+ expect(left.x).toBeCloseTo(180, 5)
+ expect(left.y).toBeCloseTo(-11.547, 3)
+ expect(right.x).toBeCloseTo(180, 5)
+ expect(right.y).toBeCloseTo(11.547, 3)
})
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)
+ expect(tip).toEqual({ x: 0, y: 0 })
+ expect(left.y).toBeCloseTo(-5, 5)
+ expect(right.y).toBeCloseTo(-5, 5)
+ expect([left.x, right.x].sort((p, q) => p - q)[0]).toBeCloseTo(-5 / SQRT3, 5)
+ expect([left.x, right.x].sort((p, q) => p - q)[1]).toBeCloseTo(5 / SQRT3, 5)
})
test('scales linearly with stroke weight', () => {
- const [, left] = equilateralArrowPoints(0, 0, 0, 3)
+ const [, left] = equilateralArrowPoints(200, 0, 0, 10)
- expect(left.x).toBeCloseTo(-6 * SQRT3, 5)
- expect(left.y).toBeCloseTo(-6, 5)
+ expect(left.x).toBeCloseTo(150, 5)
+ expect(left.y).toBeCloseTo(-28.8675, 3)
})
})
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('meets at the end and runs 4.5 weights back at 45°', () => {
+ const [first, second] = arrowLinesSegments(200, 0, 0, 1)
+
+ expect(first.from).toEqual({ x: 200, y: 0 })
+ expect(second.from).toEqual({ x: 200, y: 0 })
+ const ends = [first.to, second.to].sort((p, q) => p.y - q.y)
+ expect(ends[0].x).toBeCloseTo(196.818, 3)
+ expect(ends[0].y).toBeCloseTo(-3.182, 3)
+ expect(ends[1].x).toBeCloseTo(196.818, 3)
+ expect(ends[1].y).toBeCloseTo(3.182, 3)
})
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)
+ const [first] = arrowLinesSegments(200, 0, 0, 4)
- expect(length).toBeCloseTo(8, 5)
+ expect(first.to.x).toBeCloseTo(187.272, 3)
+ expect(Math.abs(first.to.y)).toBeCloseTo(12.728, 3)
})
})
@@ -241,13 +238,40 @@ function stroke(overrides: Partial<Stroke> = {}): Stroke {
}
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)
+ // A triangle head on a line shorter than it reaches furthest: from the end to its base corners.
+ const REACH = Math.hypot(5, 5 / Math.sqrt(3))
+
+ test('a short line reserves room for a triangle head longer than itself', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const line = graph.createNode('VECTOR', page, {
+ width: 1,
+ height: 0,
+ strokes: [stroke({ weight: 4 })],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 1, y: 0, strokeCap: 'ARROW_EQUILATERAL' }
+ ],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ }
+ })
+ const [, base] = equilateralArrowPoints(1, 0, 0, 4)
+ // The head's base corner, 19 back from the line's start, stays inside the reserved room.
+ expect(-base.x).toBeLessThanOrEqual(arrowCapOverflow(line.strokes, 'NONE', line.vectorNetwork))
+ })
+
+ test('an arrow cap reserves the furthest any head reaches', () => {
+ expect(arrowCapOverflow([stroke({ cap: 'ARROW_EQUILATERAL', weight: 3 })])).toBeCloseTo(
+ 3 * REACH,
+ 5
+ )
+ expect(arrowCapOverflow([stroke({ cap: 'ARROW_LINES', weight: 2 })])).toBeCloseTo(2 * REACH, 5)
})
test('the fallback cap applies when the stroke has none', () => {
- expect(arrowCapOverflow([stroke({ weight: 2 })], 'ARROW_LINES')).toBe(9)
+ expect(arrowCapOverflow([stroke({ weight: 2 })], 'ARROW_LINES')).toBeCloseTo(2 * REACH, 5)
})
test('a vertex-only arrow cap still reserves overflow', () => {
@@ -259,7 +283,7 @@ describe('arrowCapOverflow', () => {
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', network)).toBeCloseTo(2 * REACH, 5)
expect(arrowCapOverflow([stroke({ weight: 2 })], 'NONE')).toBe(0)
})
@@ -275,9 +299,11 @@ describe('arrowCapOverflow', () => {
})
describe('strokeOverflow with arrow caps', () => {
+ const REACH = 4 * Math.hypot(5, 5 / Math.sqrt(3))
+
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)
+ expect(strokeOverflow([stroke({ cap: 'ARROW_EQUILATERAL' })])).toBeCloseTo(REACH, 5)
+ expect(strokeOverflow([stroke({ weight: 4 })], 'ARROW_LINES')).toBeCloseTo(REACH, 5)
})
test('a vertex-only arrow cap widens overflow through the network parameter', () => {
@@ -289,7 +315,7 @@ describe('strokeOverflow with arrow caps', () => {
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)
+ expect(strokeOverflow([stroke({ weight: 4 })], 'NONE', network)).toBeCloseTo(REACH, 5)
})
test('non-arrow strokes keep the align-based overflow', () => {
@@ -370,4 +396,10 @@ describe('filled heads', () => {
expect(trimmed.vertices[1].y).toBeCloseTo(0, 6)
expect(network.vertices[1].x).toBe(100)
})
+
+ test('the line stops 4.5 weights short of an equilateral head, as of a triangle', () => {
+ const network = straightOpenLine()
+ network.vertices[1].strokeCap = 'ARROW_EQUILATERAL'
+ expect(trimArrowShafts(network, 'NONE', 4).vertices[1].x).toBeCloseTo(82, 6)
+ })
})
diff --git a/tests/engine/geometry/visual-bounds.test.ts b/tests/engine/geometry/visual-bounds.test.ts
index 7a9d660f4..116723a7f 100644
--- a/tests/engine/geometry/visual-bounds.test.ts
+++ b/tests/engine/geometry/visual-bounds.test.ts
@@ -449,7 +449,8 @@ describe('computeVisualBounds', () => {
(id) => nodes[id as keyof typeof nodes],
() => ({ x: 0, y: 0 })
)
- expect(bounds?.minY).toBe(-18)
+ // A triangle head reaches furthest on a short line: from the end to its base corners.
+ expect(bounds?.minY).toBeCloseTo(-4 * Math.hypot(5, 5 / Math.sqrt(3)), 5)
})
test('nested clipping stops descendants outside the ancestor clip', () => {
diff --git a/tests/engine/render/canvas/arrow-heads-draw.test.ts b/tests/engine/render/canvas/arrow-heads-draw.test.ts
index 311ca0cda..d53eeed12 100644
--- a/tests/engine/render/canvas/arrow-heads-draw.test.ts
+++ b/tests/engine/render/canvas/arrow-heads-draw.test.ts
@@ -43,7 +43,8 @@ function createHarness() {
ck: {
PathBuilder: MockPathBuilder,
Color4f: mock((r: number, g: number, b: number, a: number) => ['color', r, g, b, a]),
- StrokeCap: { Butt: 'butt-cap' }
+ StrokeCap: { Butt: 'butt-cap', Round: 'round-cap' },
+ StrokeJoin: { Round: 'round-join' }
},
fillPaint: {
setColor: mock(() => undefined),
@@ -55,6 +56,7 @@ function createHarness() {
setStrokeWidth: mock(() => undefined),
setAlphaf: mock(() => undefined),
setStrokeCap: mock(() => undefined),
+ setStrokeJoin: mock(() => undefined),
setPathEffect: mock(() => undefined),
setShader: mock(() => undefined)
}
@@ -99,10 +101,10 @@ describe('drawArrowHeads', () => {
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(corners[0][0]).toBeCloseTo(0, 5)
+ expect(corners[0][1]).toBeCloseTo(5 - 10 / SQRT3, 5)
+ expect(corners[1][0]).toBeCloseTo(0, 5)
+ expect(corners[1][1]).toBeCloseTo(5 + 10 / SQRT3, 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)
@@ -110,7 +112,7 @@ describe('drawArrowHeads', () => {
expect(harness.drawLineCalls).toHaveLength(0)
})
- test('strokes two wings for a lines endpoint without a dash effect', () => {
+ test('strokes both wings as one round-joined path without a dash effect', () => {
const harness = createHarness()
drawArrowHeads(
@@ -122,18 +124,19 @@ describe('drawArrowHeads', () => {
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)
+ const end = 4.5 * Math.SQRT1_2
+ expect(harness.counters()).toEqual({ pathsBuilt: 1, closeCalls: 0 })
+ expect(harness.moveToCalls[0][0]).toBeCloseTo(-end, 5)
+ expect(Math.abs(harness.moveToCalls[0][1])).toBeCloseTo(end, 5)
+ expect(harness.lineToCalls[0]).toEqual([0, 0])
+ expect(harness.lineToCalls[1][0]).toBeCloseTo(-end, 5)
+ expect(harness.lineToCalls[1][1]).toBeCloseTo(-harness.moveToCalls[0][1], 5)
expect(harness.renderer.strokePaint.setStrokeWidth).toHaveBeenCalledWith(1)
- expect(harness.renderer.strokePaint.setStrokeCap).toHaveBeenCalledWith('butt-cap')
+ expect(harness.renderer.strokePaint.setStrokeCap).toHaveBeenCalledWith('round-cap')
+ expect(harness.renderer.strokePaint.setStrokeJoin).toHaveBeenCalledWith('round-join')
expect(harness.renderer.strokePaint.setPathEffect).toHaveBeenCalledWith(null)
- expect(harness.drawPath).not.toHaveBeenCalled()
+ expect(harness.drawPath).toHaveBeenCalledWith(harness.detached, harness.renderer.strokePaint)
+ expect(harness.drawLineCalls).toHaveLength(0)
})
test('draws nothing for an empty endpoint list', () => {