Skip to content

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

fix(svg): draw FigJam shapes and arrow heads in SVG and PDF export (#1519)

Danila Poyarkov6e16b949c0f0
diff --git a/changes/1519/fixed.md b/changes/1519/fixed.md
new file mode 100644
index 000000000..34ef1301e
--- /dev/null
+++ b/changes/1519/fixed.md
@@ -0,0 +1 @@
+- SVG and PDF exports draw FigJam shapes in their own outlines, with inner lines such as a database's rim, instead of as rounded rectangles, and arrows and connectors keep their arrow heads and rounded corners.
diff --git a/packages/core/src/canvas/strokes/line.ts b/packages/core/src/canvas/strokes/line.ts
index 397a77528..554a0ab67 100644
--- a/packages/core/src/canvas/strokes/line.ts
+++ b/packages/core/src/canvas/strokes/line.ts
@@ -24,7 +24,7 @@ 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) {
+export 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 = {
diff --git a/packages/core/src/io/formats/svg/arrows.ts b/packages/core/src/io/formats/svg/arrows.ts
new file mode 100644
index 000000000..66a980cfd
--- /dev/null
+++ b/packages/core/src/io/formats/svg/arrows.ts
@@ -0,0 +1,148 @@
+import type { SceneNode, StrokeCap, VectorNetwork } from '@open-pencil/scene-graph'
+import {
+ arrowLinesSegments,
+ circleCapRadius,
+ collectArrowEndpoints,
+ diamondCapPoints,
+ equilateralArrowPoints,
+ hasTrimmedShaft,
+ trimArrowShafts,
+ triangleCapPoints,
+ type ArrowEndpoint
+} from '@open-pencil/scene-graph/arrow-caps'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+import { addOpenSegmentsToPath } from '#core/vector/path-helpers'
+
+import { svg, type SVGNode } from './node'
+import { round, svgPathSink } from './paths'
+
+type Attrs = Record<string, string | number | undefined>
+
+/** Which of a network's segments to draw: all of them, or those no region encloses. */
+type SegmentsOf = (network: VectorNetwork) => VectorNetwork['segments']
+
+const allSegments: SegmentsOf = (network) => network.segments
+
+/**
+ * Open segments of a vector network as the canvas strokes them: corners rounded by the layer's
+ * corner radius, and, under `stroke`, the line pulled back from each triangle or equilateral head.
+ * The whole network is trimmed before `segmentsOf` picks from it, so only its own open ends are.
+ */
+function openStrokePath(
+ node: Pick<SceneNode, 'cornerRadius' | 'strokeCap'>,
+ network: VectorNetwork,
+ stroke: { weight: number; cap?: StrokeCap; align: string } | undefined,
+ segmentsOf: SegmentsOf
+): string {
+ const cap = stroke?.cap ?? node.strokeCap
+ const trimmed =
+ stroke?.align === 'CENTER' && hasTrimmedShaft(network, cap)
+ ? trimArrowShafts(network, cap, stroke.weight)
+ : network
+ const parts: string[] = []
+ const segments = segmentsOf(trimmed)
+ addOpenSegmentsToPath(svgPathSink(parts), segments, trimmed.vertices, node.cornerRadius)
+ return parts.join('')
+}
+
+/** Stroke attributes cleared, for a fill drawn apart from its stroke. */
+const NO_STROKE = {
+ stroke: undefined,
+ 'stroke-width': undefined,
+ 'stroke-opacity': undefined,
+ 'stroke-linecap': undefined,
+ 'stroke-linejoin': undefined,
+ 'stroke-dasharray': undefined
+}
+
+/**
+ * A network's open segments, chosen by `segmentsOf`, as the canvas draws them: corners rounded, and
+ * the line pulled back under its heads, with any fill kept to the whole path.
+ */
+export function openPathElements(
+ node: Pick<SceneNode, 'cornerRadius' | 'strokeCap' | 'strokes'>,
+ network: VectorNetwork,
+ common: Attrs,
+ segmentsOf: SegmentsOf = allSegments
+): SVGNode[] {
+ const stroke = node.strokes.find((item) => item.visible)
+ const d = openStrokePath(node, network, stroke, segmentsOf)
+ const whole = openStrokePath(node, network, undefined, segmentsOf)
+ if (d === whole) return [svg('path', { d, ...common })]
+ const shaft = svg('path', { d, ...common, fill: 'none' })
+ if (common.fill === 'none') return [shaft]
+ return [svg('path', { d: whole, ...common, ...NO_STROKE }), shaft]
+}
+
+function polygonData(points: readonly Vector[]): string {
+ const commands = points.map(({ x, y }, index) => `${index ? 'L' : 'M'}${round(x)} ${round(y)}`)
+ return `${commands.join('')}Z`
+}
+
+/**
+ * A head on an open end, in the stroke's colour as `strokeAttrs` gives it: a line arrow stroked at
+ * the line's weight with round ends, the others filled.
+ */
+function headElement(
+ { x, y, angle, cap }: ArrowEndpoint,
+ weight: number,
+ strokeAttrs: Attrs
+): SVGNode {
+ const color = strokeAttrs.stroke
+ const opacity = strokeAttrs['stroke-opacity']
+ const filled = (points: readonly Vector[]) =>
+ svg('path', { d: polygonData(points), fill: color, 'fill-opacity': opacity })
+ switch (cap) {
+ case 'ARROW_LINES': {
+ // One path, so the wings meet in a round join rather than overlapping at the tip.
+ const [first, second] = arrowLinesSegments(x, y, angle, weight)
+ const point = ({ x: px, y: py }: Vector) => `${round(px)} ${round(py)}`
+ return svg('path', {
+ d: `M${point(first.to)}L${point(first.from)}L${point(second.to)}`,
+ fill: 'none',
+ stroke: color,
+ 'stroke-opacity': opacity,
+ 'stroke-width': round(weight),
+ 'stroke-linecap': 'round',
+ 'stroke-linejoin': 'round'
+ })
+ }
+ case 'CIRCLE_FILLED':
+ return svg('circle', {
+ cx: round(x),
+ cy: round(y),
+ r: round(circleCapRadius(weight)),
+ fill: color,
+ 'fill-opacity': opacity
+ })
+ case 'ARROW_EQUILATERAL':
+ return filled(equilateralArrowPoints(x, y, angle, weight))
+ case 'TRIANGLE_FILLED':
+ return filled(triangleCapPoints(x, y, angle, weight))
+ }
+ return filled(diamondCapPoints(x, y, angle, weight))
+}
+
+/** The arrow heads a stroke puts on `network`'s open ends, or none without a visible stroke. */
+export function arrowHeadElements(
+ node: Pick<SceneNode, 'strokeCap'>,
+ network: VectorNetwork,
+ stroke: { weight: number; cap?: StrokeCap } | undefined,
+ strokeAttrs: Attrs
+): SVGNode[] {
+ if (!stroke || !strokeAttrs.stroke || strokeAttrs.stroke === 'none') return []
+ return collectArrowEndpoints(network, stroke.cap ?? node.strokeCap).map((endpoint) =>
+ headElement(endpoint, stroke.weight, strokeAttrs)
+ )
+}
+
+/** The heads a vector's first visible stroke puts on its open ends. */
+export function vectorArrowHeads(
+ node: Pick<SceneNode, 'strokeCap' | 'strokes'>,
+ network: VectorNetwork,
+ strokeAttrs: Attrs
+): SVGNode[] {
+ const stroke = node.strokes.find((item) => item.visible)
+ return arrowHeadElements(node, network, stroke, strokeAttrs)
+}
diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.ts
index c807058b9..bb8ab3778 100644
--- a/packages/core/src/io/formats/svg/export.ts
+++ b/packages/core/src/io/formats/svg/export.ts
@@ -1,7 +1,7 @@
-import { lineStrokeEnds } from '@open-pencil/scene-graph/arrow-caps'
import type { RenderColorSpace } from '@open-pencil/scene-graph/color'
import { normalizeDashPattern } from '#core/canvas/strokes'
+import { lineStrokePath } from '#core/canvas/strokes/line'
import { fittedDashPattern } from '#core/canvas/strokes/sides'
import { computeContentBounds } from '#core/io/formats/raster'
@@ -18,12 +18,15 @@ import {
import {
round,
geometryBlobToSVGPath,
- vectorNetworkToSVGPaths,
makePolygonPoints,
roundedPolygonPath,
hasRadius,
roundedRectPath,
- arcPath
+ arcPath,
+ shapeWithTextDetailsPath,
+ shapeWithTextOutlinePath,
+ regionSVGPaths,
+ looseSegments
} from './paths'
export {
@@ -33,8 +36,9 @@ export {
type OutlineNode
} from './paths'
-import type { SceneGraph, SceneNode, Fill, Stroke } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode, Fill, Stroke, VectorNetwork } from '@open-pencil/scene-graph'
+import { arrowHeadElements, openPathElements, vectorArrowHeads } from './arrows'
import type { SVGExportContext, SVGFontAlias } from './defs'
import { svg, renderSVGNode } from './node'
import type { SVGNode } from './node'
@@ -43,6 +47,20 @@ import type { SVGTextLayout } from './text/lines'
// --- Node rendering ---
+/**
+ * A vector network's paths: its regions as they are traced, and its open segments as the canvas
+ * strokes them, rounded and pulled back under their heads.
+ */
+function networkElements(
+ node: SceneNode,
+ network: VectorNetwork,
+ common: Record<string, string | number | undefined>
+): SVGNode[] {
+ const regions = regionSVGPaths(network).map((d) => svg('path', { d, ...common }))
+ if (looseSegments(network).length === 0) return regions
+ return [...regions, ...openPathElements(node, network, common, looseSegments)]
+}
+
function vectorShapeElements(
node: SceneNode,
common: Record<string, string | number | undefined>,
@@ -84,10 +102,7 @@ function vectorShapeElements(
}
}
} else if (node.vectorNetwork) {
- const paths = vectorNetworkToSVGPaths(node.vectorNetwork)
- for (const d of paths) {
- elements.push(svg('path', { d, ...common }))
- }
+ elements.push(...networkElements(node, node.vectorNetwork, common))
}
if (node.strokeGeometry.length > 0 && strokeAttrs.stroke && strokeAttrs.stroke !== 'none') {
for (const geo of node.strokeGeometry) {
@@ -104,6 +119,7 @@ function vectorShapeElements(
}
}
}
+ if (node.vectorNetwork) elements.push(...vectorArrowHeads(node, node.vectorNetwork, strokeAttrs))
return elements.length > 0
? elements
: [svg('rect', { width: round(node.width), height: round(node.height), ...common })]
@@ -151,12 +167,11 @@ function nodeShapeElements(
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
- )
+ const {
+ network,
+ from: start,
+ to: end
+ } = lineStrokePath(node, stroke?.weight ?? 0, stroke?.cap ?? node.strokeCap)
return [
svg('line', {
x1: round(start.x),
@@ -166,7 +181,8 @@ function nodeShapeElements(
fill: 'none',
...strokeAttrs,
...lineDashAttrs(stroke, Math.hypot(end.x - start.x, end.y - start.y))
- })
+ }),
+ ...arrowHeadElements(node, network, stroke, strokeAttrs)
]
}
@@ -179,6 +195,9 @@ function nodeShapeElements(
case 'VECTOR':
return vectorShapeElements(node, common, strokeAttrs, ctx)
+ case 'SHAPE_WITH_TEXT':
+ return shapeWithTextElements(node, common, strokeAttrs, ctx)
+
default: {
if (hasRadius(node)) {
if (node.independentCorners) {
@@ -199,6 +218,29 @@ function nodeShapeElements(
}
}
+/**
+ * A FigJam shape's outline, and its inner lines, such as a database's front rim, stroked as the
+ * canvas strokes them: at the stroke's own weight, ending where the outline does.
+ */
+function shapeWithTextElements(
+ node: SceneNode,
+ common: Record<string, string | number | undefined>,
+ strokeAttrs: Record<string, string | number | undefined>,
+ ctx: SVGExportContext
+): SVGNode[] {
+ const outline = shapeWithTextOutlinePath(node)
+ const elements = [svg('path', { d: outline, ...common })]
+ const details = strokeAttrs.stroke ? shapeWithTextDetailsPath(node) : null
+ if (details) {
+ const clipId = nextDefId(ctx, 'clip')
+ ctx.defs.push(svg('clipPath', { id: clipId }, svg('path', { d: outline })))
+ elements.push(
+ svg('path', { d: details, fill: 'none', ...strokeAttrs, 'clip-path': `url(#${clipId})` })
+ )
+ }
+ return elements
+}
+
// --- Main recursive renderer ---
function buildTransformAttr(node: SceneNode): string | undefined {
diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.ts
index faf7e0a3e..5974f1d45 100644
--- a/packages/core/src/io/formats/svg/paths.ts
+++ b/packages/core/src/io/formats/svg/paths.ts
@@ -8,9 +8,11 @@ import type {
} from '@open-pencil/scene-graph'
import { polygonVertices } from '@open-pencil/scene-graph/geometry'
import { outlineSVGPath, polygonOutline } from '@open-pencil/scene-graph/polygon'
+import { shapeWithTextGeometry } from '@open-pencil/scene-graph/shape-with-text'
import { traceSmoothRect, type SmoothCornerSink } from '#core/canvas/paths/smooth-corners'
import { nodeHasRadius } from '#core/canvas/shapes'
+import type { PathSink } from '#core/vector/path-helpers'
const CMD_CLOSE = 0
const CMD_MOVE_TO = 1
@@ -217,24 +219,35 @@ export function vectorNetworkToSVGPaths(
network: VectorNetwork,
decimals: number | null = 2
): string[] {
- const { vertices, segments, regions } = network
+ const { vertices, regions } = network
if (regions.length === 0) {
const path = unfilledSegmentsToPath(network, decimals)
return path ? [path] : []
}
- const paths = regions.map((region) =>
- region.loops.map((loop) => traceOrderedSegments(loop, segments, vertices, decimals)).join('')
- )
+ const paths = regionSVGPaths(network, decimals)
// Segments no region encloses, such as an icon's open strokes beside its filled shapes,
// draw as open paths after the regions.
- const enclosed = new Set(regions.flatMap((region) => region.loops.flat()))
- const open = segments.filter((_, index) => !enclosed.has(index))
+ const open = looseSegments(network)
const loose =
open.length > 0 && unfilledSegmentsToPath({ vertices, segments: open, regions: [] }, decimals)
return loose ? [...paths, loose] : paths
}
+/** Each region of a vector network as path data, its loops traced in turn. */
+export function regionSVGPaths(network: VectorNetwork, decimals: number | null = 2): string[] {
+ const { vertices, segments, regions } = network
+ return regions.map((region) =>
+ region.loops.map((loop) => traceOrderedSegments(loop, segments, vertices, decimals)).join('')
+ )
+}
+
+/** The segments of a vector network that no region encloses. */
+export function looseSegments({ segments, regions }: VectorNetwork): VectorNetwork['segments'] {
+ const enclosed = new Set(regions.flatMap((region) => region.loops.flat()))
+ return segments.filter((_, index) => !enclosed.has(index))
+}
+
/** The outline of a polygon or star whose corners are rounded, as path data. */
export function roundedPolygonPath(node: SceneNode): string {
return outlineSVGPath(polygonOutline(node), (value) => round(value))
@@ -336,20 +349,28 @@ export function arcPath(node: Pick<SceneNode, 'width' | 'height' | 'arcData'>):
return parts.join('')
}
-/** A rectangle with smoothed corners as path data, traced as the canvas draws it. */
-function smoothRectPath(node: RectOutlineNode & Pick<SceneNode, 'cornerSmoothing'>): string {
- const parts: string[] = []
+/** Path commands written as SVG path data into `parts`, as the canvas would build a path. */
+export function svgPathSink(parts: string[]): PathSink {
const point = (x: number, y: number) => `${round(x)} ${round(y)}`
- const sink: SmoothCornerSink = {
+ return {
moveTo: (x, y) => parts.push(`M${point(x, y)}`),
lineTo: (x, y) => parts.push(`L${point(x, y)}`),
cubicTo: (x1, y1, x2, y2, x, y) =>
parts.push(`C${point(x1, y1)} ${point(x2, y2)} ${point(x, y)}`),
+ close: () => parts.push('Z')
+ }
+}
+
+/** A rectangle with smoothed corners as path data, traced as the canvas draws it. */
+function smoothRectPath(node: RectOutlineNode & Pick<SceneNode, 'cornerSmoothing'>): string {
+ const parts: string[] = []
+ const point = (x: number, y: number) => `${round(x)} ${round(y)}`
+ const sink: SmoothCornerSink = {
+ ...svgPathSink(parts),
arcToRotated: (rx, ry, rotation, useSmallArc, isCCW, x, y) =>
parts.push(
`A${round(rx)} ${round(ry)} ${rotation} ${useSmallArc ? 0 : 1} ${isCCW ? 0 : 1} ${point(x, y)}`
- ),
- close: () => parts.push('Z')
+ )
}
const box = { left: 0, top: 0, right: node.width, bottom: node.height }
return traceSmoothRect(sink, node, box) ? parts.join('') : roundedRectPath(node)
@@ -385,3 +406,27 @@ export function nodeOutlinePath(node: OutlineNode): string | null {
return null
}
}
+
+/** A FigJam shape's outline in its own box as path data, with its corner radius. */
+export function shapeWithTextOutlinePath(
+ node: Pick<SceneNode, 'shapeWithTextType' | 'width' | 'height' | 'cornerRadius'>
+): string {
+ const { outline } = shapeWithTextGeometry(
+ node.shapeWithTextType,
+ node.width,
+ node.height,
+ node.cornerRadius
+ )
+ return outlineSVGPath(outline, (value) => round(value))
+}
+
+/**
+ * A FigJam shape's stroke-only inner lines, such as a database's front rim, as path data; null for
+ * a shape without any.
+ */
+export function shapeWithTextDetailsPath(
+ node: Pick<SceneNode, 'shapeWithTextType' | 'width' | 'height'>
+): string | null {
+ const { details } = shapeWithTextGeometry(node.shapeWithTextType, node.width, node.height)
+ return details.length > 0 ? outlineSVGPath(details, (value) => round(value)) : null
+}
diff --git a/packages/core/tests/io/formats/svg/arrows.test.ts b/packages/core/tests/io/formats/svg/arrows.test.ts
new file mode 100644
index 000000000..838cb35b0
--- /dev/null
+++ b/packages/core/tests/io/formats/svg/arrows.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { renderNodesToSVG } from '@open-pencil/core/io/formats/svg'
+import { SceneGraph, type SceneNode, type Stroke, type StrokeCap } from '@open-pencil/scene-graph'
+import { createConnector, freeEndpoint } from '@open-pencil/scene-graph/connectors'
+
+const black = (weight: number, cap?: StrokeCap): Stroke => ({
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight,
+ align: 'CENTER',
+ cap
+})
+
+function exported(build: (graph: SceneGraph, pageId: string) => SceneNode): string {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const node = build(graph, pageId)
+ return expectDefined(renderNodesToSVG(graph, pageId, [node.id], { xmlDeclaration: false }))
+}
+
+/** A vector bent once at its middle, open at both ends. */
+function bent(cornerRadius: number, cap: StrokeCap): Partial<SceneNode> {
+ const straight = { x: 0, y: 0 }
+ return {
+ width: 200,
+ height: 60,
+ cornerRadius,
+ strokes: [black(3, cap)],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 60 },
+ { x: 100, y: 0 },
+ { x: 200, y: 60 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: straight, tangentEnd: straight },
+ { start: 1, end: 2, tangentStart: straight, tangentEnd: straight }
+ ],
+ regions: []
+ }
+ }
+}
+
+describe('arrow heads exported to SVG', () => {
+ test('a line ends in filled heads, its shaft stopping inside them', () => {
+ const plain = exported((graph, page) =>
+ graph.createNode('LINE', page, { width: 300, height: 0, strokes: [black(6, 'ROUND')] })
+ )
+ const headed = exported((graph, page) =>
+ graph.createNode('LINE', page, {
+ width: 300,
+ height: 0,
+ strokes: [black(6, 'TRIANGLE_FILLED')]
+ })
+ )
+ const end = (svg: string) => Number(expectDefined(/<line\b[^>]* x2="([\d.]+)"/.exec(svg))[1])
+ expect(end(headed)).toBeLessThan(end(plain))
+ expect(headed.match(/<path d="M[^"]+Z" fill="#000000"/g)).toHaveLength(2)
+ })
+
+ test('a connector’s line arrow is two wings stroked with round ends, a dot a circle', () => {
+ const svg = exported((graph, page) =>
+ createConnector(
+ graph,
+ page,
+ { start: freeEndpoint(0, 0), end: freeEndpoint(200, 0) },
+ { connectorStartCap: 'CIRCLE_FILLED', connectorEndCap: 'ARROW_LINES' }
+ )
+ )
+ expect(svg).toMatch(/<path d="M[^"]+L[^"]+L[^"]+" fill="none"[^>]*stroke-linecap="round"/)
+ expect(svg).toContain('<circle ')
+ })
+
+ test('an open path keeps its rounded corner and carries its heads', () => {
+ const corner = (radius: number) =>
+ exported((graph, page) => graph.createNode('VECTOR', page, bent(radius, 'TRIANGLE_FILLED')))
+ const shaft = (svg: string) => expectDefined(/<path d="([^"]+)" fill="none"/.exec(svg))[1]
+ expect(shaft(corner(16))).toContain('C')
+ expect(shaft(corner(0))).not.toContain('C')
+ expect(corner(16).match(/<path d="M[^"]+Z" fill="#000000"/g)).toHaveLength(2)
+ })
+
+ test('a loose segment beside a filled region stops short of its head too', () => {
+ const straight = { x: 0, y: 0 }
+ const segment = (start: number, end: number) => ({
+ start,
+ end,
+ tangentStart: straight,
+ tangentEnd: straight
+ })
+ const svg = exported((graph, page) =>
+ graph.createNode('VECTOR', page, {
+ width: 300,
+ height: 40,
+ strokes: [black(3, 'TRIANGLE_FILLED')],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 40, y: 0 },
+ { x: 20, y: 40 },
+ { x: 100, y: 20 },
+ { x: 300, y: 20 }
+ ],
+ segments: [segment(0, 1), segment(1, 2), segment(2, 0), segment(3, 4)],
+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]
+ }
+ })
+ )
+ // The loose line runs from 100 to 300 and ends inside the heads at either end.
+ const [, from, to] = expectDefined(/<path d="M([\d.]+) 20L([\d.]+) 20"/.exec(svg))
+ expect(Number(from)).toBeGreaterThan(100)
+ expect(Number(to)).toBeLessThan(300)
+ })
+
+ test('a loose segment leaving a filled region keeps its join and stops short of its head', () => {
+ const straight = { x: 0, y: 0 }
+ const segment = (start: number, end: number) => ({
+ start,
+ end,
+ tangentStart: straight,
+ tangentEnd: straight
+ })
+ const svg = exported((graph, page) =>
+ graph.createNode('VECTOR', page, {
+ width: 300,
+ height: 40,
+ strokes: [black(3, 'TRIANGLE_FILLED')],
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 40, y: 20 },
+ { x: 0, y: 40 },
+ { x: 300, y: 20 }
+ ],
+ segments: [segment(0, 1), segment(1, 2), segment(2, 0), segment(1, 3)],
+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]
+ }
+ })
+ )
+ // The line leaves the triangle's tip at 40 untrimmed, and ends inside its one head.
+ const [, to] = expectDefined(/<path d="M40 20L([\d.]+) 20"/.exec(svg))
+ expect(Number(to)).toBeLessThan(300)
+ expect(svg.match(/<path d="M[^"]+Z" fill="#000000"/g)).toHaveLength(1)
+ })
+})
diff --git a/packages/core/tests/io/formats/svg/export.test.ts b/packages/core/tests/io/formats/svg/export.test.ts
index fe769e573..c779a84e9 100644
--- a/packages/core/tests/io/formats/svg/export.test.ts
+++ b/packages/core/tests/io/formats/svg/export.test.ts
@@ -9,6 +9,9 @@ import {
} from '@open-pencil/core/io/formats/svg'
import { parsePenFile } from '@open-pencil/pen'
import { SceneGraph, type Fill, type SceneNode, type Stroke } from '@open-pencil/scene-graph'
+import { createShapeWithText } from '@open-pencil/scene-graph/generated'
+import { outlineSVGPath } from '@open-pencil/scene-graph/polygon'
+import { shapeWithTextGeometry } from '@open-pencil/scene-graph/shape-with-text'
import { renderNodeSVGElement } from '#core/io/formats/svg/export'
@@ -410,3 +413,46 @@ describe('solid paint opacity exported to SVG', () => {
])
})
})
+
+describe('FigJam shapes exported to SVG', () => {
+ const stroke: Stroke = {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ weight: 2,
+ opacity: 1,
+ visible: true,
+ align: 'CENTER'
+ }
+
+ /** The SVG a page holding one FigJam shape of `type`, outlined in black, exports to. */
+ function exportedShape(shapeWithTextType: SceneNode['shapeWithTextType']) {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const shape = createShapeWithText(
+ graph,
+ page,
+ { shapeWithTextType, width: 120, height: 80, strokes: [stroke] },
+ {}
+ )
+ return { shape, svg: expectDefined(renderNodesToSVG(graph, page, [shape.id])) }
+ }
+
+ test('draw their own outline, not a box', () => {
+ const { shape, svg } = exportedShape('DIAMOND')
+ const outline = outlineSVGPath(
+ shapeWithTextGeometry('DIAMOND', shape.width, shape.height, shape.cornerRadius).outline,
+ (value) => Math.round(value * 100) / 100
+ )
+ expect(svg).toContain(`d="${outline}"`)
+ expect(svg).not.toContain('<rect')
+ })
+
+ test('stroke their inner lines inside the outline, as a database’s front rim', () => {
+ const { svg } = exportedShape('ENG_DATABASE')
+ const rim = expectDefined(
+ svg.match(/<path d="[^"]+" fill="none"[^>]*clip-path="url\(#([^)]+)\)"/)
+ )
+ expect(svg).toContain(`<clipPath id="${rim[1]}">`)
+ expect(exportedShape('DIAMOND').svg).not.toContain('clip-path')
+ })
+})