AI-native design editor. Open-source Figma alternative.
fix(canvas): stroke a line to one side, as Figma does (#1374)
Danila Poyarkov228dcfd7b5cf
diff --git a/changes/1374/breaking.md b/changes/1374/breaking.mdnew file mode 100644index 000000000..49be5029b--- /dev/null+++ b/changes/1374/breaking.md@@ -0,0 +1 @@+- `lineArrowEndpoints` is removed from `@open-pencil/scene-graph/arrow-caps`; `lineStrokeEnds` gives the path a line's stroke runs along. `StrokeCorners` from `@open-pencil/scene-graph/geometry` is renamed `StrokeShape` and takes the layer's `type`.diff --git a/changes/1374/fixed.md b/changes/1374/fixed.mdnew file mode 100644index 000000000..6e37d69d0--- /dev/null+++ b/changes/1374/fixed.md@@ -0,0 +1 @@+- A line draws its stroke above it as Figma does, instead of centred on it, keeps round and square caps and arrow heads within its length, spaces its dashes as Figma does, and draws with inside and outside alignment instead of disappearing.diff --git a/packages/core/src/canvas/boolean.ts b/packages/core/src/canvas/boolean.tsindex 817f331e9..016bdfac5 100644--- a/packages/core/src/canvas/boolean.ts+++ b/packages/core/src/canvas/boolean.ts@@ -7,6 +7,7 @@ import { getTextOutlineSupport } from '#core/text/outlines'import { makeArcPath } from './fills'import type { SkiaRenderer } from './renderer'import { nodeHasRadius } from './shapes'+import { makeLineStrokeOutline } from './strokes/line'import { textNodeToOutlinePath } from './text/outlines'const BOOLEAN_PATH_OP: Record<@@ -62,20 +63,9 @@ export function canMakeBooleanSourceNode(node: SceneNode, graph: SceneGraph): bo})}-function lineStrokePath(r: SkiaRenderer, node: SceneNode): Path | null {- const path = new r.ck.PathBuilder()- path.moveTo(0, 0)- path.lineTo(node.width, node.height)- const stroke = node.strokes.find((item) => item.visible)- const source = path.detachAndDelete()- const outline = source.makeStroked({ width: stroke?.weight ?? 1 })- source.delete()- return outline-}-function baseShapePath(r: SkiaRenderer, node: SceneNode): Path | null {if (node.type === 'TEXT') return textNodeToOutlinePath(r, node)- if (node.type === 'LINE') return lineStrokePath(r, node)+ if (node.type === 'LINE') return makeLineStrokeOutline(r, node)if (node.type === 'ELLIPSE' && node.arcData) return makeArcPath(r, node)const rect = r.ck.LTRBRect(0, 0, node.width, node.height)diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex 46e670ba8..2156327bd 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -2,12 +2,10 @@import type { Canvas, Path } from 'canvaskit-wasm'import { type SceneNode, type SceneGraph, type Fill } from '@open-pencil/scene-graph'-import type { ArrowEndpoint } from '@open-pencil/scene-graph/arrow-caps'import {arrowCapOverflow,collectArrowEndpoints,hasTrimmedShaft,- lineArrowEndpoints,trimArrowShafts} from '@open-pencil/scene-graph/arrow-caps'import Matrix from '@open-pencil/scene-graph/matrix'@@ -50,6 +48,7 @@ import {getStrokeJoinEntity,normalizeDashPattern} from './strokes'+import { drawLineStroke } from './strokes/line'import { drawOutlinedDashes } from './strokes/outlined-dashes'import { drawDashedRectStroke, strokeDashesByOutline, strokeSideWeights } from './strokes/sides'import { textVerticalOffset, withTextParagraph } from './text'@@ -833,9 +832,9 @@ 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.+ * Draws arrow-cap heads for a stroke on a vector's 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,@@ -844,13 +843,8 @@ function drawNodeArrowHeads(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 (node.type !== 'VECTOR' || !node.vectorNetwork) return+ const endpoints = collectArrowEndpoints(node.vectorNetwork, stroke.cap ?? node.strokeCap)if (endpoints.length > 0) {drawArrowHeads(r, canvas, endpoints, stroke.weight, color, stroke.opacity)}@@ -868,6 +862,10 @@ function paintNodeStrokes(vectorStroke: Path[] | null): void {forVisibleStrokes(r, node, graph, (stroke, color) => {+ if (node.type === 'LINE') {+ drawLineStroke(r, canvas, node, stroke, color)+ return+ }if (stroke.dashPattern &&stroke.dashPattern.length > 0 &&diff --git a/packages/core/src/canvas/shadows/silhouette.ts b/packages/core/src/canvas/shadows/silhouette.tsindex 9c42f9873..c9ebf9904 100644--- a/packages/core/src/canvas/shadows/silhouette.ts+++ b/packages/core/src/canvas/shadows/silhouette.ts@@ -1,6 +1,7 @@import type { Canvas } from 'canvaskit-wasm'import type { Fill, NodeType, SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'+import { strokeOverflow as strokeReach } from '@open-pencil/scene-graph/geometry'import Matrix from '@open-pencil/scene-graph/matrix'import type { Rect } from '@open-pencil/scene-graph/primitives'@@ -174,7 +175,13 @@ export function strokeOutset(stroke: Stroke): number {function strokeOverflow(node: SceneNode): number {let overflow = 0for (const stroke of node.strokes) {- if (paintCastsShadow(stroke)) overflow = Math.max(overflow, strokeOutset(stroke))+ if (!paintCastsShadow(stroke)) continue+ // A line's stroke lies wholly to one side of it, whatever its alignment, with its heads.+ const reach =+ node.type === 'LINE'+ ? strokeReach([stroke], node.strokeCap, null, node)+ : strokeOutset(stroke)+ overflow = Math.max(overflow, reach)}return overflow}diff --git a/packages/core/src/canvas/strokes.ts b/packages/core/src/canvas/strokes.tsindex 4d3473a17..9c430fcba 100644--- a/packages/core/src/canvas/strokes.ts+++ b/packages/core/src/canvas/strokes.ts@@ -1,4 +1,4 @@-import type { Canvas, EmbindEnumEntity, Paint } from 'canvaskit-wasm'+import type { Canvas, EmbindEnumEntity, Paint, Path } from 'canvaskit-wasm'import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'import type { ArrowEndpoint, ArrowWing } from '@open-pencil/scene-graph/arrow-caps'@@ -112,6 +112,56 @@ export function drawDashedRRectWithSolidCorners(r.strokePaint.setPathEffect(null)}+/** The outline a polygonal head fills: a triangle, an equilateral arrow, or a diamond. */+function polygonPath(r: SkiaRenderer, points: readonly Vector[]): Path {+ const builder = new r.ck.PathBuilder()+ points.forEach((point, index) =>+ index === 0 ? builder.moveTo(point.x, point.y) : builder.lineTo(point.x, point.y)+ )+ builder.close()+ return builder.detachAndDelete()+}++/** The corners of each head drawn as a polygon, from its tip, direction, and weight. */+const POLYGON_HEADS = {+ ARROW_EQUILATERAL: equilateralArrowPoints,+ TRIANGLE_FILLED: triangleCapPoints,+ DIAMOND_FILLED: diamondCapPoints+} satisfies Record<string, (x: number, y: number, angle: number, weight: number) => Vector[]>++/**+ * The filled outline of the head at `endpoint`. A line arrow's wings are one stroked path, so they+ * meet in a round join rather than overlapping at the tip.+ */+export function arrowHeadPath(+ r: SkiaRenderer,+ endpoint: ArrowEndpoint,+ weight: number+): Path | null {+ const { x, y, angle, cap } = endpoint+ if (cap === 'ARROW_LINES') {+ const [first, second] = arrowLinesSegments(x, y, angle, weight)+ 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 wings = builder.detachAndDelete()+ const outline = wings.makeStroked({+ width: weight,+ cap: r.ck.StrokeCap.Round,+ join: r.ck.StrokeJoin.Round+ })+ wings.delete()+ return outline+ }+ if (cap === 'CIRCLE_FILLED') {+ const builder = new r.ck.PathBuilder()+ builder.addCircle(x, y, circleCapRadius(weight))+ return builder.detachAndDelete()+ }+ return polygonPath(r, POLYGON_HEADS[cap](x, y, angle, weight))+}+/*** 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.@@ -177,12 +227,7 @@ function fillHead(color: Color,opacity: number) {- const builder = new r.ck.PathBuilder()- points.forEach((point, index) =>- index === 0 ? builder.moveTo(point.x, point.y) : builder.lineTo(point.x, point.y)- )- builder.close()- const path = builder.detachAndDelete()+ const path = polygonPath(r, points)setHeadPaint(r, color, opacity)canvas.drawPath(path, r.fillPaint)path.delete()diff --git a/packages/core/src/canvas/strokes/line.ts b/packages/core/src/canvas/strokes/line.tsnew file mode 100644index 000000000..397a77528--- /dev/null+++ b/packages/core/src/canvas/strokes/line.ts@@ -0,0 +1,100 @@+import type { Canvas, Path } from 'canvaskit-wasm'++import type { SceneNode, Stroke, StrokeCap, VectorNetwork } from '@open-pencil/scene-graph'+import {+ collectArrowEndpoints,+ hasTrimmedShaft,+ lineStrokeEnds,+ trimArrowShafts+} from '@open-pencil/scene-graph/arrow-caps'+import type { Color } from '@open-pencil/scene-graph/primitives'++import type { SkiaRenderer } from '#core/canvas/renderer'+import {+ arrowHeadPath,+ configureStrokePaint,+ drawArrowHeads,+ getStrokeCapEntity,+ normalizeDashPattern+} from '#core/canvas/strokes'++import { sideDashSpans } from './sides'++/**+ * The path Figma strokes for a LINE, as a one-segment network its arrow heads follow, and the ends+ * of its shaft, which stops short of a triangle or equilateral head.+ */+function lineStrokePath(node: SceneNode, weight: number, cap: StrokeCap) {+ const { start, end } = lineStrokeEnds(node.width, node.height, weight, cap)+ const still = { x: 0, y: 0 }+ const network: VectorNetwork = {+ vertices: [start, end],+ segments: [{ start: 0, end: 1, tangentStart: still, tangentEnd: still }],+ regions: []+ }+ const [from, to] = (+ hasTrimmedShaft(network, cap) ? trimArrowShafts(network, cap, weight) : network+ ).vertices+ return { network, from, to }+}++/**+ * Strokes a LINE as Figma does: to one side of the line whatever the alignment, with its caps and+ * heads inside its length, and its dashes stretched to whole periods like a rectangle's side.+ */+export function drawLineStroke(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ stroke: Stroke,+ color: Color+): void {+ const cap = stroke.cap ?? node.strokeCap+ const { network, from, to } = lineStrokePath(node, stroke.weight, cap)+ const length = Math.hypot(to.x - from.x, to.y - from.y)+ const pattern = normalizeDashPattern(stroke.dashPattern)+ const spans = pattern.length > 0 ? sideDashSpans(length, pattern) : [[0, length]]++ configureStrokePaint(r, node, stroke, color)+ r.strokePaint.setPathEffect(null)+ const at = (distance: number) => (length > 0 ? distance / length : 0)+ for (const [start, end] of spans) {+ canvas.drawLine(+ from.x + (to.x - from.x) * at(start),+ from.y + (to.y - from.y) * at(start),+ from.x + (to.x - from.x) * at(end),+ from.y + (to.y - from.y) * at(end),+ r.strokePaint+ )+ }+ const heads = collectArrowEndpoints(network, cap)+ drawArrowHeads(r, canvas, heads, stroke.weight, color, stroke.opacity)+}++/**+ * The outline of a LINE's first visible stroke, as booleans and flattening take it: its shaft, its+ * caps, and its heads, without dashes.+ */+export function makeLineStrokeOutline(r: SkiaRenderer, node: SceneNode): Path | null {+ const stroke = node.strokes.find((item) => item.visible)+ const weight = stroke?.weight ?? 1+ const cap = stroke?.cap ?? node.strokeCap+ const { network, from, to } = lineStrokePath(node, weight, cap)+ const shaft = new r.ck.PathBuilder()+ shaft.moveTo(from.x, from.y)+ shaft.lineTo(to.x, to.y)+ const source = shaft.detachAndDelete()+ const outline = source.makeStroked({ width: weight, cap: getStrokeCapEntity(r, cap) })+ source.delete()+ if (!outline) return null+ const builder = new r.ck.PathBuilder()+ builder.addPath(outline)+ outline.delete()+ for (const endpoint of collectArrowEndpoints(network, cap)) {+ const head = arrowHeadPath(r, endpoint, weight)+ if (!head) continue+ builder.addPath(head)+ head.delete()+ }+ return builder.detachAndDelete()+}diff --git a/packages/core/src/canvas/strokes/sides.ts b/packages/core/src/canvas/strokes/sides.tsindex 31f203315..a41ef7155 100644--- a/packages/core/src/canvas/strokes/sides.ts+++ b/packages/core/src/canvas/strokes/sides.ts@@ -133,17 +133,29 @@ export function drawIndividualSideStrokes(}/**- * Where one side's dashes fall along its length: Figma 126 stretches the pattern so the side- * holds a whole number of periods, rounded to the nearest, with half a dash at each end.+ * A dash pattern stretched to `length` as Figma 126 lays dashes along a side or a line: the length+ * holds a whole number of periods, rounded to the nearest, with half a dash at each end. `offset`+ * is how far before the start the stretched pattern begins.*/-export function sideDashSpans(length: number, pattern: readonly number[]): Array<[number, number]> {+export function fittedDashPattern(+ length: number,+ pattern: readonly number[]+): { intervals: number[]; offset: number } | null {const period = pattern.reduce((sum, size) => sum + size, 0)- if (period <= 0 || length <= 0) return [[0, Math.max(0, length)]]+ if (period <= 0 || length <= 0) return nullconst scale = length / (Math.max(1, Math.round(length / period)) * period)+ return { intervals: pattern.map((size) => size * scale), offset: (pattern[0] * scale) / 2 }+}++/** Where one side's dashes fall along its length, laid out by `fittedDashPattern`. */+export function sideDashSpans(length: number, pattern: readonly number[]): Array<[number, number]> {+ const fitted = fittedDashPattern(length, pattern)+ if (!fitted) return [[0, Math.max(0, length)]]+ const { intervals } = fittedconst spans: Array<[number, number]> = []- let position = (-pattern[0] * scale) / 2+ let position = -fitted.offsetfor (let index = 0; position < length; index++) {- const size = pattern[index % pattern.length] * scale+ const size = intervals[index % intervals.length]const start = Math.max(0, position)const end = Math.min(length, position + size)if (index % 2 === 0 && end > start) spans.push([start, end])diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.tsindex 7a8a72ac9..698def3b2 100644--- a/packages/core/src/io/formats/svg/export.ts+++ b/packages/core/src/io/formats/svg/export.ts@@ -1,6 +1,9 @@+import { lineStrokeEnds } from '@open-pencil/scene-graph/arrow-caps'import type { RenderColorSpace } from '@open-pencil/scene-graph/color'import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'+import { normalizeDashPattern } from '#core/canvas/strokes'+import { fittedDashPattern } from '#core/canvas/strokes/sides'import { computeContentBounds } from '#core/io/formats/raster'import {@@ -109,6 +112,16 @@ function vectorShapeElements(: [svg('rect', { width: round(node.width), height: round(node.height), ...common })]}+/** A line's dashes stretched along it as the canvas lays them, half a dash at each end. */+function lineDashAttrs(stroke: Stroke | undefined, length: number) {+ const fitted = fittedDashPattern(length, normalizeDashPattern(stroke?.dashPattern))+ if (!fitted) return {}+ return {+ 'stroke-dasharray': fitted.intervals.map((size) => round(size)).join(' '),+ 'stroke-dashoffset': round(fitted.offset)+ }+}+function nodeShapeElements(node: SceneNode,fillAttr: string | null,@@ -136,17 +149,27 @@ function nodeShapeElements(]}- case 'LINE':+ case 'LINE': {+ // Where the canvas strokes it: to one side of the line, with its caps inside its length.+ const stroke = node.strokes.find((item) => item.visible)+ const { start, end } = lineStrokeEnds(+ node.width,+ node.height,+ stroke?.weight ?? 0,+ stroke?.cap ?? node.strokeCap+ )return [svg('line', {- x1: 0,- y1: 0,- x2: round(node.width),- y2: round(node.height),+ x1: round(start.x),+ y1: round(start.y),+ x2: round(end.x),+ y2: round(end.y),fill: 'none',- ...strokeAttrs+ ...strokeAttrs,+ ...lineDashAttrs(stroke, Math.hypot(end.x - start.x, end.y - start.y))})]+ }case 'STAR':case 'POLYGON':@@ -321,18 +344,18 @@ function buildGroupAttrs(function buildSVGStrokeAttrs(visibleStrokes: Stroke[],- colorSpace: 'srgb' | 'display-p3'+ colorSpace: 'srgb' | 'display-p3',+ nodeCap: SceneNode['strokeCap']): Record<string, string | number | undefined> {if (visibleStrokes.length === 0) return {}const stroke = visibleStrokes[0]+ const cap = stroke.cap ?? nodeCapconst attrs: Record<string, string | number | undefined> = {stroke: formatColor(stroke.color, 1, colorSpace),'stroke-width': round(stroke.weight)}if (stroke.opacity < 1) attrs['stroke-opacity'] = round(stroke.opacity)- if (stroke.cap && stroke.cap !== 'NONE') {- attrs['stroke-linecap'] = SVG_STROKE_CAP[stroke.cap] ?? 'butt'- }+ if (cap !== 'NONE') attrs['stroke-linecap'] = SVG_STROKE_CAP[cap] ?? 'butt'if (stroke.join && stroke.join !== 'MITER') {attrs['stroke-linejoin'] = SVG_STROKE_JOIN[stroke.join] ?? 'miter'}@@ -413,7 +436,7 @@ function renderNode(node: SceneNode, ctx: SVGExportContext): SVGNode | null {? resolveFill(visibleFills[0], node, ctx): nullconst fillAttr = ownFill && tint.includes('fill') ? CURRENT_COLOR : ownFill- const ownStrokes = buildSVGStrokeAttrs(visibleStrokes, ctx.colorSpace)+ const ownStrokes = buildSVGStrokeAttrs(visibleStrokes, ctx.colorSpace, node.strokeCap)const strokeAttrs =ownStrokes.stroke && tint.includes('stroke')? { ...ownStrokes, stroke: CURRENT_COLOR }diff --git a/packages/core/tests/canvas/strokes/line.test.ts b/packages/core/tests/canvas/strokes/line.test.tsnew file mode 100644index 000000000..54d6db41f--- /dev/null+++ b/packages/core/tests/canvas/strokes/line.test.ts@@ -0,0 +1,180 @@+import { afterAll, describe, expect, test } from 'bun:test'++import { SkiaRenderer } from '@open-pencil/core'+import { initCanvasKit } from '@open-pencil/core/io'+import { SceneGraph, type SceneNode, type Stroke } from '@open-pencil/scene-graph'++import { silhouetteBounds } from '#core/canvas/shadows/silhouette'+import { makeLineStrokeOutline } from '#core/canvas/strokes/line'++import { expectDefined } from '#core-tests/helpers/assert'++const SIZE = 400++const ck = await initCanvasKit()+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(SIZE, SIZE), 'surface'))+afterAll(() => renderer.destroy())++/** Draws a 300 px line at (50, 200) with a 6 px black stroke and returns its pixels' alpha. */+function drawLine(props: Partial<SceneNode> = {}, stroke: Partial<Stroke> = {}): Uint8Array {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ graph.createNode('LINE', page, {+ x: 50,+ y: 200,+ width: 300,+ height: 0,+ fills: [],+ strokeWeight: 6,+ ...props,+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ weight: 6,+ align: 'CENTER',+ ...stroke+ }+ ]+ })+ renderer.pageId = page+ const canvas = renderer.surface.getCanvas()+ canvas.clear(ck.TRANSPARENT)+ renderer.renderSceneToCanvas(canvas, graph, page)+ renderer.surface.flush()+ const image = renderer.surface.makeImageSnapshot()+ try {+ const pixels = expectDefined(+ image.readPixels(0, 0, {+ width: SIZE,+ height: SIZE,+ colorType: ck.ColorType.RGBA_8888,+ alphaType: ck.AlphaType.Unpremul,+ colorSpace: ck.ColorSpace.SRGB+ }),+ 'pixels'+ )+ return Uint8Array.from({ length: SIZE * SIZE }, (_, index) => pixels[index * 4 + 3])+ } finally {+ image.delete()+ }+}++/** The painted pixels' bounds, as [left, top, right, bottom] inclusive. */+function paintedBox(alpha: Uint8Array): number[] {+ const box = [SIZE, SIZE, -1, -1]+ alpha.forEach((value, index) => {+ if (value === 0) return+ const x = index % SIZE+ const y = Math.floor(index / SIZE)+ box[0] = Math.min(box[0], x)+ box[1] = Math.min(box[1], y)+ box[2] = Math.max(box[2], x)+ box[3] = Math.max(box[3], y)+ })+ return box+}++// Figma 126 strokes a line a full weight to its upper side, whatever the stroke's alignment, and+// keeps caps and heads inside its length: a 300 px line with a 6 px stroke gives the stroke+// geometry `M0 -3 L0 0 L300 0 L300 -6 L0 -6 Z`, and its export paints rows 194–199 at y 200.+describe('a line stroke', () => {+ test('draws a full weight above the line', () => {+ expect(paintedBox(drawLine())).toEqual([50, 194, 349, 199])+ })++ test('ignores the stroke alignment', () => {+ expect(paintedBox(drawLine({}, { align: 'INSIDE' }))).toEqual([50, 194, 349, 199])+ expect(paintedBox(drawLine({}, { align: 'OUTSIDE' }))).toEqual([50, 194, 349, 199])+ })++ test('keeps round and square caps inside its length', () => {+ expect(paintedBox(drawLine({}, { cap: 'ROUND' }))).toEqual([50, 194, 349, 199])+ expect(paintedBox(drawLine({}, { cap: 'SQUARE' }))).toEqual([50, 194, 349, 199])+ })++ test('keeps a triangle head inside its length, on the middle of the stroke', () => {+ expect(paintedBox(drawLine({}, { cap: 'TRIANGLE_FILLED' }))).toEqual([53, 179, 346, 214])+ })++ test('turns its stroke with the line', () => {+ expect(paintedBox(drawLine({ rotation: 90 }))).toEqual([50, 200, 55, 399])+ })++ test('stretches its dashes to whole periods, with half a dash at each end', () => {+ // Dashes of 10 and gaps of 5 fit 20 times into 300: 0–5, 10–20, 25–35 … 295–300.+ const alpha = drawLine({}, { dashPattern: [10, 5] })+ const row = Array.from({ length: SIZE }, (_, x) => alpha[197 * SIZE + x] > 0)+ expect(row.slice(50, 55).every(Boolean)).toBe(true)+ expect(row.slice(55, 60).some(Boolean)).toBe(false)+ expect(row.slice(60, 70).every(Boolean)).toBe(true)+ expect(row.slice(345, 350).every(Boolean)).toBe(true)+ expect(row[350]).toBe(false)+ })+})++// Booleans and flattening take a line as its stroke outline: Figma's stroke geometry for a 300 px+// line with a 6 px stroke and triangle heads spans x 3 to 297 and y -20.32 to 14.32.+describe('a line taken as a boolean operand', () => {+ test('keeps its heads and the shaft between them', () => {+ const graph = new SceneGraph()+ const line = graph.createNode('LINE', graph.getPages()[0].id, {+ width: 300,+ height: 0,+ strokeCap: 'TRIANGLE_FILLED',+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ weight: 6,+ align: 'CENTER'+ }+ ]+ })+ const outline = expectDefined(makeLineStrokeOutline(renderer, line), 'outline')+ const [left, top, right, bottom] = outline.getBounds()+ outline.delete()+ expect(left).toBeCloseTo(3, 3)+ expect(top).toBeCloseTo(-20.3205, 3)+ expect(right).toBeCloseTo(297, 3)+ expect(bottom).toBeCloseTo(14.3205, 3)+ })+})++describe('a line casts from its whole stroke', () => {+ test('its shadow reaches a full weight past the line, whatever the alignment', () => {+ const graph = new SceneGraph()+ const line = graph.createNode('LINE', graph.getPages()[0].id, {+ width: 300,+ height: 0,+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ weight: 6,+ align: 'INSIDE'+ }+ ],+ effects: [+ {+ type: 'DROP_SHADOW',+ radius: 0,+ spread: 0,+ offset: { x: 0, y: 0 },+ color: { r: 0, g: 0, b: 0, a: 1 },+ visible: true,+ blendMode: 'NORMAL',+ showShadowBehindNode: false+ }+ ]+ })+ const bounds = expectDefined(silhouetteBounds(graph, line, false), 'bounds')+ expect(bounds.y).toBeLessThanOrEqual(-6)+ })+})diff --git a/packages/core/tests/io/formats/svg/export.test.ts b/packages/core/tests/io/formats/svg/export.test.tsnew file mode 100644index 000000000..d8f5f0aa1--- /dev/null+++ b/packages/core/tests/io/formats/svg/export.test.ts@@ -0,0 +1,53 @@+import { describe, expect, test } from 'bun:test'++import { renderNodesToSVG } from '@open-pencil/core'+import { SceneGraph, type SceneNode, type Stroke } from '@open-pencil/scene-graph'++import { expectDefined } from '#core-tests/helpers/assert'++/** The attributes of the `<line>` an SVG export writes for a line with a 6 px black stroke. */+function exportedLine(props: Partial<SceneNode>, stroke: Partial<Stroke> = {}): Map<string, string> {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const line = graph.createNode('LINE', page, {+ width: 300,+ height: 0,+ strokeWeight: 6,+ ...props,+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ weight: 6,+ align: 'CENTER',+ ...stroke+ }+ ]+ })+ const svg = expectDefined(renderNodesToSVG(graph, page, [line.id]), 'SVG output')+ const element = expectDefined(/<line\b([^>]*)>/.exec(svg), 'line element')[1]+ return new Map(Array.from(element.matchAll(/([\w-]+)="([^"]*)"/g), ([, name, value]) => [name, value]))+}++// The canvas strokes a line as Figma 126 does; its export draws the same.+describe('a line exported to SVG', () => {+ test('takes its cap from the layer when the stroke has none, pulled in to end with the line', () => {+ const line = exportedLine({ strokeCap: 'ROUND' })+ expect(line.get('stroke-linecap')).toBe('round')+ expect(line.get('x1')).toBe('3')+ expect(line.get('x2')).toBe('297')+ expect(line.get('y1')).toBe('-3')+ })++ test('stretches its dashes to whole periods, with half a dash at each end', () => {+ // Dashes of 10 and gaps of 5 fit 20 times into 300 and 7 times, stretched, into 100: Figma's+ // stroke geometry for the 100 px line starts with a dash from 0 to 4.7619, which SVG rounds.+ const long = exportedLine({}, { dashPattern: [10, 5] })+ expect(long.get('stroke-dasharray')).toBe('10 5')+ expect(long.get('stroke-dashoffset')).toBe('5')+ const short = exportedLine({ width: 100 }, { dashPattern: [10, 5] })+ expect(Number(short.get('stroke-dashoffset'))).toBeCloseTo(4.7619, 1)+ })+})diff --git a/packages/scene-graph/src/arrow-caps.ts b/packages/scene-graph/src/arrow-caps.tsindex d9a6dd582..538781d23 100644--- a/packages/scene-graph/src/arrow-caps.ts+++ b/packages/scene-graph/src/arrow-caps.ts@@ -336,13 +336,29 @@ function trimSegmentEnd(}}-/** 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 }- ]+/**+ * Where Figma strokes a LINE running from its origin to (`width`, `height`): a full weight to one+ * side, toward its local negative y, whatever the stroke's alignment. Under a cap both ends come in+ * by half a weight, so the cap or head ends where the line does; an equilateral arrow already+ * comes to its point at the end, so it stays there.+ */+export function lineStrokeEnds(+ width: number,+ height: number,+ weight: number,+ cap: StrokeCap | undefined+): { start: Vector; end: Vector } {+ const length = Math.hypot(width, height)+ if (length === 0) return { start: { x: 0, y: 0 }, end: { x: 0, y: 0 } }+ const ux = width / length+ const uy = height / length+ const inset =+ cap === undefined || cap === 'NONE' || cap === 'ARROW_EQUILATERAL'+ ? 0+ : Math.min(weight, length) / 2+ const offset = { x: (uy * weight) / 2, y: (-ux * weight) / 2 }+ return {+ start: { x: ux * inset + offset.x, y: uy * inset + offset.y },+ end: { x: width - ux * inset + offset.x, y: height - uy * inset + offset.y }+ }}diff --git a/packages/scene-graph/src/geometry.ts b/packages/scene-graph/src/geometry.tsindex 685c68cf9..6bda46047 100644--- a/packages/scene-graph/src/geometry.ts+++ b/packages/scene-graph/src/geometry.ts@@ -138,8 +138,12 @@ export function polygonVertices(node: {})}-/** A layer's stroke join and miter limit, for the tips mitered path corners reach. */-export interface StrokeCorners {+/**+ * What shapes how far a layer's stroke reaches past its box: its type, since a line is stroked to+ * one side, and its join and miter limit, for the tips mitered path corners reach.+ */+export interface StrokeShape {+ type?: stringstrokeJoin?: StrokeJoinstrokeMiterLimit?: number}@@ -148,20 +152,23 @@ export function strokeOverflow(strokes?: Stroke[],fallbackCap?: StrokeCap,network?: VectorNetwork | null,- corners?: StrokeCorners+ shape?: StrokeShape): number {+ const line = shape?.type === 'LINE'let overflow = 0for (const stroke of strokes ?? []) {if (!stroke.visible) continuelet extra = 0- if (stroke.align === 'OUTSIDE') extra = stroke.weight+ if (line || stroke.align === 'OUTSIDE') extra = stroke.weightelse if (stroke.align === 'CENTER') extra = stroke.weight / 2const miter = network- ? miterRatio(network, stroke.join ?? corners?.strokeJoin, corners?.strokeMiterLimit)+ ? miterRatio(network, stroke.join ?? shape?.strokeJoin, shape?.strokeMiterLimit): 1overflow = Math.max(overflow, extra * miter)}- return Math.max(overflow, arrowCapOverflow(strokes, fallbackCap, network))+ // A line's heads sit on its stroke's middle, half a weight off the line.+ const heads = arrowCapOverflow(strokes, fallbackCap, network)+ return Math.max(overflow, heads > 0 && line ? heads + overflow / 2 : heads)}/** The direction a segment leaves `vertex` in, along its handle when it has one. */@@ -250,7 +257,7 @@ export function computeVisualBounds(strokeCap?: StrokeCapvectorNetwork?: VectorNetwork | nulleffects?: Effect[]- } & StrokeCorners+ } & StrokeShape>,getAbsolutePosition: (id: string) => Vector): Rect {diff --git a/packages/scene-graph/tests/arrow-caps.test.ts b/packages/scene-graph/tests/arrow-caps.test.tsnew file mode 100644index 000000000..5169e31ec--- /dev/null+++ b/packages/scene-graph/tests/arrow-caps.test.ts@@ -0,0 +1,57 @@+import { describe, expect, test } from 'bun:test'++import type { Stroke } from '@open-pencil/scene-graph'+import { lineStrokeEnds } from '@open-pencil/scene-graph/arrow-caps'+import { strokeOverflow } from '@open-pencil/scene-graph/geometry'++// From Figma 126 stroke geometry: a 300 px line with a 6 px stroke runs its stroke along y = -3,+// over the whole line without a cap or with an equilateral arrow, and from 3 to 297 under the+// other caps.+describe('lineStrokeEnds', () => {+ test('runs half a weight above the line, end to end without a cap', () => {+ expect(lineStrokeEnds(300, 0, 6, 'NONE')).toEqual({+ start: { x: 0, y: -3 },+ end: { x: 300, y: -3 }+ })+ })++ test('comes in half a weight at each end under a cap', () => {+ for (const cap of ['ROUND', 'SQUARE', 'ARROW_LINES', 'TRIANGLE_FILLED'] as const) {+ expect(lineStrokeEnds(300, 0, 6, cap)).toEqual({+ start: { x: 3, y: -3 },+ end: { x: 297, y: -3 }+ })+ }+ })++ test('keeps the point of an equilateral arrow at the end', () => {+ expect(lineStrokeEnds(240, 0, 8, 'ARROW_EQUILATERAL')).toEqual({+ start: { x: 0, y: -4 },+ end: { x: 240, y: -4 }+ })+ })++ test('moves to the side of a line that runs at an angle', () => {+ const { start, end } = lineStrokeEnds(30, 40, 10, 'ROUND')+ expect(start.x).toBeCloseTo(7, 9)+ expect(start.y).toBeCloseTo(1, 9)+ expect(end.x).toBeCloseTo(31, 9)+ expect(end.y).toBeCloseTo(33, 9)+ })+})++describe('strokeOverflow for a line', () => {+ const stroke: Stroke = {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ weight: 6,+ align: 'INSIDE'+ }++ test('reaches a full weight past the line, whatever the alignment', () => {+ expect(strokeOverflow([stroke], 'NONE', null, { type: 'LINE' })).toBe(6)+ expect(strokeOverflow([stroke], 'NONE', null, { type: 'RECTANGLE' })).toBe(0)+ })+})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.pngindex 7f529199c..ba5350010 100644Binary 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 differdiff --git a/tests/e2e/canvas/fill-modes-visual.spec.ts b/tests/e2e/canvas/fill-modes-visual.spec.tsindex 7c47397bd..fc3bdab9e 100644--- a/tests/e2e/canvas/fill-modes-visual.spec.ts+++ b/tests/e2e/canvas/fill-modes-visual.spec.ts@@ -279,10 +279,12 @@ test('gradients and image fill modes', async () => {expect(Math.min(r, g, b)).toBeLessThan(200)}await editor.canvas.waitForRender()+ // A line is stroked to its upper side: the one turned down covers 730–733, the one turned up+ // 747–750.const [cropPixel, ...linePixels] = await readScenePixels(editor.page, [{ x: 706, y: 235 },- { x: 730, y: 130 },- { x: 750, y: 130 }+ { x: 731, y: 130 },+ { x: 748, y: 130 }])expect(cropPixel.slice(0, 3)).toEqual([17, 24, 39])for (const [r, g, b] of linePixels) {diff --git a/tests/e2e/canvas/stroke-paint-visual.spec.ts-snapshots/gradient-lines-openpencil-darwin.png b/tests/e2e/canvas/stroke-paint-visual.spec.ts-snapshots/gradient-lines-openpencil-darwin.pngindex 9cec82b3c..88bb74f0c 100644Binary files a/tests/e2e/canvas/stroke-paint-visual.spec.ts-snapshots/gradient-lines-openpencil-darwin.png and b/tests/e2e/canvas/stroke-paint-visual.spec.ts-snapshots/gradient-lines-openpencil-darwin.png differdiff --git a/tests/engine/geometry/arrow-caps.test.ts b/tests/engine/geometry/arrow-caps.test.tsindex b70171908..0e7ab851e 100644--- a/tests/engine/geometry/arrow-caps.test.ts+++ b/tests/engine/geometry/arrow-caps.test.ts@@ -10,7 +10,6 @@ import {diamondCapPoints,equilateralArrowPoints,isArrowCap,- lineArrowEndpoints,triangleCapPoints,trimArrowShafts} from '@open-pencil/scene-graph/arrow-caps'@@ -200,31 +199,6 @@ describe('arrowLinesSegments', () => {})})-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 {type: 'SOLID',diff --git a/tests/engine/geometry/visual-bounds.test.ts b/tests/engine/geometry/visual-bounds.test.tsindex 116723a7f..08d86d876 100644--- a/tests/engine/geometry/visual-bounds.test.ts+++ b/tests/engine/geometry/visual-bounds.test.ts@@ -449,8 +449,9 @@ describe('computeVisualBounds', () => {(id) => nodes[id as keyof typeof nodes],() => ({ x: 0, y: 0 }))- // 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)+ // A triangle head reaches furthest on a short line: from the end to its base corners. A+ // line's head sits on its stroke's middle, half a weight off the line.+ expect(bounds?.minY).toBeCloseTo(-4 * Math.hypot(5, 5 / Math.sqrt(3)) - 2, 5)})test('nested clipping stops descendants outside the ancestor clip', () => {diff --git a/tests/engine/render/canvas/boolean.test.ts b/tests/engine/render/canvas/boolean.test.tsindex 87328820f..8bdff8b67 100644--- a/tests/engine/render/canvas/boolean.test.ts+++ b/tests/engine/render/canvas/boolean.test.ts@@ -163,8 +163,9 @@ describe('boolean operation paths', () => {const path = makeBooleanOperationPath(r, node, api.graph)const bounds = path?.getBounds()- expect(bounds?.[2]).toBeGreaterThan(145)- expect(bounds?.[3]).toBeGreaterThan(100)+ // A line is stroked to its upper side, so the outline reaches past it to the right.+ expect(bounds?.[2]).toBeGreaterThan(150)+ expect(bounds?.[3]).toBeCloseTo(100, 3)path?.delete()})