AI-native design editor. Open-source Figma alternative.
fix(core): fill open subpaths of filled SVG paths (#876)
Danila Poyarkovfa3672c39c4e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 15508a87e..4f3fc2c3e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -98,6 +98,7 @@- Load the Bold, Medium, and other styles of macOS system fonts packaged as font collections, such as Menlo, Helvetica Neue, and Avenir Next, instead of reporting them as substituted or drawing a different style (#746).- Load the Medium, Semibold, Bold, and other styles of installed variable fonts such as SF Pro on macOS instead of reporting them as substituted (#752).- Ship the MIT license text in every published npm package, and add READMEs for `@open-pencil/core`, `@open-pencil/cli`, and `@open-pencil/mcp` on npm.+- Fill the open subpaths of filled, unstroked SVG paths as if they were closed, as SVG does, in icons from `insert_icon` and Design JSX `<Icon>`, inline Design JSX `<svg>`, SVG from `import_svg` or dropped and pasted files, and SVG clip paths. Icons that cut holes with open subpaths, such as some Font Awesome icons, no longer render with those holes filled in, and filled `<polyline>` elements render filled instead of not at all.- Keep round and other stroke caps and joins after saving and reopening the file on icons from `insert_icon` and Design JSX `<Icon>`, and on vectors from inline Design JSX `<svg>`, `import_svg`, and dropped or pasted SVG files. They were set only on the stroke paint, which `.fig` does not store, so outline icons such as Lucide's reopened with butt caps and miter joins and showed gaps where their strokes meet.### Performancediff --git a/packages/core/src/icons/svg.ts b/packages/core/src/icons/svg.tsindex c8b3f5bf4..89421a4d6 100644--- a/packages/core/src/icons/svg.ts+++ b/packages/core/src/icons/svg.ts@@ -407,10 +407,15 @@ export function scalePathInfos(}if (scaleX !== 1 || scaleY !== 1) transformedPath = transformedPath.scale(scaleX, scaleY)const scaledD = transformedPath.round(2).toString()+ const fill = normalizeSVGPaint(path.fill)+ const stroke = normalizeSVGPaint(path.stroke)return {- vectorNetwork: parseSVGPath(scaledD, path.fillRule),- fill: normalizeSVGPaint(path.fill),- stroke: normalizeSVGPaint(path.stroke),+ // A stroke would also trace the closing edge of an open subpath in the fill region.+ vectorNetwork: parseSVGPath(scaledD, path.fillRule, {+ includeOpenRegions: fill !== null && stroke === null+ }),+ fill,+ stroke,strokeWidth:path.strokeWidth * transformStrokeScale(path.transform) * Math.min(scaleX, scaleY),strokeCap: path.strokeCap,diff --git a/packages/core/src/vector/vectorize/svg/to-vectors.ts b/packages/core/src/vector/vectorize/svg/to-vectors.tsindex 5717b5b65..2ce77b301 100644--- a/packages/core/src/vector/vectorize/svg/to-vectors.ts+++ b/packages/core/src/vector/vectorize/svg/to-vectors.ts@@ -99,7 +99,12 @@ export function svgToVectorPaths(const transform = path.transform ?? nullconst pathData = applySVGTransformToPath(path.d, transform)const scaledD = mapSVGPathToViewport(pathData, viewport)- const network = parseSVGPath(scaledD, fillRule)+ const solidFills = resolveFill(path, defaultColor)+ const strokes = resolveStrokes(path, defaultColor, strokeScale)+ // A stroke would also trace the closing edge of an open subpath in the fill region.+ const network = parseSVGPath(scaledD, fillRule, {+ includeOpenRegions: solidFills.length > 0 && strokes.length === 0+ })const pathBounds = computeAccurateBounds(network)const gradientFill =gradients.size > 0@@ -127,9 +132,11 @@ export function svgToVectorPaths(.scale(pathBounds.width, pathBounds.height).translate(pathBounds.x, pathBounds.y).toString()- return parseSVGPath(clipData, clipPath.fillRule)+ return parseSVGPath(clipData, clipPath.fillRule, { includeOpenRegions: true })}- return parseSVGPath(mapSVGPathToViewport(clipData, viewport), clipPath.fillRule)+ return parseSVGPath(mapSVGPathToViewport(clipData, viewport), clipPath.fillRule, {+ includeOpenRegions: true+ })})))@@ -138,8 +145,8 @@ export function svgToVectorPaths(}vectorized.push({vectorNetwork: network,- fills: gradientFill ? [gradientFill] : resolveFill(path, defaultColor),- strokes: resolveStrokes(path, defaultColor, strokeScale),+ fills: gradientFill ? [gradientFill] : solidFills,+ strokes,clipNetworks})}diff --git a/packages/core/tests/icons/render.test.ts b/packages/core/tests/icons/render.test.tsindex 3372d3223..f1c17b31d 100644--- a/packages/core/tests/icons/render.test.ts+++ b/packages/core/tests/icons/render.test.ts@@ -2,7 +2,13 @@ import { describe, expect, test } from 'bun:test'import { expectDefined } from '#core-tests/helpers/assert'-import { exportFigFile, parseFigFile } from '@open-pencil/core/io'+import { SkiaRenderer } from '@open-pencil/core'+import {+ exportFigFile,+ initCanvasKit,+ parseFigFile,+ renderNodesToImage+} from '@open-pencil/core/io'import { SceneGraph } from '@open-pencil/scene-graph'import { parseColor } from '@open-pencil/scene-graph/color'@@ -39,4 +45,46 @@ describe('createIconFromPaths', () => {{ cap: 'ROUND', join: 'ROUND' }])})++ test('fills open subpaths of a filled path together with its closed subpaths', async () => {+ const graph = new SceneGraph()+ // An open outer square around a closed, counter-wound inner square: a 24 px ring.+ const { page, frame } = insertIcon(+ graph,+ '<path fill="currentColor" d="M0 0h24v24H0M6 6v12h12V6z"/>'+ )++ const ck = await initCanvasKit()+ const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))+ try {+ const png = expectDefined(+ renderNodesToImage(ck, renderer, graph, page.id, [frame.id], {+ scale: 1,+ format: 'PNG',+ trimTransparent: false+ })+ )+ const image = expectDefined(ck.MakeImageFromEncoded(png))+ const alphaAt = (x: number, y: number) => {+ const pixel = expectDefined(+ image.readPixels(x, y, {+ width: 1,+ height: 1,+ alphaType: ck.AlphaType.Unpremul,+ colorType: ck.ColorType.RGBA_8888,+ colorSpace: ck.ColorSpace.SRGB+ })+ )+ return pixel[3]+ }+ try {+ expect(alphaAt(3, 3)).toBe(255)+ expect(alphaAt(12, 12)).toBe(0)+ } finally {+ image.delete()+ }+ } finally {+ renderer.destroy()+ }+ })})diff --git a/packages/core/tests/vector/vectorize/placement.test.ts b/packages/core/tests/vector/vectorize/placement.test.tsindex c0401355c..34572ad5e 100644--- a/packages/core/tests/vector/vectorize/placement.test.ts+++ b/packages/core/tests/vector/vectorize/placement.test.ts@@ -32,4 +32,15 @@ describe('SVG vector placement', () => {{ cap: 'ROUND', join: 'BEVEL' }])})++ test('fills open subpaths of a filled path but does not stroke their closing edges', async () => {+ const ring = 'M0 0h24v24H0M6 6v12h12V6z'+ const { vectors } = await importVectors(+ `<svg viewBox="0 0 24 24"><path d="${ring}"/><path d="${ring}" stroke="#000"/></svg>`+ )+ const [filled, stroked] = vectors.map((vector) => expectDefined(vector.vectorNetwork))++ expect(filled.regions.flatMap((region) => region.loops)).toHaveLength(2)+ expect(stroked.regions.flatMap((region) => region.loops)).toHaveLength(1)+ })})diff --git a/packages/scene-graph/src/parse-path.ts b/packages/scene-graph/src/parse-path.tsindex 20c6f868b..61786b00d 100644--- a/packages/scene-graph/src/parse-path.ts+++ b/packages/scene-graph/src/parse-path.ts@@ -21,10 +21,18 @@ interface ParseOptions {** Uses `svgpath` to normalize all commands to absolute M/L/C/Z* (arcs → cubics via `.unarc()`, smooth curves → explicit via `.unshort()`).+ *+ * Only closed subpaths form the fill region unless `includeOpenRegions` is set. SVG fills every+ * subpath as if it were closed, so set it for a filled path to keep holes that an open subpath and+ * a closed one cut together under the path's fill rule.*/-export function parseSVGPath(d: string, windingRule: WindingRule = 'NONZERO'): VectorNetwork {+export function parseSVGPath(+ d: string,+ windingRule: WindingRule = 'NONZERO',+ options: { includeOpenRegions?: boolean } = {}+): VectorNetwork {const parsed = parsePath(d, windingRule, {- includeOpenRegions: false,+ includeOpenRegions: options.includeOpenRegions ?? false,strictCommands: false})return parsed.ok ? parsed.network : { vertices: [], segments: [], regions: [] }diff --git a/packages/scene-graph/tests/parse-path.test.ts b/packages/scene-graph/tests/parse-path.test.tsnew file mode 100644index 000000000..17a29bb17--- /dev/null+++ b/packages/scene-graph/tests/parse-path.test.ts@@ -0,0 +1,29 @@+import { describe, expect, test } from 'bun:test'++import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'++// An open outer square around a closed inner square, as filled icon sets often draw a ring.+const RING = 'M0 0h24v24H0M6 6v12h12V6z'++describe('parseSVGPath', () => {+ test('leaves open subpaths out of the fill region by default', () => {+ const network = parseSVGPath(RING)++ expect(network.regions).toHaveLength(1)+ expect(network.regions[0].loops).toEqual([[3, 4, 5, 6]])+ })++ test('puts open subpaths in the fill region with includeOpenRegions', () => {+ const network = parseSVGPath(RING, 'EVENODD', { includeOpenRegions: true })++ expect(network.regions).toEqual([+ {+ windingRule: 'EVENODD',+ loops: [+ [0, 1, 2],+ [3, 4, 5, 6]+ ]+ }+ ])+ })+})diff --git a/tests/engine/io/svg/import.test.ts b/tests/engine/io/svg/import.test.tsindex de88b716d..0aaa811a2 100644--- a/tests/engine/io/svg/import.test.ts+++ b/tests/engine/io/svg/import.test.ts@@ -212,9 +212,10 @@ describe('import_svg', () => {</svg>`})) as { id: string }+ // SVG fills a polyline as if it were closed, so both flatten into one filled vector.const children = graph.getChildren(result.id)- expect(children).toHaveLength(2)- expect(children.every(({ vectorNetwork }) => vectorNetwork !== null)).toBe(true)+ expect(children).toHaveLength(1)+ expect(expectDefined(children[0].vectorNetwork).regions).toHaveLength(2)})test('applies nested transforms through the XML tree', async () => {