AI-native design editor. Open-source Figma alternative.
feat(design-jsx): draw and export vectors as <Vector d> and <Vector paths> (#1573)
Danila Poyarkov4c7f97a7eede
diff --git a/changes/1573/added.md b/changes/1573/added.mdnew file mode 100644index 000000000..e77ffd945--- /dev/null+++ b/changes/1573/added.md@@ -0,0 +1 @@+- Design JSX `<Vector>` takes its path as SVG path data (`d`, with `fillRule`) or as Figma's `vectorPaths` (`paths`), and JSX export writes every vector's paths, so vectors and inline SVG artwork no longer render back empty.diff --git a/changes/1573/breaking.md b/changes/1573/breaking.mdnew file mode 100644index 000000000..21bb45f45--- /dev/null+++ b/changes/1573/breaking.md@@ -0,0 +1,2 @@+- `@open-pencil/core/io/formats/svg` no longer exports `vectorNetworkToSVGPaths`; import it from `@open-pencil/scene-graph/vector-network`.+- `createDesignJSXRenderer` from `@open-pencil/design-jsx` takes a `vectorBounds(network)` service, which measures a `<Vector>`'s path; `@open-pencil/core/design-jsx` provides it.diff --git a/packages/core/src/design-jsx/renderer.ts b/packages/core/src/design-jsx/renderer.tsindex e1fbd5462..90cdac93d 100644--- a/packages/core/src/design-jsx/renderer.ts+++ b/packages/core/src/design-jsx/renderer.ts@@ -4,6 +4,7 @@ import { defaultIcons, placeIcon, type IconProvider } from '#core/icons'import { extractPaths, extractPathsFromElements, scalePathInfos } from '#core/icons/svg'import type { IconData } from '#core/icons/types'import { layoutAuthoredNodes } from '#core/layout'+import { computeAccurateBounds } from '#core/vector/curve-math'function parseViewBox(viewBox: string | undefined): { w: number; h: number } {if (!viewBox) return { w: 0, h: 0 }@@ -52,7 +53,8 @@ function createRenderer(icons: IconProvider) {// Inline SVG is artwork, not an icon from a set.identity: icon.prefix !== INLINE_SVG}),- layout: layoutAuthoredNodes+ layout: layoutAuthoredNodes,+ vectorBounds: computeAccurateBounds})}diff --git a/packages/core/src/figma-api/accessors/vector.ts b/packages/core/src/figma-api/accessors/vector.tsindex f12b588ed..812274dea 100644--- a/packages/core/src/figma-api/accessors/vector.ts+++ b/packages/core/src/figma-api/accessors/vector.ts@@ -11,7 +11,8 @@ import {mergeVectorNetworks,normalizeVectorNetwork,transformVectorNetwork,- validateVectorNetwork+ validateVectorNetwork,+ vectorNetworkPaths} from '@open-pencil/scene-graph/vector-network'import {@@ -23,7 +24,7 @@ import {type ProxyThis} from '#core/figma-api/accessor-utils'import { parseFigmaPaints, toFigmaPaint, type FigmaPaint } from '#core/figma-api/paints'-import { geometryBlobToSVGPath, vectorNetworkToSVGPaths } from '#core/io/formats/svg/paths'+import { geometryBlobToSVGPath } from '#core/io/formats/svg/paths'import { computeAccurateBounds } from '#core/vector/curve-math'import { regenerateFillGeometry } from '#core/vector/fill-geometry'@@ -170,39 +171,6 @@ function assignVectorNetwork(setGeometry(target, internals, network, fillGeometry)}-function vectorPathsForNetwork(network: SceneVectorNetwork): FigmaVectorPath[] {- if (network.segments.length === 0) return []- const regions = (network as Partial<SceneVectorNetwork>).regions ?? []- if (regions.length === 0) {- return vectorNetworkToSVGPaths({ ...network, regions }, null).map((data) => ({- windingRule: 'NONE',- data- }))- }-- const paths: FigmaVectorPath[] = []- const usedSegments = new Set<number>()- for (const region of regions) {- for (const loop of region.loops) for (const segmentIndex of loop) usedSegments.add(segmentIndex)- const data = vectorNetworkToSVGPaths({ ...network, regions: [region] }, null)[0]- if (data) paths.push({ windingRule: region.windingRule, data })- }-- const remainingSegments = network.segments.filter((_, index) => !usedSegments.has(index))- if (remainingSegments.length > 0) {- const data = vectorNetworkToSVGPaths(- {- vertices: network.vertices,- segments: remainingSegments,- regions: []- },- null- )[0]- if (data) paths.push({ windingRule: 'NONE', data })- }- return paths-}-function readVectorPaths(target: ProxyThis,internals: NodeProxyInternals@@ -210,7 +178,7 @@ function readVectorPaths(const node = raw(target, internals)const paths =node.vectorNetwork && node.vectorNetwork.segments.length > 0- ? vectorPathsForNetwork(node.vectorNetwork)+ ? vectorNetworkPaths(node.vectorNetwork): node.fillGeometry.map((geometry) => ({windingRule: geometry.windingRule,data: geometryBlobToSVGPath(geometry.commandsBlob, null)diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.tsindex c5429c398..7b37fc551 100644--- a/packages/core/src/io/formats/svg/export.ts+++ b/packages/core/src/io/formats/svg/export.ts@@ -23,19 +23,13 @@ import {hasRadius,roundedRectPath,arcPath,- shapeWithTextOutlinePath,- regionSVGPaths,- looseSegments+ shapeWithTextOutlinePath} from './paths'-export {- geometryBlobToSVGPath,- nodeOutlinePath,- vectorNetworkToSVGPaths,- type OutlineNode-} from './paths'+export { geometryBlobToSVGPath, nodeOutlinePath, type OutlineNode } from './paths'import type { SceneGraph, SceneNode, Fill, Stroke, VectorNetwork } from '@open-pencil/scene-graph'+import { looseSegments, regionSVGPaths } from '@open-pencil/scene-graph/vector-network'import { arrowHeadElements, openPathElements, vectorArrowHeads } from './arrows'import type { SVGExportContext, SVGFontAlias } from './defs'diff --git a/packages/core/src/io/formats/svg/index.ts b/packages/core/src/io/formats/svg/index.tsindex dbcf2d41c..8d180122d 100644--- a/packages/core/src/io/formats/svg/index.ts+++ b/packages/core/src/io/formats/svg/index.ts@@ -3,7 +3,6 @@ export {type SVGExportOptions,geometryBlobToSVGPath,nodeOutlinePath,- vectorNetworkToSVGPaths,type OutlineNode} from './export'export {diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.tsindex 5974f1d45..1a66f034a 100644--- a/packages/core/src/io/formats/svg/paths.ts+++ b/packages/core/src/io/formats/svg/paths.ts@@ -1,14 +1,10 @@import { compact } from 'es-toolkit/array'-import type {- SceneNode,- VectorNetwork,- VectorSegment,- VectorVertex-} from '@open-pencil/scene-graph'+import type { SceneNode } 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 { vectorNetworkToSVGPaths } from '@open-pencil/scene-graph/vector-network'import { traceSmoothRect, type SmoothCornerSink } from '#core/canvas/paths/smooth-corners'import { nodeHasRadius } from '#core/canvas/shapes'@@ -83,171 +79,6 @@ export function geometryBlobToSVGPath(blob: Uint8Array, decimals: number | nullreturn parts.join('')}-function segmentToSVG(- seg: VectorSegment,- vertices: VectorVertex[],- forward: boolean,- decimals: number | null-): string {- const start = forward ? vertices[seg.start] : vertices[seg.end]- const end = forward ? vertices[seg.end] : vertices[seg.start]- const ts = forward ? seg.tangentStart : { x: -seg.tangentEnd.x, y: -seg.tangentEnd.y }- const te = forward ? seg.tangentEnd : { x: -seg.tangentStart.x, y: -seg.tangentStart.y }-- const isStraight =- Math.abs(ts.x) < 0.001 &&- Math.abs(ts.y) < 0.001 &&- Math.abs(te.x) < 0.001 &&- Math.abs(te.y) < 0.001-- if (isStraight) {- return `L${coordinate(end.x, decimals)} ${coordinate(end.y, decimals)}`- }-- const cp1x = coordinate(start.x + ts.x, decimals)- const cp1y = coordinate(start.y + ts.y, decimals)- const cp2x = coordinate(end.x + te.x, decimals)- const cp2y = coordinate(end.y + te.y, decimals)- return `C${cp1x} ${cp1y} ${cp2x} ${cp2y} ${coordinate(end.x, decimals)} ${coordinate(end.y, decimals)}`-}--function traceOrderedSegments(- segmentIndices: readonly number[],- segments: VectorSegment[],- vertices: VectorVertex[],- decimals: number | null-): string {- if (segmentIndices.length === 0) return ''- const first = segments[segmentIndices[0]]- const second = segmentIndices.length > 1 ? segments[segmentIndices[1]] : null- // Start at the first segment endpoint that does not connect to the second segment.- const secondConnectsStart = second?.start === first.start || second?.end === first.start- const secondConnectsEnd = second?.start === first.end || second?.end === first.end- const firstForward = !second || secondConnectsEnd || !secondConnectsStart- const startIndex = firstForward ? first.start : first.end- let currentIndex = startIndex- const parts = [- `M${coordinate(vertices[startIndex].x, decimals)} ${coordinate(vertices[startIndex].y, decimals)}`- ]-- for (const segmentIndex of segmentIndices) {- const segment = segments[segmentIndex]- const isConnected = segment.start === currentIndex || segment.end === currentIndex- const forward = segment.start === currentIndex || !isConnected- if (!isConnected) {- const segmentStart = forward ? segment.start : segment.end- parts.push(- `M${coordinate(vertices[segmentStart].x, decimals)} ${coordinate(vertices[segmentStart].y, decimals)}`- )- }- parts.push(segmentToSVG(segment, vertices, forward, decimals))- currentIndex = forward ? segment.end : segment.start- }- if (parts.length === segmentIndices.length + 1 && currentIndex === startIndex) parts.push('Z')- return parts.join('')-}--type SegmentAdjacency = ReadonlyMap<number, readonly number[]>--function buildSegmentAdjacency(segments: VectorSegment[]): SegmentAdjacency {- const adjacency = new Map<number, number[]>()- for (let index = 0; index < segments.length; index++) {- const segment = segments[index]- for (const vertexIndex of [segment.start, segment.end]) {- const incidentSegments = adjacency.get(vertexIndex)- if (incidentSegments) incidentSegments.push(index)- else adjacency.set(vertexIndex, [index])- }- }- return adjacency-}--function findConnectedSegment(- remaining: ReadonlySet<number>,- adjacency: SegmentAdjacency,- vertexIndex: number-): number | undefined {- return adjacency.get(vertexIndex)?.find((index) => remaining.has(index))-}--function extendSegmentChain(- chain: number[],- startVertex: number,- remaining: Set<number>,- segments: VectorSegment[],- adjacency: SegmentAdjacency-): void {- let currentIndex = startVertex- let nextIndex = findConnectedSegment(remaining, adjacency, currentIndex)- while (nextIndex !== undefined) {- chain.push(nextIndex)- remaining.delete(nextIndex)- const segment = segments[nextIndex]- currentIndex = segment.start === currentIndex ? segment.end : segment.start- nextIndex = findConnectedSegment(remaining, adjacency, currentIndex)- }-}--function unfilledSegmentsToPath(network: VectorNetwork, decimals: number | null): string {- const { vertices, segments } = network- const remaining = new Set(segments.map((_, index) => index))- const adjacency = buildSegmentAdjacency(segments)- const parts: string[] = []-- while (remaining.size > 0) {- const firstIndex = remaining.values().next().value- if (firstIndex === undefined) break- remaining.delete(firstIndex)- const first = segments[firstIndex]-- const backward: number[] = []- extendSegmentChain(backward, first.start, remaining, segments, adjacency)- backward.reverse()-- const forward: number[] = []- extendSegmentChain(forward, first.end, remaining, segments, adjacency)-- parts.push(- traceOrderedSegments([...backward, firstIndex, ...forward], segments, vertices, decimals)- )- }-- return parts.join('')-}--export function vectorNetworkToSVGPaths(- network: VectorNetwork,- decimals: number | null = 2-): string[] {- const { vertices, regions } = network-- if (regions.length === 0) {- const path = unfilledSegmentsToPath(network, decimals)- return path ? [path] : []- }- 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 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))diff --git a/packages/core/src/tools/create/render.ts b/packages/core/src/tools/create/render.tsindex afc2eceeb..227a33b01 100644--- a/packages/core/src/tools/create/render.ts+++ b/packages/core/src/tools/create/render.ts@@ -7,7 +7,7 @@ export const render = defineTool({name: 'render',description:- 'Render JSX to design nodes. Supports inline SVG paths, including open stroked paths: <svg viewBox="0 0 24 24" size={24}><path d="M2 12 L22 12" stroke="#000" fill="none" /></svg>. Use replace_id to replace a placeholder while preserving its position.',+ 'Render JSX to design nodes. Draw a shape of your own as one layer with <Vector d="M2 12 L22 12" stroke="#000" />, styled like any layer; inline <svg> is for artwork copied from elsewhere and draws its shapes, without its text. Use replace_id to replace a placeholder while preserving its position.',execution: { kind: 'async', mutation: 'document' },input: v.strictObject({replace_id: v.optional(diff --git a/packages/core/tests/design-jsx/vectors.test.ts b/packages/core/tests/design-jsx/vectors.test.tsnew file mode 100644index 000000000..fc71dec67--- /dev/null+++ b/packages/core/tests/design-jsx/vectors.test.ts@@ -0,0 +1,137 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'+import { pick } from 'es-toolkit'++import { renderJSX } from '@open-pencil/core/design-jsx'+import { sceneNodeToJSX } from '@open-pencil/design-jsx'+import { SceneGraph } from '@open-pencil/scene-graph'+import { vectorNetworkPaths } from '@open-pencil/scene-graph/vector-network'++async function render(jsx: string) {+ const graph = new SceneGraph()+ const [node] = await renderJSX(graph, jsx)+ return getNodeOrThrow(graph, node.id)+}++describe('<Vector> paths', () => {+ test('draw a d as SVG does, the layer taking its bounds', async () => {+ const node = await render('<Vector x={10} y={20} d="M4 2 L20 2 L12 18 Z" bg="#000" />')+ expect(node).toMatchObject({ x: 14, y: 22, width: 16, height: 16 })+ expect(vectorNetworkPaths(expectDefined(node.vectorNetwork, 'network'))).toEqual([+ { windingRule: 'NONZERO', data: 'M0 0L16 0L8 16L0 0Z' }+ ])+ })++ test('take relative commands and arcs in d, and fillRule for holes', async () => {+ const node = await render(+ '<Vector d="m0 0 h20 v20 h-20 z M5 5 a5 5 0 1 0 10 0 a5 5 0 1 0 -10 0 z" fillRule="evenodd" />'+ )+ expect(node).toMatchObject({ width: 20, height: 20 })+ expect(node.vectorNetwork?.regions.map((region) => region.windingRule)).toEqual(['EVENODD'])+ })++ test('size a curve by where it reaches, not by its control points', async () => {+ const node = await render('<Vector d="M0 0 C0 40 40 40 40 0" stroke="#000" />')+ expect(node.width).toBe(40)+ expect(node.height).toBe(30)+ })++ test('take paths as Figma writes them, an open path with NONE', async () => {+ const node = await render(+ `<Vector paths={[{ windingRule: 'EVENODD', data: 'M0 0 L10 0 L10 10 Z' }, { windingRule: 'NONE', data: 'M0 20 L10 20' }]} />`+ )+ expect(vectorNetworkPaths(expectDefined(node.vectorNetwork, 'network'))).toEqual([+ { windingRule: 'EVENODD', data: 'M0 0L10 0L10 10L0 0Z' },+ { windingRule: 'NONE', data: 'M0 20L10 20' }+ ])+ })++ test('draw in the box they are given as written, as an icon in its view box', async () => {+ const node = await render('<Vector w={24} h={24} d="M4 4 L20 4 L20 20 Z" />')+ expect(node).toMatchObject({ x: 0, y: 0, width: 24, height: 24 })+ expect(node.vectorNetwork?.vertices).toEqual([+ { x: 4, y: 4 },+ { x: 20, y: 4 },+ { x: 20, y: 20 }+ ])+ })++ test('keep a size bound to a variable, drawing the path in that box', async () => {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Sizes')+ graph.createVariable('Icon', 'FLOAT', collection.id, 32)+ const [created] = await renderJSX(+ graph,+ '<Vector w={designVar("Icon")} h={designVar("Icon")} d="M4 4 L20 4 L20 20 Z" />'+ )+ const node = getNodeOrThrow(graph, created.id)+ expect(node).toMatchObject({ x: 0, y: 0, width: 32, height: 32 })+ expect(node.vectorNetwork?.vertices[0]).toEqual({ x: 4, y: 4 })+ })++ test('take their size from style as from w and h', async () => {+ const node = await render(+ '<Vector style={{ width: 24, height: 24 }} d="M4 4 L20 4 L20 20 Z" />'+ )+ expect(node).toMatchObject({ x: 0, y: 0, width: 24, height: 24 })+ expect(node.vectorNetwork?.vertices[0]).toEqual({ x: 4, y: 4 })+ })++ test('fill an open path as if closed only when nothing strokes it', async () => {+ const filled = await render('<Vector d="M0 0 L20 0 L20 20" bg="#000" />')+ expect(vectorNetworkPaths(expectDefined(filled.vectorNetwork, 'network'))).toEqual([+ { windingRule: 'NONZERO', data: 'M0 0L20 0L20 20' }+ ])+ const stroked = await render('<Vector d="M0 0 L20 0 L20 20" bg="#000" stroke="#000" />')+ expect(vectorNetworkPaths(expectDefined(stroked.vectorNetwork, 'network'))).toEqual([+ { windingRule: 'NONE', data: 'M0 0L20 0L20 20' }+ ])+ })++ test('say what is wrong with a path', async () => {+ await expect(render('<Vector d="M0 0 L" />')).rejects.toThrow('Invalid <Vector> `d`')+ await expect(+ render(`<Vector paths={[{ windingRule: 'NONZERO', data: 'M0 0 h10 v10 Z' }]} />`)+ ).rejects.toThrow('Invalid <Vector> paths[0]')+ await expect(render('<Vector d="M0 0 L1 1" paths={[]} />')).rejects.toThrow('not both')+ })+})++describe('<Vector> export', () => {+ const pathsOf = (node: { vectorNetwork: Parameters<typeof vectorNetworkPaths>[0] | null }) =>+ vectorNetworkPaths(expectDefined(node.vectorNetwork, 'network'))++ test('writes the paths a vector draws, which render back to the same layer', async () => {+ const graph = new SceneGraph()+ const [source] = await renderJSX(+ graph,+ `<Vector x={8} y={4} w={24} h={24} bg="#E22" paths={[{ windingRule: 'EVENODD', data: 'M4 4L20 4L20 20L4 20L4 4ZM8 8L16 8L16 16L8 16L8 8Z' }, { windingRule: 'NONE', data: 'M0 22L24 22' }]} />`+ )+ const jsx = sceneNodeToJSX(source.id, graph)+ expect(jsx).toContain('paths={[')+ const [result] = await renderJSX(graph, jsx)+ const before = getNodeOrThrow(graph, source.id)+ const after = getNodeOrThrow(graph, result.id)+ expect(pick(after, ['x', 'y', 'width', 'height'])).toEqual(+ pick(before, ['x', 'y', 'width', 'height'])+ )+ expect(pathsOf(after)).toEqual(pathsOf(before))+ expect(sceneNodeToJSX(result.id, graph)).toBe(jsx)+ })++ test('keeps inline SVG artwork drawing after a round trip', async () => {+ const graph = new SceneGraph()+ const [source] = await renderJSX(+ graph,+ '<svg viewBox="0 0 24 24" size={24}><path d="M12 2 L22 22 L2 22 Z" fill="#000" /></svg>'+ )+ const [result] = await renderJSX(graph, sceneNodeToJSX(source.id, graph))+ const vectors = (id: string) => graph.getChildren(id).filter((child) => child.type === 'VECTOR')+ expect(vectors(result.id).map(pathsOf)).toEqual(vectors(source.id).map(pathsOf))+ expect(vectors(result.id)).toHaveLength(1)+ expect(pathsOf(vectors(result.id)[0])).toEqual([+ { windingRule: 'NONZERO', data: 'M12 2L22 22L2 22L12 2Z' }+ ])+ })+})diff --git a/packages/core/tests/io/formats/svg/paths.test.ts b/packages/core/tests/io/formats/svg/paths.test.tsindex cbc6daaa7..384499cfe 100644--- a/packages/core/tests/io/formats/svg/paths.test.ts+++ b/packages/core/tests/io/formats/svg/paths.test.ts@@ -1,9 +1,9 @@import { expect, test } from 'bun:test'-import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'import type { NodeType, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'+import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'-import { nodeOutlinePath, vectorNetworkToSVGPaths } from '#core/io/formats/svg/paths'+import { nodeOutlinePath } from '#core/io/formats/svg/paths'const corner = { x: 0, y: 0 }const line = (start: number, end: number) => ({@@ -26,16 +26,6 @@ const network: VectorNetwork = {regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]}-test('segments outside every region draw as open paths after the regions', () => {- expect(vectorNetworkToSVGPaths(network)).toEqual(['M19 20L9 12L19 4L19 20Z', 'M5 19L5 5'])-})--test('a network with regions only draws the regions', () => {- expect(vectorNetworkToSVGPaths({ ...network, segments: network.segments.slice(0, 3) })).toEqual([- 'M19 20L9 12L19 4L19 20Z'- ])-})-const shape = (type: NodeType, overrides: Partial<SceneNode> = {}) =>createDefaultNode(() => 'shape', type, { width: 100, height: 50, ...overrides })diff --git a/packages/design-jsx/src/components.ts b/packages/design-jsx/src/components.tsindex 13fd925d9..e2c364cbd 100644--- a/packages/design-jsx/src/components.ts+++ b/packages/design-jsx/src/components.ts@@ -2,6 +2,7 @@ import {node,type BaseProps,type EllipseProps,+ type VectorProps,type ComponentProps,type InstanceProps,type ParagraphProps,@@ -61,7 +62,7 @@ export function Polygon(return withChildren('polygon', props, children)}-export function Vector(props: BaseProps, ...children: Child[]): TreeNode {+export function Vector(props: BaseProps & VectorProps, ...children: Child[]): TreeNode {return withChildren('vector', props, children)}diff --git a/packages/design-jsx/src/definitions.ts b/packages/design-jsx/src/definitions.tsindex d17a709d4..a52a6e36b 100644--- a/packages/design-jsx/src/definitions.ts+++ b/packages/design-jsx/src/definitions.ts@@ -184,6 +184,9 @@ export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = ['innerRadius','startAngle','endAngle',+ 'd',+ 'fillRule',+ 'paths','label','style','bind',diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.tsindex f35bffc9a..3ac86bd7a 100644--- a/packages/design-jsx/src/export/props.ts+++ b/packages/design-jsx/src/export/props.ts@@ -5,6 +5,7 @@ import { DEFAULT_FONT_FAMILY } from '@open-pencil/scene-graph/constants'import { layoutSizing } from '@open-pencil/scene-graph/layout'import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'+import { vectorNetworkPaths } from '@open-pencil/scene-graph/vector-network'import { BLEND_MODE, TEXT_ALIGN, TEXT_ALIGN_VERTICAL, TEXT_CASE, TEXT_DECORATION } from '../enums'import { textLengthJSX } from '../overrides/text'@@ -329,6 +330,11 @@ function collectShapeNodeProps(node: SceneNode, props: JSXProp[]): void {if (node.type === 'POLYGON' && node.pointCount !== 3) {props.push(['points', node.pointCount])}+ if (node.type === 'VECTOR' && node.vectorNetwork) {+ // Figma's own form of a vector's geometry, which <Vector> reads back as written.+ const paths = vectorNetworkPaths(node.vectorNetwork)+ if (paths.length > 0) props.push(['paths', paths.map((path) => ({ ...path }))])+ }}/**diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.tsindex 7af4a3604..ff0a03bce 100644--- a/packages/design-jsx/src/index.ts+++ b/packages/design-jsx/src/index.ts@@ -42,6 +42,7 @@ export {type TreeNode,type BaseProps,type EllipseProps,+ type VectorProps,type ComponentProps,type InstanceProps,type TextProps,diff --git a/packages/design-jsx/src/overrides/vector.ts b/packages/design-jsx/src/overrides/vector.tsnew file mode 100644index 000000000..91f8f8132--- /dev/null+++ b/packages/design-jsx/src/overrides/vector.ts@@ -0,0 +1,125 @@+import * as v from 'valibot'++import type { SceneGraph, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'+import { parsePluginVectorPath, parseSVGPathData } from '@open-pencil/scene-graph/parse-path'+import type { Rect } from '@open-pencil/scene-graph/primitives'+import {+ mergeVectorNetworks,+ transformVectorNetwork+} from '@open-pencil/scene-graph/vector-network'++import { designJSXProp } from '../definitions'+import { normalizeStyleProps } from '../props-overrides'+import { parseScriptInput } from '../schema'++const FILL_RULES = { nonzero: 'NONZERO', evenodd: 'EVENODD' } as const++const vectorPropsSchema = v.pipe(+ v.object({+ d: v.optional(v.pipe(v.string(), v.trim(), v.nonEmpty())),+ fillRule: v.optional(v.picklist(['nonzero', 'evenodd'])),+ paths: v.optional(+ v.array(+ v.object({+ windingRule: v.picklist(['NONZERO', 'EVENODD', 'NONE']),+ data: v.string()+ })+ )+ )+ }),+ v.check((props) => !(props.d && props.paths), 'Expected `d` or `paths`, not both')+)++function parsedNetwork(result: ReturnType<typeof parseSVGPathData>, which: string): VectorNetwork {+ if (!result.ok) throw new Error(`Invalid <Vector> ${which}: ${result.error}`)+ return result.network+}++/**+ * The vector network a `<Vector>`'s `d` or `paths` draws, in the coordinates they are written+ * in, or null when it has neither. `d` reads as SVG does, its open subpaths filled only when+ * `fillsOpenSubpaths`; `paths` as Figma's `vectorPaths`.+ */+function vectorNetworkProp(+ props: Record<string, unknown>,+ fillsOpenSubpaths: boolean+): VectorNetwork | null {+ const parsed = parseScriptInput('Invalid <Vector> props', vectorPropsSchema, props)+ if (parsed.d) {+ const windingRule = FILL_RULES[parsed.fillRule ?? 'nonzero']+ return parsedNetwork(+ parseSVGPathData(parsed.d, windingRule, { includeOpenRegions: fillsOpenSubpaths }),+ '`d`'+ )+ }+ if (!parsed.paths) return null+ return mergeVectorNetworks(+ parsed.paths.map(({ windingRule, data }, index) =>+ parsedNetwork(parsePluginVectorPath(data, windingRule), `paths[${index}]`)+ )+ )+}++/** The size a `<Vector>` is given, on the axes its props size. */+interface VectorSize {+ width?: number+ height?: number+}++/**+ * The size of `node` on the axes `props` set, by `w`/`width` and `h`/`height`, however they set+ * them: a number, a variable, or a layout value. The layer already holds what they resolve to.+ */+function vectorSize(props: Record<string, unknown>, node: SceneNode): VectorSize {+ const sized = normalizeStyleProps(props)+ return {+ width: designJSXProp(sized, 'w') === undefined ? undefined : node.width,+ height: designJSXProp(sized, 'h') === undefined ? undefined : node.height+ }+}++/**+ * The fields that place a vector network in its layer. On an axis the author sized, the path is+ * drawn in the layer's own box as written, as an SVG icon is in its view box. On an axis left+ * unsized, the layer takes the network's extent and moves to where it starts, as Figma's+ * `vectorPaths` setter does.+ */+function vectorGeometry(+ network: VectorNetwork,+ bounds: Rect,+ size: VectorSize,+ position: Pick<SceneNode, 'x' | 'y'>+): Partial<SceneNode> {+ const dx = size.width === undefined ? bounds.x : 0+ const dy = size.height === undefined ? bounds.y : 0+ return {+ x: position.x + dx,+ y: position.y + dy,+ width: size.width ?? bounds.width,+ height: size.height ?? bounds.height,+ vectorNetwork: transformVectorNetwork([1, 0, -dx, 0, 1, -dy, 0, 0, 1], network)+ }+}++/**+ * A `<Vector>`'s `d` or `paths` as its vector network, the layer sized to it. `vectorBounds`+ * measures the network, curves included, which the engine provides.+ */+export function placeVectorPaths(+ graph: SceneGraph,+ node: SceneNode,+ props: Record<string, unknown>,+ vectorBounds: (network: VectorNetwork) => Rect+): void {+ if (node.type !== 'VECTOR') return+ // A filled vector strokes its regions, which close, so an open subpath becomes one only when+ // nothing strokes it, as SVG import decides.+ const fillsOpenSubpaths =+ node.fills.some((fill) => fill.visible) && !node.strokes.some((stroke) => stroke.visible)+ const network = vectorNetworkProp(props, fillsOpenSubpaths)+ if (!network) return+ graph.updateNode(+ node.id,+ vectorGeometry(network, vectorBounds(network), vectorSize(props, node), node)+ )+}diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/props-overrides.tsindex 08d9ba0ad..cd3a1c2d0 100644--- a/packages/design-jsx/src/props-overrides.ts+++ b/packages/design-jsx/src/props-overrides.ts@@ -44,7 +44,8 @@ function numberFromPx(value: unknown): number | undefined {return typeof value === 'string' ? (parseCSSNumber(value) ?? undefined) : undefined}-function normalizeStyleProps(props: Record<string, unknown>): Record<string, unknown> {+/** `props` with the sizes and styles its `style` object gives, where the props leave them unset. */+export function normalizeStyleProps(props: Record<string, unknown>): Record<string, unknown> {const style = props.styleif (style === null || typeof style !== 'object' || Array.isArray(style)) return propsdiff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex b76634c2b..27c914aeb 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -26,6 +26,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `fontFeatures` turns OpenType features on or off by tag (`fontFeatures={{ tnum: true, liga: false }}`), `fontVariations` sets variable-font axes by tag (`fontVariations={{ wght: 650 }}`), and `lang` names the text's language (`lang="de"`) for shaping and font fallback. A variable font's optical size follows the font size unless `fontOpticalSizing="none"`, as in CSS; only then does an `opsz` in `fontVariations` apply. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, `fontFeatures`, `fontVariations`, `lang`, and `textCase`; a span's `fontFeatures` and `fontVariations` replace the text's rather than adding to them, and `fontOpticalSizing` is set on the `Text` for all of it. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.+- Pick artwork by where it comes from. A known icon is an `Icon` by its Iconify name. A shape you draw yourself is a `Vector` with its path in SVG syntax, `<Vector d="M11 2L4 11h5l-1 7 7-9h-5z" bg={designVar(…)} />`: one layer, styled with the same props as any other, so its fills can use variables, stack, and take `strokeAlign` and `effects`. `fillRule="evenodd"` cuts holes. An open path with a `stroke` stays open, a line; with only a `bg` it fills as if closed. Given `w` and `h`, the path is drawn in that box as written, as an icon is in its view box; without them the layer fits the path. `paths` takes several paths as export writes them, each `{ windingRule, data }` with `NONZERO`, `EVENODD`, or `NONE` for an open path: `paths={[{ windingRule: "EVENODD", data: "M0 0L10 0L10 10Z" }]}`. Inline `<svg>` is for artwork copied from elsewhere: it draws the SVG's shapes, a frame with a layer per shape in the SVG's own colours, and leaves out its text, so do not use it for a shape you will style or bind, nor for text.- `Sticky` makes a FigJam sticky note whose text is its body: `<Sticky color="yellow" author="Ada">Ship it</Sticky>`. `color` takes a FigJam palette name (`white`, `gray`, `red`, `orange`, `yellow`, `green`, `teal`, `blue`, `violet`, `pink`) or any colour, `author` signs it (`authorVisible={false}` hides the line), `wide` makes it 416 wide instead of 240, `textSize` is `small`, `medium`, `large`, `extraLarge`, or `huge`, `typeface` is `simple`, `bookish`, `technical`, or `scribbled`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows taller to fit its label, never wider, so a word too long for it breaks. `truncate` keeps its height and cuts the label off with "…" instead, as FigJam does once a shape's height is set. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.tsindex 97b65fc72..0a3a82aa3 100644--- a/packages/design-jsx/src/renderer.ts+++ b/packages/design-jsx/src/renderer.ts@@ -16,6 +16,7 @@ import {} from './component-properties'import { CONNECTOR_ELEMENT, resolveConnectorEnds } from './connectors'import { elementNodeType, elementOwnLayer, type OwnLayerRenderer } from './elements'+import { placeVectorPaths } from './overrides/vector'import { applySizeOverrides, propsToOverrides, shapeOverrides } from './props-overrides'import { LayerRefs } from './refs'import { prepareScalarBindings } from './scalar-bindings'@@ -566,6 +567,7 @@ async function renderNodeContent<Artwork>(const { overrides, bindings } = elementOverrides(graph, nodeType, element, elementParentId)const created = graph.createNode(nodeType, elementParentId, overrides)applyBindings(graph, created.id, bindings)+ placeVectorPaths(graph, created, element.props, (network) => services.vectorBounds(network))return created},instance: (element, elementParentId) => renderInstanceNode(graph, element, elementParentId),@@ -581,6 +583,7 @@ async function renderNodeContent<Artwork>(const { overrides, bindings } = elementOverrides(graph, nodeType, tree, parentId)const node = graph.createNode(nodeType, parentId, overrides)applyBindings(graph, node.id, bindings)+ placeVectorPaths(graph, node, tree.props, (network) => services.vectorBounds(network))for (const child of tree.children) {if (typeof child === 'string' || (node.type === 'TEXT' && isTextContent(child))) continuediff --git a/packages/design-jsx/src/services.ts b/packages/design-jsx/src/services.tsindex dd88e09b2..a98f1bd7c 100644--- a/packages/design-jsx/src/services.ts+++ b/packages/design-jsx/src/services.ts@@ -1,5 +1,5 @@-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import type { Color } from '@open-pencil/scene-graph/primitives'+import type { SceneGraph, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'+import type { Color, Rect } from '@open-pencil/scene-graph/primitives'import type { TreeNode } from './tree'@@ -31,4 +31,6 @@ export interface DesignJSXServices<Artwork> {createArtwork(graph: SceneGraph, artwork: Artwork, placement: ArtworkPlacement): SceneNode/** Size and lay out the rendered roots once they are in place. */layout(graph: SceneGraph, rootIds: readonly string[]): void+ /** The tight bounds of a vector network, its curves included, which size a `<Vector>`. */+ vectorBounds(network: VectorNetwork): Rect}diff --git a/packages/design-jsx/src/tree.ts b/packages/design-jsx/src/tree.tsindex 3c2daa3b9..cb1c168db 100644--- a/packages/design-jsx/src/tree.ts+++ b/packages/design-jsx/src/tree.ts@@ -221,6 +221,14 @@ export type EllipseProps = {/** The hole as a share of the ellipse, from 0 (none) to 1. */innerRadius?: number}+/** A `<Vector>`'s path, in SVG's syntax as `d` or as Figma's `vectorPaths`. */+export type VectorProps = {+ /** Path data as SVG writes it, filled under `fillRule`; an open subpath fills only without a stroke. */+ d?: string+ fillRule?: 'nonzero' | 'evenodd'+ /** Paths with their own winding rules, as export writes them; `NONE` draws an open path. */+ paths?: Array<{ windingRule: 'NONZERO' | 'EVENODD' | 'NONE'; data: string }>+}export type TextProps = BaseProps/** A `<Span>`'s props: the character styles of `<Text>`, under the same names. */diff --git a/packages/design-jsx/tests/elements.test.ts b/packages/design-jsx/tests/elements.test.tsindex d7f289c03..e11ba72e8 100644--- a/packages/design-jsx/tests/elements.test.ts+++ b/packages/design-jsx/tests/elements.test.ts@@ -20,6 +20,9 @@ const renderer = createDesignJSXRenderer<never>({},layout: () => {// Element types do not depend on layout.+ },+ vectorBounds: () => {+ throw new Error('No vectors in these tests')}})diff --git a/packages/design-jsx/tests/enums.test.ts b/packages/design-jsx/tests/enums.test.tsindex 5d7737c25..721d2f5ae 100644--- a/packages/design-jsx/tests/enums.test.ts+++ b/packages/design-jsx/tests/enums.test.ts@@ -29,6 +29,9 @@ const renderer = createDesignJSXRenderer<never>({},layout: () => {// These props do not depend on layout.+ },+ vectorBounds: () => {+ throw new Error('No vectors in these tests')}})diff --git a/packages/design-jsx/tests/text-content.test.ts b/packages/design-jsx/tests/text-content.test.tsindex facb393bd..910bc3226 100644--- a/packages/design-jsx/tests/text-content.test.ts+++ b/packages/design-jsx/tests/text-content.test.ts@@ -14,6 +14,9 @@ const renderer = createDesignJSXRenderer<never>({},layout: () => {// Text content does not depend on layout.+ },+ vectorBounds: () => {+ throw new Error('No vectors in these tests')}})diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex 90e010765..268b615f2 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -28,6 +28,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `fontFeatures` turns OpenType features on or off by tag (`fontFeatures={{ tnum: true, liga: false }}`), `fontVariations` sets variable-font axes by tag (`fontVariations={{ wght: 650 }}`), and `lang` names the text's language (`lang="de"`) for shaping and font fallback. A variable font's optical size follows the font size unless `fontOpticalSizing="none"`, as in CSS; only then does an `opsz` in `fontVariations` apply. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, `fontFeatures`, `fontVariations`, `lang`, and `textCase`; a span's `fontFeatures` and `fontVariations` replace the text's rather than adding to them, and `fontOpticalSizing` is set on the `Text` for all of it. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.+- Pick artwork by where it comes from. A known icon is an `Icon` by its Iconify name. A shape you draw yourself is a `Vector` with its path in SVG syntax, `<Vector d="M11 2L4 11h5l-1 7 7-9h-5z" bg={designVar(…)} />`: one layer, styled with the same props as any other, so its fills can use variables, stack, and take `strokeAlign` and `effects`. `fillRule="evenodd"` cuts holes. An open path with a `stroke` stays open, a line; with only a `bg` it fills as if closed. Given `w` and `h`, the path is drawn in that box as written, as an icon is in its view box; without them the layer fits the path. `paths` takes several paths as export writes them, each `{ windingRule, data }` with `NONZERO`, `EVENODD`, or `NONE` for an open path: `paths={[{ windingRule: "EVENODD", data: "M0 0L10 0L10 10Z" }]}`. Inline `<svg>` is for artwork copied from elsewhere: it draws the SVG's shapes, a frame with a layer per shape in the SVG's own colours, and leaves out its text, so do not use it for a shape you will style or bind, nor for text.- `Sticky` makes a FigJam sticky note whose text is its body: `<Sticky color="yellow" author="Ada">Ship it</Sticky>`. `color` takes a FigJam palette name (`white`, `gray`, `red`, `orange`, `yellow`, `green`, `teal`, `blue`, `violet`, `pink`) or any colour, `author` signs it (`authorVisible={false}` hides the line), `wide` makes it 416 wide instead of 240, `textSize` is `small`, `medium`, `large`, `extraLarge`, or `huge`, `typeface` is `simple`, `bookish`, `technical`, or `scribbled`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows taller to fit its label, never wider, so a word too long for it breaks. `truncate` keeps its height and cuts the label off with "…" instead, as FigJam does once a shape's height is set. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.@@ -132,4 +133,4 @@ Generated from the renderer metadata. This inventory lists accepted names, not a**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `defineVars`, `defineMode`, `designVar`, `designMode`, `property`, `ref`.-**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of file+**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/packages/scene-graph/src/parse-path.ts b/packages/scene-graph/src/parse-path.tsindex 0e0bc36c0..483192cb2 100644--- a/packages/scene-graph/src/parse-path.ts+++ b/packages/scene-graph/src/parse-path.ts@@ -38,6 +38,19 @@ export function parseSVGPath(return parsed.ok ? parsed.network : { vertices: [], segments: [], regions: [] }}+/**+ * Parse a `d` with any command SVG has, its closed subpaths filled under `windingRule` and, with+ * `includeOpenRegions`, its open ones too, as SVG fills them. Unlike `parseSVGPath`, a path that+ * does not parse says why.+ */+export function parseSVGPathData(+ d: string,+ windingRule: WindingRule,+ options: { includeOpenRegions: boolean }+): SVGPathParseResult {+ return parsePath(d, windingRule, { ...options, strictCommands: false })+}+/** Parse the strict absolute command subset accepted by Figma's VectorPath API. */export function parsePluginVectorPath(d: string,diff --git a/packages/scene-graph/src/vector-network.ts b/packages/scene-graph/src/vector-network.tsindex c3ee18631..707ae1404 100644--- a/packages/scene-graph/src/vector-network.ts+++ b/packages/scene-graph/src/vector-network.ts@@ -1,8 +1,9 @@import { isEqual } from 'es-toolkit/predicate'import type { Mat3 } from './matrix'+import type { VectorPathWindingRule } from './parse-path'import type { Vector } from './primitives'-import type { VectorNetwork, VectorSegment } from './types'+import type { VectorNetwork, VectorSegment, VectorVertex } from './types'/** Concatenate vector networks while preserving independent geometry. */export function mergeVectorNetworks(networks: readonly VectorNetwork[]): VectorNetwork {@@ -291,3 +292,198 @@ export function normalizeVectorNetwork(vn: NormalizableVectorNetwork): VectorNetregions: vn.regions ?? []}}++function coordinate(value: number, decimals: number | null): number {+ if (decimals === null) return value+ const factor = 10 ** decimals+ return Math.round(value * factor) / factor+}++function segmentToSVG(+ seg: VectorSegment,+ vertices: VectorVertex[],+ forward: boolean,+ decimals: number | null+): string {+ const start = forward ? vertices[seg.start] : vertices[seg.end]+ const end = forward ? vertices[seg.end] : vertices[seg.start]+ const ts = forward ? seg.tangentStart : { x: -seg.tangentEnd.x, y: -seg.tangentEnd.y }+ const te = forward ? seg.tangentEnd : { x: -seg.tangentStart.x, y: -seg.tangentStart.y }++ const isStraight =+ Math.abs(ts.x) < 0.001 &&+ Math.abs(ts.y) < 0.001 &&+ Math.abs(te.x) < 0.001 &&+ Math.abs(te.y) < 0.001++ if (isStraight) {+ return `L${coordinate(end.x, decimals)} ${coordinate(end.y, decimals)}`+ }++ const cp1x = coordinate(start.x + ts.x, decimals)+ const cp1y = coordinate(start.y + ts.y, decimals)+ const cp2x = coordinate(end.x + te.x, decimals)+ const cp2y = coordinate(end.y + te.y, decimals)+ return `C${cp1x} ${cp1y} ${cp2x} ${cp2y} ${coordinate(end.x, decimals)} ${coordinate(end.y, decimals)}`+}++function traceOrderedSegments(+ segmentIndices: readonly number[],+ segments: VectorSegment[],+ vertices: VectorVertex[],+ decimals: number | null+): string {+ if (segmentIndices.length === 0) return ''+ const first = segments[segmentIndices[0]]+ const second = segmentIndices.length > 1 ? segments[segmentIndices[1]] : null+ // Start at the first segment endpoint that does not connect to the second segment.+ const secondConnectsStart = second?.start === first.start || second?.end === first.start+ const secondConnectsEnd = second?.start === first.end || second?.end === first.end+ const firstForward = !second || secondConnectsEnd || !secondConnectsStart+ const startIndex = firstForward ? first.start : first.end+ let currentIndex = startIndex+ const parts = [+ `M${coordinate(vertices[startIndex].x, decimals)} ${coordinate(vertices[startIndex].y, decimals)}`+ ]++ for (const segmentIndex of segmentIndices) {+ const segment = segments[segmentIndex]+ const isConnected = segment.start === currentIndex || segment.end === currentIndex+ const forward = segment.start === currentIndex || !isConnected+ if (!isConnected) {+ const segmentStart = forward ? segment.start : segment.end+ parts.push(+ `M${coordinate(vertices[segmentStart].x, decimals)} ${coordinate(vertices[segmentStart].y, decimals)}`+ )+ }+ parts.push(segmentToSVG(segment, vertices, forward, decimals))+ currentIndex = forward ? segment.end : segment.start+ }+ if (parts.length === segmentIndices.length + 1 && currentIndex === startIndex) parts.push('Z')+ return parts.join('')+}++type SegmentAdjacency = ReadonlyMap<number, readonly number[]>++function buildSegmentAdjacency(segments: VectorSegment[]): SegmentAdjacency {+ const adjacency = new Map<number, number[]>()+ for (let index = 0; index < segments.length; index++) {+ const segment = segments[index]+ for (const vertexIndex of [segment.start, segment.end]) {+ const incidentSegments = adjacency.get(vertexIndex)+ if (incidentSegments) incidentSegments.push(index)+ else adjacency.set(vertexIndex, [index])+ }+ }+ return adjacency+}++function findConnectedSegment(+ remaining: ReadonlySet<number>,+ adjacency: SegmentAdjacency,+ vertexIndex: number+): number | undefined {+ return adjacency.get(vertexIndex)?.find((index) => remaining.has(index))+}++function extendSegmentChain(+ chain: number[],+ startVertex: number,+ remaining: Set<number>,+ segments: VectorSegment[],+ adjacency: SegmentAdjacency+): void {+ let currentIndex = startVertex+ let nextIndex = findConnectedSegment(remaining, adjacency, currentIndex)+ while (nextIndex !== undefined) {+ chain.push(nextIndex)+ remaining.delete(nextIndex)+ const segment = segments[nextIndex]+ currentIndex = segment.start === currentIndex ? segment.end : segment.start+ nextIndex = findConnectedSegment(remaining, adjacency, currentIndex)+ }+}++function unfilledSegmentsToPath(network: VectorNetwork, decimals: number | null): string {+ const { vertices, segments } = network+ const remaining = new Set(segments.map((_, index) => index))+ const adjacency = buildSegmentAdjacency(segments)+ const parts: string[] = []++ while (remaining.size > 0) {+ const firstIndex = remaining.values().next().value+ if (firstIndex === undefined) break+ remaining.delete(firstIndex)+ const first = segments[firstIndex]++ const backward: number[] = []+ extendSegmentChain(backward, first.start, remaining, segments, adjacency)+ backward.reverse()++ const forward: number[] = []+ extendSegmentChain(forward, first.end, remaining, segments, adjacency)++ parts.push(+ traceOrderedSegments([...backward, firstIndex, ...forward], segments, vertices, decimals)+ )+ }++ return parts.join('')+}++export function vectorNetworkToSVGPaths(+ network: VectorNetwork,+ decimals: number | null = 2+): string[] {+ const { vertices, regions } = network++ if (regions.length === 0) {+ const path = unfilledSegmentsToPath(network, decimals)+ return path ? [path] : []+ }+ 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 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))+}++/** A path of a vector network as Figma's `vectorPaths` gives it. */+export interface VectorPath {+ windingRule: VectorPathWindingRule+ data: string+}++/**+ * A vector network as Figma's `vectorPaths`: each region as a path with its winding rule, then+ * the segments no region encloses as one open path, at full precision.+ */+export function vectorNetworkPaths(network: VectorNetwork): VectorPath[] {+ if (network.segments.length === 0) return []+ const paths: VectorPath[] = regionSVGPaths(network, null).flatMap((data, index) =>+ data ? [{ windingRule: network.regions[index].windingRule, data }] : []+ )+ const open = looseSegments(network)+ if (open.length === 0) return paths+ const data = vectorNetworkToSVGPaths(+ { vertices: network.vertices, segments: open, regions: [] },+ null+ ).join('')+ return data ? [...paths, { windingRule: 'NONE', data }] : paths+}diff --git a/packages/scene-graph/tests/vector-network.test.ts b/packages/scene-graph/tests/vector-network.test.tsindex e709919cb..a46411715 100644--- a/packages/scene-graph/tests/vector-network.test.ts+++ b/packages/scene-graph/tests/vector-network.test.ts@@ -1,7 +1,12 @@import { describe, expect, test } from 'bun:test'import type { VectorNetwork } from '@open-pencil/scene-graph'-import { mergeVectorNetworks } from '@open-pencil/scene-graph/vector-network'+import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'+import {+ mergeVectorNetworks,+ vectorNetworkPaths,+ vectorNetworkToSVGPaths+} from '@open-pencil/scene-graph/vector-network'import { expectDefined } from './helpers/assert'@@ -44,3 +49,318 @@ describe('mergeVectorNetworks', () => {expect(expectDefined(expectDefined(first.regions[0]).loops[0])[0]).toBe(0)})})++describe('vectorNetworkToSVGPaths()', () => {+ test('single straight segment', () => {+ const paths = vectorNetworkToSVGPaths({+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 100 }+ ],+ segments: [+ {+ start: 0,+ end: 1,+ tangentStart: { x: 0, y: 0 },+ tangentEnd: { x: 0, y: 0 }+ }+ ],+ regions: []+ })+ expect(paths).toHaveLength(1)+ expect(paths[0]).toContain('M0 0')+ expect(paths[0]).toContain('L100 100')+ })++ test('curved segment', () => {+ const paths = vectorNetworkToSVGPaths({+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 0 }+ ],+ segments: [+ {+ start: 0,+ end: 1,+ tangentStart: { x: 0, y: 50 },+ tangentEnd: { x: 0, y: 50 }+ }+ ],+ regions: []+ })+ expect(paths).toHaveLength(1)+ expect(paths[0]).toContain('C')+ })++ test('traces arbitrarily ordered open segments as one path', () => {+ const paths = vectorNetworkToSVGPaths({+ vertices: [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 20, y: 0 },+ { x: 30, y: 0 }+ ],+ segments: [+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 2, end: 3, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ })++ expect(paths).toEqual(['M0 0L10 0L20 0L30 0'])+ })++ test('region with loop', () => {+ const paths = vectorNetworkToSVGPaths({+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 0 },+ { x: 50, y: 100 }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 2, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]+ })+ expect(paths).toHaveLength(1)+ expect(paths[0]).toContain('M0 0')+ expect(paths[0]).toContain('Z')+ })++ test('traces non-directional region segments continuously', () => {+ const paths = vectorNetworkToSVGPaths({+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 0 },+ { x: 50, y: 100 }+ ],+ segments: [+ { start: 1, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 0, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]+ })++ expect(paths).toEqual(['M0 0L100 0L50 100L0 0Z'])+ })++ test('starts a new subpath for disconnected region segments', () => {+ const paths = vectorNetworkToSVGPaths({+ vertices: [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 20, y: 0 },+ { x: 30, y: 0 }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 2, end: 3, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1]] }]+ })++ expect(paths).toEqual(['M0 0L10 0M20 0L30 0'])+ })++ test('recognizes closed unfilled segment chains', () => {+ const paths = vectorNetworkToSVGPaths({+ vertices: [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 0, y: 10 }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 2, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ })++ expect(paths).toEqual(['M10 0L0 10L0 0L10 0Z'])+ })++ test('empty network', () => {+ const paths = vectorNetworkToSVGPaths({ vertices: [], segments: [], regions: [] })+ expect(paths).toHaveLength(0)+ })+})++describe('vectorNetworkToSVGPaths() with regions and open segments', () => {+ const corner = { x: 0, y: 0 }+ const line = (start: number, end: number) => ({+ start,+ end,+ tangentStart: corner,+ tangentEnd: corner+ })++ /** A skip-back icon: a filled triangle beside a bar, which no region encloses. */+ const network: VectorNetwork = {+ vertices: [+ { x: 19, y: 20 },+ { x: 9, y: 12 },+ { x: 19, y: 4 },+ { x: 5, y: 19 },+ { x: 5, y: 5 }+ ],+ segments: [line(0, 1), line(1, 2), line(2, 0), line(3, 4)],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]+ }++ test('segments outside every region draw as open paths after the regions', () => {+ expect(vectorNetworkToSVGPaths(network)).toEqual(['M19 20L9 12L19 4L19 20Z', 'M5 19L5 5'])+ })++ test('a network with regions only draws the regions', () => {+ expect(vectorNetworkToSVGPaths({ ...network, segments: network.segments.slice(0, 3) })).toEqual(+ ['M19 20L9 12L19 4L19 20Z']+ )+ })+})++describe('vectorNetworkPaths()', () => {+ const still = { x: 0, y: 0 }+ const segment = (start: number, end: number, tangentStart = still, tangentEnd = still) => ({+ start,+ end,+ tangentStart,+ tangentEnd+ })+ /** A network's segments by their end points, in either direction. */+ const segmentsOf = (network: VectorNetwork) =>+ network.segments+ .map(({ start, end }) =>+ [network.vertices[start], network.vertices[end]]+ .map(({ x, y }) => `${x},${y}`)+ .sort()+ .join(' ')+ )+ .sort()+ /** The paths, and that parsing them back draws every segment once. */+ const traced = (network: VectorNetwork) => {+ const paths = vectorNetworkPaths(network)+ const back = parseSVGPath(paths.map((path) => path.data).join(''), 'NONZERO')+ expect(segmentsOf(back)).toEqual(segmentsOf(network))+ return paths+ }++ test('has no paths for an empty network', () => {+ expect(vectorNetworkPaths({ vertices: [], segments: [], regions: [] })).toEqual([])+ })++ test('keeps full precision', () => {+ const network: VectorNetwork = {+ vertices: [+ { x: 0.123456789, y: 0 },+ { x: 10, y: 1 / 3 }+ ],+ segments: [segment(0, 1)],+ regions: []+ }+ expect(traced(network)).toEqual([+ { windingRule: 'NONE', data: 'M0.123456789 0L10 0.3333333333333333' }+ ])+ })++ test('draws every branch of a vertex three segments meet at', () => {+ const network: VectorNetwork = {+ vertices: [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 20, y: 10 },+ { x: 20, y: -10 }+ ],+ segments: [segment(0, 1), segment(1, 2), segment(1, 3)],+ regions: []+ }+ expect(traced(network)).toEqual([{ windingRule: 'NONE', data: 'M0 0L10 0L20 10M10 0L20 -10' }])+ })++ test('keeps a segment of no length', () => {+ const network: VectorNetwork = {+ vertices: [+ { x: 0, y: 0 },+ { x: 0, y: 0 },+ { x: 10, y: 0 }+ ],+ segments: [segment(0, 1), segment(1, 2)],+ regions: []+ }+ expect(traced(network)).toEqual([{ windingRule: 'NONE', data: 'M0 0L0 0L10 0' }])+ })++ test('follows segments written against the way their loop runs, curves included', () => {+ const loop: VectorNetwork = {+ vertices: [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 10, y: 10 }+ ],+ segments: [segment(0, 1), segment(2, 1), segment(0, 2)],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]+ }+ expect(traced(loop)).toEqual([{ windingRule: 'NONZERO', data: 'M0 0L10 0L10 10L0 0Z' }])+ const curve: VectorNetwork = {+ vertices: [+ { x: 0, y: 0 },+ { x: 10, y: 0 }+ ],+ segments: [segment(1, 0, { x: 0, y: 5 }, { x: 0, y: 5 })],+ regions: []+ }+ expect(traced(curve)).toEqual([{ windingRule: 'NONE', data: 'M10 0C10 5 0 5 0 0' }])+ })++ test('closes each loop of a region, loops that share a vertex too', () => {+ const network: VectorNetwork = {+ vertices: [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 5, y: 5 },+ { x: 0, y: 10 },+ { x: 10, y: 10 }+ ],+ segments: [+ segment(0, 1),+ segment(1, 2),+ segment(2, 0),+ segment(2, 3),+ segment(3, 4),+ segment(4, 2)+ ],+ regions: [+ {+ windingRule: 'EVENODD',+ loops: [+ [0, 1, 2],+ [3, 4, 5]+ ]+ }+ ]+ }+ expect(traced(network)).toEqual([+ { windingRule: 'EVENODD', data: 'M0 0L10 0L5 5L0 0ZM5 5L0 10L10 10L5 5Z' }+ ])+ })++ test('skips a region with no loops and keeps the winding rule of the next', () => {+ const network: VectorNetwork = {+ vertices: [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 10, y: 10 }+ ],+ segments: [segment(0, 1), segment(1, 2), segment(2, 0)],+ regions: [+ { windingRule: 'NONZERO', loops: [] },+ { windingRule: 'EVENODD', loops: [[0, 1, 2]] }+ ]+ }+ expect(traced(network)).toEqual([{ windingRule: 'EVENODD', data: 'M0 0L10 0L10 10L0 0Z' }])+ })+})diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex 90e010765..268b615f2 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -28,6 +28,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `fontFeatures` turns OpenType features on or off by tag (`fontFeatures={{ tnum: true, liga: false }}`), `fontVariations` sets variable-font axes by tag (`fontVariations={{ wght: 650 }}`), and `lang` names the text's language (`lang="de"`) for shaping and font fallback. A variable font's optical size follows the font size unless `fontOpticalSizing="none"`, as in CSS; only then does an `opsz` in `fontVariations` apply. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, `fontFeatures`, `fontVariations`, `lang`, and `textCase`; a span's `fontFeatures` and `fontVariations` replace the text's rather than adding to them, and `fontOpticalSizing` is set on the `Text` for all of it. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.+- Pick artwork by where it comes from. A known icon is an `Icon` by its Iconify name. A shape you draw yourself is a `Vector` with its path in SVG syntax, `<Vector d="M11 2L4 11h5l-1 7 7-9h-5z" bg={designVar(…)} />`: one layer, styled with the same props as any other, so its fills can use variables, stack, and take `strokeAlign` and `effects`. `fillRule="evenodd"` cuts holes. An open path with a `stroke` stays open, a line; with only a `bg` it fills as if closed. Given `w` and `h`, the path is drawn in that box as written, as an icon is in its view box; without them the layer fits the path. `paths` takes several paths as export writes them, each `{ windingRule, data }` with `NONZERO`, `EVENODD`, or `NONE` for an open path: `paths={[{ windingRule: "EVENODD", data: "M0 0L10 0L10 10Z" }]}`. Inline `<svg>` is for artwork copied from elsewhere: it draws the SVG's shapes, a frame with a layer per shape in the SVG's own colours, and leaves out its text, so do not use it for a shape you will style or bind, nor for text.- `Sticky` makes a FigJam sticky note whose text is its body: `<Sticky color="yellow" author="Ada">Ship it</Sticky>`. `color` takes a FigJam palette name (`white`, `gray`, `red`, `orange`, `yellow`, `green`, `teal`, `blue`, `violet`, `pink`) or any colour, `author` signs it (`authorVisible={false}` hides the line), `wide` makes it 416 wide instead of 240, `textSize` is `small`, `medium`, `large`, `extraLarge`, or `huge`, `typeface` is `simple`, `bookish`, `technical`, or `scribbled`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows taller to fit its label, never wider, so a word too long for it breaks. `truncate` keeps its height and cuts the label off with "…" instead, as FigJam does once a shape's height is set. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.@@ -132,4 +133,4 @@ Generated from the renderer metadata. This inventory lists accepted names, not a**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `defineVars`, `defineMode`, `designVar`, `designMode`, `property`, `ref`.-**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of file+**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/tests/engine/io/svg/export/paths.test.ts b/tests/engine/io/svg/export/paths.test.tsindex 5f3a954b7..d1e6c3300 100644--- a/tests/engine/io/svg/export/paths.test.ts+++ b/tests/engine/io/svg/export/paths.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { geometryBlobToSVGPath, vectorNetworkToSVGPaths } from '@open-pencil/core/io/formats/svg'+import { geometryBlobToSVGPath } from '@open-pencil/core/io/formats/svg'// --- geometryBlobToSVGPath tests ---@@ -63,145 +63,3 @@ describe('geometryBlobToSVGPath()', () => {expect(result).toContain('Z')})})--// --- vectorNetworkToSVGPaths tests -----describe('vectorNetworkToSVGPaths()', () => {- test('single straight segment', () => {- const paths = vectorNetworkToSVGPaths({- vertices: [- { x: 0, y: 0 },- { x: 100, y: 100 }- ],- segments: [- {- start: 0,- end: 1,- tangentStart: { x: 0, y: 0 },- tangentEnd: { x: 0, y: 0 }- }- ],- regions: []- })- expect(paths).toHaveLength(1)- expect(paths[0]).toContain('M0 0')- expect(paths[0]).toContain('L100 100')- })-- test('curved segment', () => {- const paths = vectorNetworkToSVGPaths({- vertices: [- { x: 0, y: 0 },- { x: 100, y: 0 }- ],- segments: [- {- start: 0,- end: 1,- tangentStart: { x: 0, y: 50 },- tangentEnd: { x: 0, y: 50 }- }- ],- regions: []- })- expect(paths).toHaveLength(1)- expect(paths[0]).toContain('C')- })-- test('traces arbitrarily ordered open segments as one path', () => {- const paths = vectorNetworkToSVGPaths({- vertices: [- { x: 0, y: 0 },- { x: 10, y: 0 },- { x: 20, y: 0 },- { x: 30, y: 0 }- ],- segments: [- { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 2, end: 3, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }- ],- regions: []- })-- expect(paths).toEqual(['M0 0L10 0L20 0L30 0'])- })-- test('region with loop', () => {- const paths = vectorNetworkToSVGPaths({- vertices: [- { x: 0, y: 0 },- { x: 100, y: 0 },- { x: 50, y: 100 }- ],- segments: [- { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 2, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }- ],- regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]- })- expect(paths).toHaveLength(1)- expect(paths[0]).toContain('M0 0')- expect(paths[0]).toContain('Z')- })-- test('traces non-directional region segments continuously', () => {- const paths = vectorNetworkToSVGPaths({- vertices: [- { x: 0, y: 0 },- { x: 100, y: 0 },- { x: 50, y: 100 }- ],- segments: [- { start: 1, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 0, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }- ],- regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]- })-- expect(paths).toEqual(['M0 0L100 0L50 100L0 0Z'])- })-- test('starts a new subpath for disconnected region segments', () => {- const paths = vectorNetworkToSVGPaths({- vertices: [- { x: 0, y: 0 },- { x: 10, y: 0 },- { x: 20, y: 0 },- { x: 30, y: 0 }- ],- segments: [- { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 2, end: 3, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }- ],- regions: [{ windingRule: 'NONZERO', loops: [[0, 1]] }]- })-- expect(paths).toEqual(['M0 0L10 0M20 0L30 0'])- })-- test('recognizes closed unfilled segment chains', () => {- const paths = vectorNetworkToSVGPaths({- vertices: [- { x: 0, y: 0 },- { x: 10, y: 0 },- { x: 0, y: 10 }- ],- segments: [- { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 2, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }- ],- regions: []- })-- expect(paths).toEqual(['M10 0L0 10L0 0L10 0Z'])- })-- test('empty network', () => {- const paths = vectorNetworkToSVGPaths({ vertices: [], segments: [], regions: [] })- expect(paths).toHaveLength(0)- })-})diff --git a/tests/engine/io/svg/path-parse.test.ts b/tests/engine/io/svg/path-parse.test.tsindex ee4a22dbc..944ad2623 100644--- a/tests/engine/io/svg/path-parse.test.ts+++ b/tests/engine/io/svg/path-parse.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from 'bun:test'-import { vectorNetworkToSVGPaths } from '@open-pencil/core/io/formats/svg'import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'+import { vectorNetworkToSVGPaths } from '@open-pencil/scene-graph/vector-network'describe('parseSVGPath', () => {test('simple rectangle M L L L Z', () => {