Skip to content

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

feat(vector): add bitmap vectorization engine

Danila Poyarkov7d8d33e1e5c9
diff --git a/bun.lock b/bun.lock
index edac95972..9deb7f694 100644
--- a/bun.lock
+++ b/bun.lock
@@ -144,6 +144,7 @@
"@open-pencil/pen": "workspace:*",
"@open-pencil/scene-graph": "workspace:*",
"@tauri-apps/api": "^2",
+ "@xmldom/xmldom": "^0.9.10",
"acorn": "^8.16.0",
"canvaskit-wasm": "^0.40.0",
"culori": "^4.0.2",
@@ -1437,6 +1438,8 @@
"@webgpu/types": ["@webgpu/[email protected]", "", {}, "sha512-pUrWq3V5PiSGFLeLxoGqReTZmiiXwY3jRkIG5sLLKjyqNxrwm/04b4nw7LSmGWJcKk59XOM/YRTUwOzo4MMlow=="],
+ "@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw=="],
+
"abort-controller": ["[email protected]", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="],
"abort-error": ["[email protected]", "", {}, "sha512-fxqCblJiIPdSXIUrxI0PL+eJG49QdP9SQ70qtB65MVAoMr2rASlOyAbJFOylfB467F/f+5BCLJJq58RYi7mGfg=="],
diff --git a/packages/core/package.json b/packages/core/package.json
index b287b9acd..8cb75d96f 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -167,6 +167,7 @@
"@open-pencil/pen": "workspace:*",
"@open-pencil/scene-graph": "workspace:*",
"@tauri-apps/api": "^2",
+ "@xmldom/xmldom": "^0.9.10",
"acorn": "^8.16.0",
"canvaskit-wasm": "^0.40.0",
"culori": "^4.0.2",
diff --git a/packages/core/src/icons/svg.ts b/packages/core/src/icons/svg.ts
index afbf8f02f..b78d78638 100644
--- a/packages/core/src/icons/svg.ts
+++ b/packages/core/src/icons/svg.ts
@@ -6,9 +6,8 @@ import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
import type { IconData, IconifyIconEntry, IconPathInfo } from './types'
function attrValue(tag: string, attr: string): string | null {
- const re = new RegExp(`\\b${attr}="([^"]*)"`)
- const match = tag.match(re)
- return match ? match[1] : null
+ const match = tag.match(new RegExp(`\\b${attr}\\s*=\\s*(["'])(.*?)\\1`, 'i'))
+ return match?.[2] ?? null
}
function num(tag: string, attr: string, fallback = 0): number {
@@ -123,7 +122,8 @@ export function extractPaths(svgBody: string): IconPathInfo[] {
),
strokeCap: attrValue(tag, 'stroke-linecap') ?? groupAttrs.strokeCap ?? 'butt',
strokeJoin: attrValue(tag, 'stroke-linejoin') ?? groupAttrs.strokeJoin ?? 'miter',
- fillRule: fillRuleAttr === 'evenodd' ? 'EVENODD' : 'NONZERO'
+ fillRule: fillRuleAttr === 'evenodd' ? 'EVENODD' : 'NONZERO',
+ transform: attrValue(tag, 'transform')
})
}
return result
diff --git a/packages/core/src/icons/types.ts b/packages/core/src/icons/types.ts
index e84a854b6..e8df7c89b 100644
--- a/packages/core/src/icons/types.ts
+++ b/packages/core/src/icons/types.ts
@@ -45,4 +45,6 @@ export interface IconPathInfo {
strokeCap: string
strokeJoin: string
fillRule: WindingRule
+ /** Raw transform attribute from the source SVG element. */
+ transform?: string | null
}
diff --git a/packages/core/src/io/formats/svg/metadata.ts b/packages/core/src/io/formats/svg/metadata.ts
new file mode 100644
index 000000000..66cf00619
--- /dev/null
+++ b/packages/core/src/io/formats/svg/metadata.ts
@@ -0,0 +1,35 @@
+import type { Rect, Size } from '@open-pencil/scene-graph/primitives'
+
+function attributeValue(svg: string, attribute: string): string | null {
+ const match = svg.match(new RegExp(`\\b${attribute}\\s*=\\s*(["'])(.*?)\\1`, 'i'))
+ return match?.[2] ?? null
+}
+
+export function parseSVGViewBox(svg: string): Rect | null {
+ const value = attributeValue(svg, 'viewBox')
+ if (!value) return null
+ const values = value
+ .trim()
+ .split(/[\s,]+/)
+ .map(Number)
+ if (values.length !== 4 || values.some((entry) => !Number.isFinite(entry))) return null
+ const [x = 0, y = 0, width = 0, height = 0] = values
+ if (width <= 0 || height <= 0) return null
+ return { x, y, width, height }
+}
+
+function parseSVGDimension(svg: string, attribute: string): number | null {
+ const value = attributeValue(svg, attribute)
+ if (!value) return null
+ const parsed = Number.parseFloat(value)
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null
+}
+
+export function parseSVGSize(svg: string, fallback: Size = { width: 24, height: 24 }): Size {
+ const viewBox = parseSVGViewBox(svg)
+ const width = parseSVGDimension(svg, 'width')
+ const height = parseSVGDimension(svg, 'height')
+ if (width && height) return { width, height }
+ if (viewBox) return { width: viewBox.width, height: viewBox.height }
+ return fallback
+}
diff --git a/packages/core/src/tools/create/svg.ts b/packages/core/src/tools/create/svg.ts
index baf7f8aee..7a2faa7a9 100644
--- a/packages/core/src/tools/create/svg.ts
+++ b/packages/core/src/tools/create/svg.ts
@@ -1,36 +1,12 @@
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
-import type { Rect } from '@open-pencil/scene-graph/primitives'
import { parseColor } from '#core/color'
import { createPathStroke } from '#core/icons/path-style'
import { extractPaths } from '#core/icons/svg'
import type { IconPathInfo } from '#core/icons/types'
+import { parseSVGSize } from '#core/io/formats/svg/metadata'
import { defineTool } from '#core/tools/schema'
-function parseSvgViewBox(svg: string): Rect | null {
- const match = svg.match(/viewBox="([^"]+)"/)
- if (!match) return null
- const [x, y, w, h] = match[1].split(/[\s,]+/).map(Number)
- if ([x, y, w, h].some((n) => !Number.isFinite(n))) return null
- return { x, y, width: w, height: h }
-}
-
-function parseSvgDimension(svg: string, attr: string): number | null {
- const match = svg.match(new RegExp(`\\b${attr}="([^"]+)"`))
- if (!match) return null
- const n = Number.parseFloat(match[1])
- return Number.isFinite(n) && n > 0 ? n : null
-}
-
-function parseSvgSize(svg: string): { width: number; height: number } {
- const viewBox = parseSvgViewBox(svg)
- const w = parseSvgDimension(svg, 'width')
- const h = parseSvgDimension(svg, 'height')
- if (w && h) return { width: w, height: h }
- if (viewBox) return { width: viewBox.width, height: viewBox.height }
- return { width: 24, height: 24 }
-}
-
function createVectorFromPath(
figma: Parameters<Parameters<typeof defineTool>[0]['execute']>[0],
path: IconPathInfo,
@@ -102,7 +78,7 @@ export const importSvg = defineTool({
const paths = extractPaths(svg)
if (paths.length === 0) return { error: 'No supported SVG elements found in the markup' }
- const { width, height } = parseSvgSize(svg)
+ const { width, height } = parseSVGSize(svg)
const defaultColor = args.color ?? '#000000'
const parentId = args.parent_id ?? figma.currentPage.id
diff --git a/packages/core/src/vector/index.ts b/packages/core/src/vector/index.ts
index 90d01be35..0f12b3add 100644
--- a/packages/core/src/vector/index.ts
+++ b/packages/core/src/vector/index.ts
@@ -1,3 +1,5 @@
+export * from './vectorize'
+
export {
breakAtVertex,
computeAccurateBounds,
diff --git a/packages/core/src/vector/vectorize/index.ts b/packages/core/src/vector/vectorize/index.ts
new file mode 100644
index 000000000..2c5ec2dfb
--- /dev/null
+++ b/packages/core/src/vector/vectorize/index.ts
@@ -0,0 +1,11 @@
+export {
+ createVectorFrameChildren,
+ resolveVectorFramePlacement,
+ type VectorFramePlacement
+} from './placement'
+export {
+ preprocessForVectorize,
+ type GetCanvasKit,
+ type PreprocessForVectorizeResult
+} from './preprocess'
+export { svgToVectorPaths, type SVGVectorizeResult, type VectorizedPath } from './svg/to-vectors'
diff --git a/packages/core/src/vector/vectorize/placement.ts b/packages/core/src/vector/vectorize/placement.ts
new file mode 100644
index 000000000..289261116
--- /dev/null
+++ b/packages/core/src/vector/vectorize/placement.ts
@@ -0,0 +1,106 @@
+import type { SceneGraph, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
+
+import { computeAccurateBounds } from '#core/vector/curve-math'
+
+import type { SVGVectorizeResult } from './svg/to-vectors'
+
+export interface VectorFramePlacement {
+ x: number
+ y: number
+ width: number
+ height: number
+ offsetX: number
+ offsetY: number
+}
+
+function shouldTightenToContent(node: Pick<SceneNode, 'width' | 'height'>, content: Rect): boolean {
+ return (
+ content.width > 0 &&
+ content.height > 0 &&
+ (content.x > 0 ||
+ content.y > 0 ||
+ content.width < node.width - 0.5 ||
+ content.height < node.height - 0.5)
+ )
+}
+
+export function resolveVectorFramePlacement(
+ node: Pick<SceneNode, 'x' | 'y' | 'width' | 'height'>,
+ content: Rect
+): VectorFramePlacement {
+ const tighten = shouldTightenToContent(node, content)
+ const offsetX = tighten ? content.x : 0
+ const offsetY = tighten ? content.y : 0
+ return {
+ x: node.x + offsetX,
+ y: node.y + offsetY,
+ width: tighten ? content.width : node.width,
+ height: tighten ? content.height : node.height,
+ offsetX,
+ offsetY
+ }
+}
+
+function offsetVectorNetwork(
+ network: VectorNetwork,
+ offsetX: number,
+ offsetY: number
+): VectorNetwork {
+ if (offsetX === 0 && offsetY === 0) return network
+ return {
+ vertices: network.vertices.map((vertex) => ({
+ ...vertex,
+ x: vertex.x - offsetX,
+ y: vertex.y - offsetY
+ })),
+ segments: network.segments,
+ regions: network.regions
+ }
+}
+
+/** Fit vector geometry to node-local coordinates and a tight width/height (pen-tool pattern). */
+function normalizeVectorToNodeBounds(network: VectorNetwork): {
+ network: VectorNetwork
+ bounds: Rect
+} | null {
+ const bounds = computeAccurateBounds(network)
+ if (bounds.width <= 0 || bounds.height <= 0) return null
+
+ return {
+ bounds,
+ network: {
+ vertices: network.vertices.map((vertex) => ({
+ ...vertex,
+ x: vertex.x - bounds.x,
+ y: vertex.y - bounds.y
+ })),
+ segments: network.segments,
+ regions: network.regions
+ }
+ }
+}
+
+export function createVectorFrameChildren(
+ graph: SceneGraph,
+ frameId: string,
+ vectorized: SVGVectorizeResult,
+ placement: VectorFramePlacement
+): void {
+ for (const [index, path] of vectorized.paths.entries()) {
+ const inFrame = offsetVectorNetwork(path.vectorNetwork, placement.offsetX, placement.offsetY)
+ const normalized = normalizeVectorToNodeBounds(inFrame)
+ if (!normalized) continue
+
+ graph.createNode('VECTOR', frameId, {
+ name: `path ${index + 1}`,
+ x: normalized.bounds.x,
+ y: normalized.bounds.y,
+ width: normalized.bounds.width,
+ height: normalized.bounds.height,
+ vectorNetwork: normalized.network,
+ fills: path.fills,
+ strokes: path.strokes
+ })
+ }
+}
diff --git a/packages/core/src/vector/vectorize/preprocess.ts b/packages/core/src/vector/vectorize/preprocess.ts
new file mode 100644
index 000000000..6096c6aaa
--- /dev/null
+++ b/packages/core/src/vector/vectorize/preprocess.ts
@@ -0,0 +1,134 @@
+import type { CanvasKit } from 'canvaskit-wasm'
+
+import type { Size } from '@open-pencil/scene-graph/primitives'
+
+const MIN_DIMENSION = 256
+const MAX_DIMENSION = 4096
+const MAX_MEGAPIXELS = 16_000_000
+const MAX_BYTES = 5 * 1024 * 1024
+
+export type GetCanvasKit = () => CanvasKit | null
+
+export interface PreprocessForVectorizeResult {
+ pngBytes: Uint8Array
+ originalWidth: number
+ originalHeight: number
+ width: number
+ height: number
+}
+
+function clampDimensions(width: number, height: number): Size {
+ let w = width
+ let h = height
+ const minDim = Math.min(w, h)
+ if (minDim > 0 && minDim < MIN_DIMENSION) {
+ const scale = MIN_DIMENSION / minDim
+ w = Math.round(w * scale)
+ h = Math.round(h * scale)
+ }
+
+ const maxDim = Math.max(w, h)
+ if (maxDim > MAX_DIMENSION) {
+ const scale = MAX_DIMENSION / maxDim
+ w = Math.round(w * scale)
+ h = Math.round(h * scale)
+ }
+
+ if (w * h > MAX_MEGAPIXELS) {
+ const scale = Math.sqrt(MAX_MEGAPIXELS / (w * h))
+ w = Math.max(1, Math.round(w * scale))
+ h = Math.max(1, Math.round(h * scale))
+ }
+
+ return { width: w, height: h }
+}
+
+function encodePNG(
+ ck: CanvasKit,
+ image: ReturnType<CanvasKit['MakeImageFromEncoded']>
+): Uint8Array | null {
+ if (!image) return null
+ const encoded = image.encodeToBytes(ck.ImageFormat.PNG, 100)
+ return encoded ? new Uint8Array(encoded) : null
+}
+
+function resizeImage(
+ ck: CanvasKit,
+ source: NonNullable<ReturnType<CanvasKit['MakeImageFromEncoded']>>,
+ width: number,
+ height: number
+): Uint8Array | null {
+ const pixels = ck.Malloc(Uint8Array, width * height * 4)
+ const surface = ck.MakeRasterDirectSurface(
+ {
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB,
+ width,
+ height
+ },
+ pixels,
+ width * 4
+ )
+ if (!surface) {
+ ck.Free(pixels)
+ return null
+ }
+ const canvas = surface.getCanvas()
+ canvas.clear(ck.TRANSPARENT)
+ const srcW = source.width()
+ const srcH = source.height()
+ canvas.drawImageRectOptions(
+ source,
+ ck.LTRBRect(0, 0, srcW, srcH),
+ ck.LTRBRect(0, 0, width, height),
+ ck.FilterMode.Linear,
+ ck.MipmapMode.None,
+ null
+ )
+ surface.flush()
+ const snapshot = surface.makeImageSnapshot()
+ const encoded = encodePNG(ck, snapshot)
+ snapshot.delete()
+ surface.delete()
+ ck.Free(pixels)
+ return encoded
+}
+
+export function preprocessForVectorize(
+ bytes: Uint8Array,
+ getCk: GetCanvasKit
+): PreprocessForVectorizeResult | null {
+ const ck = getCk()
+ if (!ck) return null
+
+ const source = ck.MakeImageFromEncoded(bytes)
+ if (!source) return null
+
+ const originalWidth = source.width()
+ const originalHeight = source.height()
+ if (originalWidth <= 0 || originalHeight <= 0) {
+ source.delete()
+ return null
+ }
+
+ const target = clampDimensions(originalWidth, originalHeight)
+ let pngBytes: Uint8Array | null
+ if (target.width === originalWidth && target.height === originalHeight) {
+ pngBytes = encodePNG(ck, source)
+ } else {
+ pngBytes = resizeImage(ck, source, target.width, target.height)
+ }
+ source.delete()
+
+ if (!pngBytes || pngBytes.length === 0) return null
+ if (pngBytes.length > MAX_BYTES) return null
+
+ return {
+ pngBytes,
+ originalWidth,
+ originalHeight,
+ width: target.width,
+ height: target.height
+ }
+}
diff --git a/packages/core/src/vector/vectorize/svg/gradients.ts b/packages/core/src/vector/vectorize/svg/gradients.ts
new file mode 100644
index 000000000..65cf90723
--- /dev/null
+++ b/packages/core/src/vector/vectorize/svg/gradients.ts
@@ -0,0 +1,226 @@
+/**
+ * Parse SVG <linearGradient>/<radialGradient> defs and resolve `fill="url(#id)"`
+ * references into scene-graph gradient fills.
+ *
+ * Raster vectorizers (Recraft, fal) emit shaded regions as gradients rather than
+ * flat colors. Without this, those paths fall back to the default solid color
+ * (black). Gradient geometry is given in userSpaceOnUse viewBox coordinates; we
+ * map the endpoints through the same transform pipeline as the path data, then
+ * normalize into each node's bounding box (objectBoundingBox) space, matching the
+ * gradientTransform convention used by the SVG exporter (see io/formats/svg/defs).
+ */
+import { DOMParser } from '@xmldom/xmldom'
+import svgpath from 'svgpath'
+
+import type { Fill, GradientStop } from '@open-pencil/scene-graph'
+import type { Color, Matrix, Rect, Size, Vector } from '@open-pencil/scene-graph/primitives'
+
+import { parseColor } from '#core/color'
+
+interface RawStop {
+ offset: number
+ color: Color
+}
+
+interface ParsedGradient {
+ kind: 'linear' | 'radial'
+ units: 'userSpaceOnUse' | 'objectBoundingBox'
+ transform: string | null
+ stops: RawStop[]
+ // linear
+ x1: number
+ y1: number
+ x2: number
+ y2: number
+ // radial
+ cx: number
+ cy: number
+ r: number
+}
+
+/** Minimal structural view of the parsed XML nodes we read (DOM-compatible). */
+interface SvgQueryable {
+ getElementsByTagName(name: string): ArrayLike<SvgElementLike>
+}
+interface SvgElementLike extends SvgQueryable {
+ getAttribute(name: string): string | null
+}
+
+/** Coordinate value: bare number (userSpaceOnUse) or percent/fraction (objectBoundingBox). */
+function coord(value: string | null, fallback: number): number {
+ if (value == null) return fallback
+ const trimmed = value.trim()
+ if (trimmed.endsWith('%')) return Number.parseFloat(trimmed) / 100
+ const n = Number.parseFloat(trimmed)
+ return Number.isFinite(n) ? n : fallback
+}
+
+function readStops(gradient: SvgElementLike): RawStop[] {
+ const stops: RawStop[] = []
+ const stopEls = Array.from(gradient.getElementsByTagName('stop'))
+ for (const [i, stop] of stopEls.entries()) {
+ const offset = coord(stop.getAttribute('offset'), i === 0 ? 0 : 1)
+ const color = parseColor(stop.getAttribute('stop-color') ?? '#000000')
+ const opacity = stop.getAttribute('stop-opacity')
+ if (opacity != null) {
+ const a = Number.parseFloat(opacity)
+ if (Number.isFinite(a)) color.a = a
+ }
+ stops.push({ offset: Math.min(1, Math.max(0, offset)), color })
+ }
+ return stops.sort((a, b) => a.offset - b.offset)
+}
+
+/**
+ * Parse every gradient def in the SVG into a lookup by id, via an XML/DOM parse
+ * (no hand-rolled markup parsing). Returns an empty map on parse failure so a
+ * malformed SVG simply falls back to solid fills.
+ */
+export function parseSVGGradients(svg: string): Map<string, ParsedGradient> {
+ const map = new Map<string, ParsedGradient>()
+ let doc: SvgQueryable
+ try {
+ doc = new DOMParser().parseFromString(svg, 'image/svg+xml')
+ } catch {
+ return map
+ }
+
+ for (const kind of ['linear', 'radial'] as const) {
+ const els = Array.from(doc.getElementsByTagName(`${kind}Gradient`))
+ for (const el of els) {
+ const id = el.getAttribute('id')
+ if (!id) continue
+ // SVG default gradientUnits is objectBoundingBox; vectorizers (Recraft/fal)
+ // set userSpaceOnUse explicitly.
+ const units =
+ el.getAttribute('gradientUnits') === 'userSpaceOnUse'
+ ? 'userSpaceOnUse'
+ : 'objectBoundingBox'
+ map.set(id, {
+ kind,
+ units,
+ transform: el.getAttribute('gradientTransform'),
+ stops: readStops(el),
+ x1: coord(el.getAttribute('x1'), 0),
+ y1: coord(el.getAttribute('y1'), 0),
+ x2: coord(el.getAttribute('x2'), units === 'objectBoundingBox' ? 1 : 0),
+ y2: coord(el.getAttribute('y2'), 0),
+ cx: coord(el.getAttribute('cx'), 0.5),
+ cy: coord(el.getAttribute('cy'), 0.5),
+ r: coord(el.getAttribute('r'), 0.5)
+ })
+ }
+ }
+ return map
+}
+
+function gradientIdFromFill(fill: string | null): string | null {
+ if (!fill) return null
+ const m = fill.match(/^url\(\s*#([^)\s]+)\s*\)$/)
+ return m ? m[1] : null
+}
+
+/**
+ * Map a userSpaceOnUse point through the same element-transform + viewBox→bounds
+ * pipeline applied to the path data, yielding bounds-pixel-space coordinates.
+ */
+function mapUserPoint(
+ x: number,
+ y: number,
+ elementTransform: string | null,
+ gradientTransform: string | null,
+ space: Rect,
+ bounds: Size
+): Vector {
+ const sx = bounds.width / space.width
+ const sy = bounds.height / space.height
+ let sp = svgpath(`M${x} ${y}`)
+ if (gradientTransform) sp = sp.transform(gradientTransform)
+ if (elementTransform) sp = sp.transform(elementTransform)
+ sp = sp.translate(-space.x, -space.y).scale(sx, sy)
+ const out = sp.toString()
+ const m = out.match(/M\s*(-?[\d.eE+-]+)[ ,]+(-?[\d.eE+-]+)/)
+ if (!m) return { x, y }
+ return { x: Number.parseFloat(m[1]), y: Number.parseFloat(m[2]) }
+}
+
+function gradientStops(stops: RawStop[]): GradientStop[] {
+ return stops.map((s) => ({ color: s.color, position: s.offset }))
+}
+
+/**
+ * Build a scene-graph gradient Fill for `fill="url(#id)"`, with its transform
+ * expressed in the path's normalized bounding-box space (`nodeBounds` in the same
+ * bounds-pixel space as the parsed network).
+ */
+export function resolveGradientFill(
+ fillRef: string | null,
+ gradients: Map<string, ParsedGradient>,
+ elementTransform: string | null,
+ space: Rect,
+ bounds: Size,
+ nodeBounds: Rect
+): Fill | null {
+ const id = gradientIdFromFill(fillRef)
+ if (!id) return null
+ const grad = gradients.get(id)
+ if (!grad || grad.stops.length === 0) return null
+ if (nodeBounds.width <= 0 || nodeBounds.height <= 0) return null
+
+ const toLocal = (px: number, py: number): Vector => {
+ const mapped =
+ grad.units === 'objectBoundingBox'
+ ? { x: nodeBounds.x + px * nodeBounds.width, y: nodeBounds.y + py * nodeBounds.height }
+ : mapUserPoint(px, py, elementTransform, grad.transform, space, bounds)
+ return {
+ x: (mapped.x - nodeBounds.x) / nodeBounds.width,
+ y: (mapped.y - nodeBounds.y) / nodeBounds.height
+ }
+ }
+
+ const baseColor = grad.stops[0].color
+ const stops = gradientStops(grad.stops)
+
+ if (grad.kind === 'radial') {
+ const center = toLocal(grad.cx, grad.cy)
+ const edgeX = toLocal(grad.cx + grad.r, grad.cy)
+ const edgeY = toLocal(grad.cx, grad.cy + grad.r)
+ const transform: Matrix = {
+ m00: edgeX.x - center.x,
+ m01: edgeY.x - center.x,
+ m02: center.x,
+ m10: edgeX.y - center.y,
+ m11: edgeY.y - center.y,
+ m12: center.y
+ }
+ return {
+ type: 'GRADIENT_RADIAL',
+ color: baseColor,
+ opacity: 1,
+ visible: true,
+ gradientStops: stops,
+ gradientTransform: transform
+ }
+ }
+
+ const start = toLocal(grad.x1, grad.y1)
+ const end = toLocal(grad.x2, grad.y2)
+ const ax = end.x - start.x
+ const ay = end.y - start.y
+ const transform: Matrix = {
+ m00: ax,
+ m01: -ay,
+ m02: start.x,
+ m10: ay,
+ m11: ax,
+ m12: start.y
+ }
+ return {
+ type: 'GRADIENT_LINEAR',
+ color: baseColor,
+ opacity: 1,
+ visible: true,
+ gradientStops: stops,
+ gradientTransform: transform
+ }
+}
diff --git a/packages/core/src/vector/vectorize/svg/to-vectors.ts b/packages/core/src/vector/vectorize/svg/to-vectors.ts
new file mode 100644
index 000000000..ca171d202
--- /dev/null
+++ b/packages/core/src/vector/vectorize/svg/to-vectors.ts
@@ -0,0 +1,118 @@
+/**
+ * Maps vendor SVG into scene-graph vector networks.
+ *
+ * Raster vectorizers often return paths in viewBox user units while width/height
+ * reflect the input pixel size. Scale path data from the SVG coordinate space
+ * (viewBox, else width/height) into the target node bounds before parsing.
+ */
+import svgpath from 'svgpath'
+
+import type { Fill, Stroke, VectorNetwork, WindingRule } from '@open-pencil/scene-graph'
+import { computeBounds } from '@open-pencil/scene-graph/geometry'
+import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
+import type { Rect, Size } from '@open-pencil/scene-graph/primitives'
+
+import { parseColor } from '#core/color'
+import { createPathStroke } from '#core/icons/path-style'
+import { extractPaths } from '#core/icons/svg'
+import type { IconPathInfo } from '#core/icons/types'
+import { parseSVGSize, parseSVGViewBox } from '#core/io/formats/svg/metadata'
+import { computeAccurateBounds } from '#core/vector/curve-math'
+
+import { parseSVGGradients, resolveGradientFill } from './gradients'
+import { applySVGTransformToPath } from './transform'
+
+/** Map path data from SVG user space (viewBox) into target pixel bounds. */
+function mapPathDataToBounds(d: string, space: Rect, target: Size): string {
+ const sx = target.width / space.width
+ const sy = target.height / space.height
+ return svgpath(d).translate(-space.x, -space.y).scale(sx, sy).toString()
+}
+
+function parseSVGCoordinateSpace(svg: string): Rect {
+ const viewBox = parseSVGViewBox(svg)
+ if (viewBox && viewBox.width > 0 && viewBox.height > 0) return viewBox
+ const size = parseSVGSize(svg)
+ return { x: 0, y: 0, width: size.width, height: size.height }
+}
+
+function unionPathBounds(paths: VectorizedPath[]): Rect {
+ const rects = paths
+ .map((path) => computeAccurateBounds(path.vectorNetwork))
+ .filter((bounds) => bounds.width > 0 && bounds.height > 0)
+ return computeBounds(rects)
+}
+
+function resolveFill(path: IconPathInfo, defaultColor: string): Fill[] {
+ if (path.fill && path.fill !== 'none') {
+ const color = path.fill === 'currentColor' ? parseColor(defaultColor) : parseColor(path.fill)
+ return [{ type: 'SOLID', color, opacity: 1, visible: true }]
+ }
+ if (path.fill === null && !path.stroke) {
+ return [{ type: 'SOLID', color: parseColor(defaultColor), opacity: 1, visible: true }]
+ }
+ return []
+}
+
+function resolveStrokes(path: IconPathInfo, defaultColor: string, strokeScale = 1): Stroke[] {
+ if (!path.stroke || path.stroke === 'none') return []
+ const color = path.stroke === 'currentColor' ? parseColor(defaultColor) : parseColor(path.stroke)
+ return [createPathStroke(color, path.strokeWidth * strokeScale, path.strokeCap, path.strokeJoin)]
+}
+
+export interface VectorizedPath {
+ vectorNetwork: VectorNetwork
+ fills: Fill[]
+ strokes: Stroke[]
+}
+
+export interface SVGVectorizeResult {
+ paths: VectorizedPath[]
+ /** Tight bounds of path geometry in the target coordinate space. */
+ contentBounds: Rect
+}
+
+export function svgToVectorPaths(
+ svgText: string,
+ bounds: Size,
+ options?: { defaultColor?: string }
+): SVGVectorizeResult | null {
+ const paths = extractPaths(svgText)
+ if (paths.length === 0) return null
+
+ const space = parseSVGCoordinateSpace(svgText)
+ if (space.width <= 0 || space.height <= 0) return null
+
+ const defaultColor = options?.defaultColor ?? '#000000'
+ const gradients = parseSVGGradients(svgText)
+ // Path coordinates are scaled from SVG space into the target bounds; scale stroke
+ // width by the same (uniform) factor so thickness matches the transformed geometry.
+ const strokeScale = Math.min(bounds.width / space.width, bounds.height / space.height)
+
+ const vectorized: VectorizedPath[] = []
+ for (const path of paths) {
+ const fillRule: WindingRule = path.fillRule
+ const transform = path.transform ?? null
+ const pathData = applySVGTransformToPath(path.d, transform)
+ const scaledD = mapPathDataToBounds(pathData, space, bounds)
+ const network = parseSVGPath(scaledD, fillRule)
+ const gradientFill =
+ gradients.size > 0
+ ? resolveGradientFill(
+ path.fill,
+ gradients,
+ transform,
+ space,
+ bounds,
+ computeAccurateBounds(network)
+ )
+ : null
+ vectorized.push({
+ vectorNetwork: network,
+ fills: gradientFill ? [gradientFill] : resolveFill(path, defaultColor),
+ strokes: resolveStrokes(path, defaultColor, strokeScale)
+ })
+ }
+
+ return { paths: vectorized, contentBounds: unionPathBounds(vectorized) }
+}
diff --git a/packages/core/src/vector/vectorize/svg/transform.ts b/packages/core/src/vector/vectorize/svg/transform.ts
new file mode 100644
index 000000000..8a4dbb0f7
--- /dev/null
+++ b/packages/core/src/vector/vectorize/svg/transform.ts
@@ -0,0 +1,17 @@
+import svgpath from 'svgpath'
+
+/**
+ * Apply an SVG `transform` attribute to path data. Delegates the full transform
+ * grammar (translate/scale/rotate/skewX/skewY/matrix and lists) to svgpath rather
+ * than parsing a subset ourselves, so non-translate/matrix transforms import
+ * correctly. Returns the original path if the transform string can't be applied.
+ */
+export function applySVGTransformToPath(d: string, transform: string | null): string {
+ if (!transform || transform === 'none') return d
+ try {
+ return svgpath(d).transform(transform).toString()
+ } catch (err) {
+ console.warn('Ignoring unsupported SVG transform:', transform, err)
+ return d
+ }
+}
diff --git a/packages/scene-graph/src/primitives.ts b/packages/scene-graph/src/primitives.ts
index dd35b6dae..7be2bd43e 100644
--- a/packages/scene-graph/src/primitives.ts
+++ b/packages/scene-graph/src/primitives.ts
@@ -24,6 +24,11 @@ export interface Matrix {
m12: number
}
+export interface Size {
+ width: number
+ height: number
+}
+
export interface Rect {
x: number
y: number
diff --git a/tests/engine/vector/vectorize.test.ts b/tests/engine/vector/vectorize.test.ts
new file mode 100644
index 000000000..e639db5bc
--- /dev/null
+++ b/tests/engine/vector/vectorize.test.ts
@@ -0,0 +1,367 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import {
+ preprocessForVectorize,
+ resolveVectorFramePlacement,
+ svgToVectorPaths
+} from '@open-pencil/core/vector'
+
+import { initCanvasKit } from '#cli/headless'
+
+import { expectDefined } from '#tests/helpers/assert'
+import { testPath } from '#tests/helpers/paths'
+
+let ck: Awaited<ReturnType<typeof initCanvasKit>>
+
+const VECTORIZE_FIXTURES = testPath('fixtures/vectorize')
+
+async function loadFixturePng(name: string): Promise<Uint8Array> {
+ const buf = await Bun.file(`${VECTORIZE_FIXTURES}/${name}`).arrayBuffer()
+ return new Uint8Array(buf)
+}
+
+function countTransparentPixels(
+ image: NonNullable<ReturnType<typeof ck.MakeImageFromEncoded>>
+): number {
+ const pixels = image.readPixels(0, 0, {
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB,
+ width: image.width(),
+ height: image.height()
+ })
+ if (!pixels) return 0
+ let transparent = 0
+ for (let i = 3; i < pixels.length; i += 4) {
+ if (pixels[i] === 0) transparent++
+ }
+ return transparent
+}
+
+function createPng(width: number, height: number, alpha = 255): Uint8Array {
+ const pixels = ck.Malloc(Uint8Array, width * height * 4)
+ for (let i = 0; i < width * height; i++) {
+ const offset = i * 4
+ pixels[offset] = 80
+ pixels[offset + 1] = 120
+ pixels[offset + 2] = 200
+ pixels[offset + 3] = alpha
+ }
+ const surface = ck.MakeRasterDirectSurface(
+ {
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB,
+ width,
+ height
+ },
+ pixels,
+ width * 4
+ )
+ if (!surface) throw new Error('Failed to create surface')
+ const image = surface.makeImageSnapshot()
+ const encoded = image.encodeToBytes(ck.ImageFormat.PNG, 100)
+ image.delete()
+ surface.delete()
+ ck.Free(pixels)
+ if (!encoded) throw new Error('Failed to encode PNG')
+ return new Uint8Array(encoded)
+}
+
+beforeAll(async () => {
+ ck = await initCanvasKit()
+})
+
+describe('preprocessForVectorize', () => {
+ test('leaves images at or above 256px short side unchanged', () => {
+ const bytes = createPng(400, 300)
+ const result = preprocessForVectorize(bytes, () => ck)
+ expect(result).not.toBeNull()
+ expect(result?.width).toBe(400)
+ expect(result?.height).toBe(300)
+ expect(result?.originalWidth).toBe(400)
+ expect(result?.originalHeight).toBe(300)
+ })
+
+ test('upscales images below 256px short side', () => {
+ const bytes = createPng(100, 200)
+ const result = preprocessForVectorize(bytes, () => ck)
+ expect(result).not.toBeNull()
+ expect(Math.min(result?.width ?? 0, result?.height ?? 0)).toBeGreaterThanOrEqual(256)
+ })
+
+ test('preserves alpha channel', () => {
+ const bytes = createPng(128, 128, 0)
+ const result = preprocessForVectorize(bytes, () => ck)
+ const processed = expectDefined(result, 'preprocess result')
+ const decoded = expectDefined(ck.MakeImageFromEncoded(processed.pngBytes), 'decoded png')
+ expect(countTransparentPixels(decoded)).toBeGreaterThan(0)
+ decoded.delete()
+ })
+})
+
+describe('preprocessForVectorize fixtures', () => {
+ test('python_logo.png upscales short side below 256px', async () => {
+ const bytes = await loadFixturePng('python_logo.png')
+ const source = expectDefined(ck.MakeImageFromEncoded(bytes), 'source png')
+ expect(source.width()).toBe(580)
+ expect(source.height()).toBe(164)
+ source.delete()
+
+ const result = preprocessForVectorize(bytes, () => ck)
+ const processed = expectDefined(result, 'preprocess result')
+ expect(processed.originalWidth).toBe(580)
+ expect(processed.originalHeight).toBe(164)
+ expect(Math.min(processed.width, processed.height)).toBeGreaterThanOrEqual(256)
+ expect(processed.width).toBeGreaterThan(580)
+ expect(processed.height).toBe(256)
+ })
+
+ test('euro_shield.png keeps dimensions and alpha', async () => {
+ const bytes = await loadFixturePng('euro_shield.png')
+ const result = preprocessForVectorize(bytes, () => ck)
+ const processed = expectDefined(result, 'preprocess result')
+ expect(processed.width).toBe(577)
+ expect(processed.height).toBe(721)
+
+ const decoded = expectDefined(ck.MakeImageFromEncoded(processed.pngBytes), 'decoded png')
+ expect(countTransparentPixels(decoded)).toBeGreaterThan(0)
+ decoded.delete()
+ })
+
+ test('pilot_avatar.png keeps dimensions without upscale', async () => {
+ const bytes = await loadFixturePng('pilot_avatar.png')
+ const result = preprocessForVectorize(bytes, () => ck)
+ const processed = expectDefined(result, 'preprocess result')
+ expect(processed.width).toBe(412)
+ expect(processed.height).toBe(364)
+ expect(Math.min(processed.width, processed.height)).toBeGreaterThanOrEqual(256)
+
+ const decoded = expectDefined(ck.MakeImageFromEncoded(processed.pngBytes), 'decoded png')
+ expect(countTransparentPixels(decoded)).toBeGreaterThan(0)
+ decoded.delete()
+ })
+
+ test('sander_test_01.png preprocesses opaque illustration', async () => {
+ const bytes = await loadFixturePng('sander_test_01.png')
+ const source = expectDefined(ck.MakeImageFromEncoded(bytes), 'source png')
+ expect(source.width()).toBe(417)
+ expect(source.height()).toBe(391)
+ const sourceTransparent = countTransparentPixels(source)
+ source.delete()
+
+ const result = preprocessForVectorize(bytes, () => ck)
+ const processed = expectDefined(result, 'preprocess result')
+ expect(processed.width).toBe(417)
+ expect(processed.height).toBe(391)
+ expect(processed.pngBytes.length).toBeGreaterThan(0)
+ expect(processed.pngBytes.length).toBeLessThanOrEqual(5 * 1024 * 1024)
+ expect(sourceTransparent).toBe(0)
+ })
+})
+
+describe('resolveVectorFramePlacement', () => {
+ test('tightens the replacement frame around inset vector content', () => {
+ expect(
+ resolveVectorFramePlacement(
+ { x: 10, y: 20, width: 200, height: 100 },
+ { x: 25, y: 10, width: 150, height: 80 }
+ )
+ ).toEqual({ x: 35, y: 30, width: 150, height: 80, offsetX: 25, offsetY: 10 })
+ })
+})
+
+describe('svgToVectorPaths', () => {
+ test('accepts single-quoted SVG attributes', () => {
+ const result = svgToVectorPaths(
+ `<svg viewBox='0 0 10 10'><path d='M0 0 H10 V10 H0 Z' fill='#336699'/></svg>`,
+ { width: 20, height: 20 }
+ )
+ expect(result?.paths).toHaveLength(1)
+ expect(result?.paths[0]?.fills[0]?.type).toBe('SOLID')
+ })
+
+ test('maps multi-path vendor SVG with viewBox larger than width/height attrs', () => {
+ const svg = `<svg viewBox="0 0 1000 800" width="200" height="160" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M0 0 H1000 V800 H0 Z" fill="#336699"/>
+ <path d="M100 100 H400 V400 H100 Z" fill="#ffcc00"/>
+ <path d="M600 200 H900 V500 H600 Z" fill="#ffcc00"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 200, height: 160 })
+ expect(result?.paths.length).toBe(3)
+
+ let maxX = 0
+ let maxY = 0
+ for (const path of result?.paths ?? []) {
+ for (const vertex of path.vectorNetwork.vertices) {
+ maxX = Math.max(maxX, vertex.x)
+ maxY = Math.max(maxY, vertex.y)
+ }
+ }
+ expect(maxX).toBeCloseTo(200, 0)
+ expect(maxY).toBeCloseTo(160, 0)
+ })
+
+ test('maps viewBox paths onto target bounds', () => {
+ const svg = `<svg viewBox="0 0 100 50" xmlns="http://www.w3.org/2000/svg">
+ <path d="M0 0 H100 V50 H0 Z" fill="#336699"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 200, height: 100 })
+ expect(result?.paths.length).toBe(1)
+ const path = expectDefined(result?.paths[0], 'vector path')
+ expect(path.fills[0]?.type).toBe('SOLID')
+ const maxX = Math.max(...path.vectorNetwork.vertices.map((vertex) => vertex.x))
+ expect(maxX).toBeCloseTo(200, 0)
+ })
+
+ test('uses viewBox user units when width/height attributes differ', () => {
+ const svg = `<svg width="240" height="300" viewBox="0 0 100 125" xmlns="http://www.w3.org/2000/svg">
+ <path d="M0 0 H100 V125 H0 Z" fill="#003399"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 240, height: 300 })
+ const path = expectDefined(result?.paths[0], 'vector path')
+ const maxX = Math.max(...path.vectorNetwork.vertices.map((vertex) => vertex.x))
+ const maxY = Math.max(...path.vectorNetwork.vertices.map((vertex) => vertex.y))
+ expect(maxX).toBeCloseTo(240, 0)
+ expect(maxY).toBeCloseTo(300, 0)
+ })
+
+ test('maps viewBox with non-zero origin into target bounds', () => {
+ const svg = `<svg viewBox="50 50 100 100" xmlns="http://www.w3.org/2000/svg">
+ <path d="M50 50 H150 V150 H50 Z" fill="#336699"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 200, height: 200 })
+ const path = expectDefined(result?.paths[0], 'vector path')
+ const minX = Math.min(...path.vectorNetwork.vertices.map((vertex) => vertex.x))
+ const minY = Math.min(...path.vectorNetwork.vertices.map((vertex) => vertex.y))
+ const maxX = Math.max(...path.vectorNetwork.vertices.map((vertex) => vertex.x))
+ const maxY = Math.max(...path.vectorNetwork.vertices.map((vertex) => vertex.y))
+ expect(minX).toBeCloseTo(0, 0)
+ expect(minY).toBeCloseTo(0, 0)
+ expect(maxX).toBeCloseTo(200, 0)
+ expect(maxY).toBeCloseTo(200, 0)
+ })
+
+ test('scales cubic control points under non-uniform viewBox mapping', () => {
+ const svg = `<svg viewBox="0 0 100 200" xmlns="http://www.w3.org/2000/svg">
+ <path d="M0 100 C40 0, 60 200, 100 100" fill="#336699"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 300, height: 100 })
+ const segment = expectDefined(result?.paths[0]?.vectorNetwork.segments[0], 'cubic segment')
+ expect(segment.tangentStart.x).toBeCloseTo(120, 0)
+ expect(segment.tangentStart.y).toBeCloseTo(-50, 0)
+ expect(segment.tangentEnd.x).toBeCloseTo(-120, 0)
+ expect(segment.tangentEnd.y).toBeCloseTo(50, 0)
+ })
+
+ test('applies path transform before viewBox mapping', () => {
+ const svg = `<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
+ <path transform="translate(10, 20)" d="M0 0 H50 V50 H0 Z" fill="#336699"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 200, height: 200 })
+ const path = expectDefined(result?.paths[0], 'vector path')
+ const minX = Math.min(...path.vectorNetwork.vertices.map((vertex) => vertex.x))
+ const minY = Math.min(...path.vectorNetwork.vertices.map((vertex) => vertex.y))
+ const maxX = Math.max(...path.vectorNetwork.vertices.map((vertex) => vertex.x))
+ const maxY = Math.max(...path.vectorNetwork.vertices.map((vertex) => vertex.y))
+ expect(minX).toBeCloseTo(20, 0)
+ expect(minY).toBeCloseTo(40, 0)
+ expect(maxX).toBeCloseTo(120, 0)
+ expect(maxY).toBeCloseTo(140, 0)
+ })
+
+ test('applies non-translate transforms (scale) via svgpath', () => {
+ // scale(2) was silently ignored by the old translate/matrix-only parser.
+ const svg = `<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
+ <path transform="scale(2)" d="M0 0 H25 V25 H0 Z" fill="#336699"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 100, height: 100 })
+ const path = expectDefined(result?.paths[0], 'vector path')
+ // 25→50 in user space after scale(2), then viewBox 100→bounds 100 (1:1).
+ const maxX = Math.max(...path.vectorNetwork.vertices.map((vertex) => vertex.x))
+ const maxY = Math.max(...path.vectorNetwork.vertices.map((vertex) => vertex.y))
+ expect(maxX).toBeCloseTo(50, 0)
+ expect(maxY).toBeCloseTo(50, 0)
+ })
+
+ test('reports tight content bounds inside target bounds', () => {
+ const svg = `<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
+ <path d="M25 25 H75 V75 H25 Z" fill="#ffcc00"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 200, height: 200 })
+ const bounds = expectDefined(result?.contentBounds, 'content bounds')
+ expect(bounds.x).toBeCloseTo(50, 0)
+ expect(bounds.y).toBeCloseTo(50, 0)
+ expect(bounds.width).toBeCloseTo(100, 0)
+ expect(bounds.height).toBeCloseTo(100, 0)
+ })
+
+ test('resolves objectBoundingBox linearGradient reference to a GRADIENT_LINEAR fill', () => {
+ const svg = `<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
+ <defs>
+ <linearGradient id="g"><stop offset="0" stop-color="#000"/><stop offset="1" stop-color="#fff"/></linearGradient>
+ </defs>
+ <path d="M0 0 H10 V10 H0 Z" fill="url(#g)"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 10, height: 10 })
+ const fill = expectDefined(result?.paths[0]?.fills[0], 'gradient fill')
+ expect(fill.type).toBe('GRADIENT_LINEAR')
+ expect(fill.gradientStops?.length).toBe(2)
+ expect(fill.gradientStops?.[0]?.color.r).toBeCloseTo(0, 2)
+ expect(fill.gradientStops?.[1]?.color.r).toBeCloseTo(1, 2)
+ expect(fill.gradientTransform).toBeDefined()
+ })
+
+ test('resolves Recraft-style userSpaceOnUse gradient with two stops', () => {
+ // Mirrors Recraft vectorize output: userSpaceOnUse coords across the node box.
+ const svg = `<svg viewBox="0 0 100 100" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
+ <defs>
+ <linearGradient id="Gradient1" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="100" y2="0">
+ <stop offset="0" stop-color="#3572b0"/>
+ <stop offset="1" stop-color="#ffd43b"/>
+ </linearGradient>
+ </defs>
+ <path d="M0 0 H100 V100 H0 Z" fill="url(#Gradient1)"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 100, height: 100 })
+ const fill = expectDefined(result?.paths[0]?.fills[0], 'gradient fill')
+ expect(fill.type).toBe('GRADIENT_LINEAR')
+ expect(fill.gradientStops?.[0]?.color.b).toBeCloseTo(176 / 255, 2)
+ expect(fill.gradientStops?.[1]?.color.r).toBeCloseTo(1, 2)
+ // horizontal axis across the node box: start x≈0, end x≈1
+ const t = expectDefined(fill.gradientTransform, 'gradient transform')
+ expect(t.m02).toBeCloseTo(0, 1)
+ expect(t.m00 + t.m02).toBeCloseTo(1, 1)
+ })
+
+ test('preserves rotated radial gradient axes', () => {
+ const svg = `<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
+ <defs>
+ <radialGradient id="g" gradientUnits="userSpaceOnUse" cx="50" cy="50" r="50" gradientTransform="rotate(90 50 50)">
+ <stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#000"/>
+ </radialGradient>
+ </defs>
+ <path d="M0 0 H100 V100 H0 Z" fill="url(#g)"/>
+ </svg>`
+ const fill = expectDefined(
+ svgToVectorPaths(svg, { width: 100, height: 100 })?.paths[0]?.fills[0],
+ 'radial fill'
+ )
+ const transform = expectDefined(fill.gradientTransform, 'gradient transform')
+ expect(fill.type).toBe('GRADIENT_RADIAL')
+ expect(transform.m00).toBeCloseTo(0, 3)
+ expect(transform.m10).toBeCloseTo(0.5, 3)
+ expect(transform.m01).toBeCloseTo(-0.5, 3)
+ expect(transform.m11).toBeCloseTo(0, 3)
+ })
+
+ test('still resolves a solid color fill alongside gradients', () => {
+ const svg = `<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
+ <path d="M0 0 H10 V10 H0 Z" fill="#e1e1e1"/>
+ </svg>`
+ const result = svgToVectorPaths(svg, { width: 10, height: 10 })
+ const fill = expectDefined(result?.paths[0]?.fills[0], 'solid fill')
+ expect(fill.type).toBe('SOLID')
+ expect(fill.color.r).toBeCloseTo(225 / 255, 2)
+ })
+})
diff --git a/tests/fixtures/vectorize/euro_shield.png b/tests/fixtures/vectorize/euro_shield.png
new file mode 100644
index 000000000..cf075dc50
Binary files /dev/null and b/tests/fixtures/vectorize/euro_shield.png differ
diff --git a/tests/fixtures/vectorize/euro_shield.recraft.svg b/tests/fixtures/vectorize/euro_shield.recraft.svg
new file mode 100644
index 000000000..b076e94bd
--- /dev/null
+++ b/tests/fixtures/vectorize/euro_shield.recraft.svg
@@ -0,0 +1,16 @@
+<svg version="1.1" xmlns="http://www.w3.org/2000/svg" style="display: block;" viewBox="0 0 1639 2048" width="577" height="721" preserveAspectRatio="none">
+<path transform="translate(0,0)" fill="rgb(15,102,228)" d="M 816.274 0 L 820.956 0 C 982.455 95.5464 1122.67 159.049 1306.01 206.839 C 1366.04 222.555 1426.65 235.966 1487.7 247.042 C 1516.66 252.415 1545.72 257.213 1574.87 261.433 C 1582.72 262.559 1631.97 268.276 1636.01 271.255 C 1638.25 282.307 1637.26 341.822 1637.24 355.707 L 1637.25 542.535 C 1637.6 622.019 1637.34 701.504 1636.48 780.984 C 1635.78 832.559 1635.4 880.603 1631.11 932.328 C 1612.44 1149.17 1538.8 1357.67 1417.14 1538.14 C 1293.63 1720.89 1130.25 1873.22 939.318 1983.65 C 910.459 2000.61 881.079 2016.67 851.22 2031.81 C 842.086 2036.39 828.596 2043.59 819.395 2047.39 C 477.934 1884.65 198.277 1603.58 70.7734 1244.1 C 41.5247 1162.71 21.2844 1078.37 10.4151 992.575 C 6.81204 966.032 3.44752 939.78 2.19591 913.01 C 1.87041 906.049 1.52406 897.546 0 890.778 L 0 270.612 C 9.77725 267.822 23.0741 266.619 33.3683 265.306 C 48.6577 263.467 63.9106 261.337 79.1188 258.918 C 129.96 251.386 180.528 242.108 230.732 231.101 C 419.138 190.547 599.588 124.734 766.771 28.5238 C 783.22 19.0582 799.674 9.13022 816.274 0 z"/>
+<path transform="translate(0,0)" fill="rgb(2,79,172)" d="M 819.495 111.977 C 827.153 114.442 853.621 132.042 863.205 137.096 C 907.437 160.728 952.29 183.179 997.715 204.426 C 1068.45 237.524 1154.01 266.114 1229.17 287.506 C 1309.06 310.994 1390.36 329.392 1472.57 342.588 C 1489.54 345.33 1530 353.347 1544.97 354.054 L 1544.95 676.109 C 1544.84 752.505 1544.76 827.705 1540.23 903.502 C 1515.62 1315.32 1268.42 1689.22 912.749 1892.77 C 893.505 1903.79 840.335 1935.6 819.766 1939.11 C 800.307 1932.62 781.09 1919.93 763.32 1909.66 C 656.147 1847.73 539.318 1757.73 452.125 1669.88 C 408.588 1626.01 369.431 1578.88 332.089 1529.73 C 303.96 1492.71 276.806 1454.89 253.232 1414.74 C 244.871 1400.51 237.766 1385.5 230.085 1370.89 C 165.149 1248.99 122.28 1116.56 103.46 979.735 C 91.4784 886.969 92.8209 777.477 92.8169 683.924 L 92.7993 356.348 C 111.881 351.207 147.019 347.457 167.783 343.903 C 207.061 336.934 246.173 329.054 285.086 320.27 C 473.51 280.852 654.095 210.467 819.495 111.977 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 1076.27 1332.75 C 1080.43 1336.92 1093.7 1380.85 1096.36 1389.08 C 1117.1 1389.26 1137.85 1389.29 1158.6 1389.17 C 1143.13 1401.71 1124.45 1415 1108.27 1426.98 C 1114.97 1444.78 1121.29 1467 1127.06 1485.44 C 1110.23 1473.68 1093.49 1461.8 1076.84 1449.79 C 1060.58 1461.4 1043.36 1474.1 1026.75 1484.97 C 1030.7 1468.96 1039.63 1443.02 1045.02 1426.89 C 1028.47 1414.15 1011.47 1402.43 995.007 1389.28 L 1056.99 1389.08 C 1063.27 1370.4 1069.28 1351.12 1076.27 1332.75 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 1254.92 1154.54 C 1259.75 1160.63 1271.88 1202.02 1274.9 1211.68 L 1336.97 1212.01 C 1322.72 1223.57 1302.29 1238.07 1287.09 1248.72 C 1291.26 1265.4 1300.37 1290.14 1305.63 1308.19 C 1288.51 1297.04 1272.2 1283.62 1255 1272.05 C 1238.26 1284.15 1221.21 1296.81 1204.09 1308.28 C 1210.17 1289.47 1216.83 1267.14 1223.66 1248.89 C 1210.05 1240.13 1186.7 1222.17 1173.58 1211.95 C 1192.74 1211.43 1216.24 1211 1235.3 1211.75 C 1242.08 1193.01 1247.64 1172.98 1254.92 1154.54 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 563.148 476.6 C 566.868 479.356 580.537 525.814 583.696 534.079 C 604.442 533.961 625.19 533.979 645.936 534.133 C 629.39 546.624 612.04 559.01 595.272 571.274 C 601.908 590.921 608.274 610.657 614.369 630.479 C 598.544 620.132 579.308 605.401 563.691 594.094 C 547.212 606.071 529.509 619.388 512.705 630.638 C 519.335 611.859 526.01 590.089 531.802 570.993 L 481.488 534.17 C 502.175 533.9 523.09 534.019 543.797 533.997 C 550.692 515.67 556.312 495.46 563.148 476.6 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 818.866 1403.43 C 823.455 1407.26 836.568 1452.17 839.209 1460.47 C 859.422 1460.97 880.89 1460.88 901.144 1460.83 C 886.718 1472.76 866.813 1486.49 851.245 1497.91 C 857.665 1517.44 863.903 1537.02 869.958 1556.67 C 853.827 1546.23 835.688 1532.2 819.421 1520.92 C 804.247 1531.85 784.295 1546.96 768.845 1556.58 C 775.448 1537.92 781.77 1516.75 787.886 1497.75 C 773.155 1486.84 751.799 1472.04 738.373 1460.41 C 758.87 1460.31 779.367 1460.39 799.863 1460.65 C 806.391 1441.64 812.726 1422.57 818.866 1403.43 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 563.277 1331.75 C 567.279 1335.75 580.633 1381.31 583.196 1389.48 C 603.353 1389.95 625.606 1389.43 645.929 1389.39 C 629.956 1401.9 611.704 1414.82 595.235 1426.9 C 601.719 1446.42 608.006 1466.02 614.096 1485.67 C 597.975 1474.98 579.397 1460.92 563.541 1449.48 C 546.751 1461.9 529.781 1474.07 512.637 1486 C 519.356 1466.2 525.779 1446.29 531.904 1426.29 C 515.275 1413.79 498.404 1401.82 481.759 1389.16 C 502.524 1389.01 523.29 1389.13 544.051 1389.54 C 550.677 1370.85 556.97 1350.67 563.277 1331.75 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 818.958 408.517 C 822.83 411.544 836.768 457.859 839.19 465.397 C 859.53 465.301 880.469 465.764 900.853 465.977 C 886.53 477.632 866.384 491.55 851.156 502.728 C 857.628 522.203 863.451 541.93 870.055 561.406 C 857.065 553.874 833.041 535.472 819.72 525.836 C 813.759 528.003 776.595 556.237 768.441 561.754 C 774.498 546.137 782.717 518.794 787.359 502.425 C 772.833 490.733 753.568 477.294 738.291 465.973 C 758.731 465.675 779.171 465.493 799.612 465.427 C 806.317 448.134 812.731 426.5 818.958 408.517 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 1075.91 476.583 C 1080.63 481.912 1093.86 524.858 1096.9 534.067 L 1158.58 534.12 C 1144.27 545.812 1122.14 559.626 1109.69 571.274 C 1115.03 590.851 1121.37 611.108 1127.21 630.588 C 1110.22 619.005 1094.03 606.16 1076.85 594.507 C 1060.3 604.692 1043.47 618.88 1026.6 629.977 C 1032.24 610.349 1039.17 590.871 1044.93 571.127 L 995.022 534.121 C 1015.69 533.75 1036.32 534.491 1057.06 534.037 C 1063.76 516.409 1068.67 493.213 1075.91 476.583 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 382.681 659.386 C 387.165 661.491 400.622 707.803 403.022 715.272 L 465.069 715.968 L 414.981 752.773 C 421.574 770.423 428.057 793.258 433.603 811.476 L 383.738 775.804 C 379.321 777.175 339.831 806.721 332.66 811.57 C 338.838 791.852 345.244 772.207 351.876 752.637 L 301.982 715.664 C 321.497 714.797 344.023 715.165 363.57 715.49 C 370.124 698.247 376.559 677.182 382.681 659.386 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 382.794 1155.46 C 386.926 1157.38 400.69 1204.23 402.895 1211.46 L 464.932 1211.97 C 450.141 1223.78 430.63 1237.71 415.045 1248.73 C 421.525 1268.52 427.807 1288.37 433.887 1308.27 C 417.229 1295.9 400.4 1283.75 383.407 1271.84 C 367.259 1282.26 349.223 1296.6 332.676 1307.92 C 338.902 1288.13 345.292 1268.38 351.844 1248.69 C 339.067 1240.38 314.134 1221.53 302.233 1211.83 C 321.597 1211.51 344.62 1210.98 363.796 1211.76 C 369.918 1192.92 376.252 1174.16 382.794 1155.46 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 1325.58 905.606 C 1330.23 908.626 1343.45 953.957 1345.88 961.728 C 1366.45 961.984 1387.54 961.756 1408.15 961.766 C 1392.69 973.747 1374.11 987.63 1358.09 998.738 C 1364.52 1017.38 1371.51 1039.03 1376.86 1057.91 L 1326.68 1022.04 C 1311.61 1031.76 1291.39 1047.29 1276.37 1058.09 C 1282.03 1038.66 1288.9 1018.21 1295.07 998.838 C 1278.62 987.365 1261.56 974.476 1245.27 962.605 C 1263.15 961.241 1288.64 961.781 1306.86 961.932 L 1325.58 905.606 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 1254.04 659.23 C 1259.08 662.272 1272.07 707.161 1274.69 715.298 L 1336.8 715.955 C 1319.99 728.038 1303.3 740.281 1286.73 752.683 C 1293.31 772.256 1299.61 791.926 1305.6 811.688 C 1289.38 799.625 1272.03 787.548 1255.49 775.854 C 1251.79 776.927 1210.74 807.305 1204.49 811.599 C 1210.75 791.857 1217.15 772.164 1223.71 752.52 C 1207.23 741.082 1190.07 727.823 1173.55 715.961 C 1194.1 715.494 1214.66 715.341 1235.22 715.502 C 1241.46 699.928 1248.79 675.558 1254.04 659.23 z"/>
+<path transform="translate(0,0)" fill="rgb(254,210,15)" d="M 310.693 905.509 C 315.121 908.091 328.747 954.188 331.093 961.705 C 351.395 962.153 372.579 961.968 392.954 962.089 C 378.399 973.81 358.555 987.535 343.175 998.849 C 349.741 1018.3 355.899 1037.88 361.646 1057.59 C 345.365 1045.81 328.533 1033.24 311.867 1022.12 C 305.617 1024.98 270.929 1051.11 261.303 1057.35 C 267.987 1038.3 273.579 1018.2 280.313 998.867 C 265.041 988.68 245.583 973.391 230.429 962.209 C 250.87 961.88 271.313 961.78 291.756 961.908 C 298.352 944.362 304.765 923.498 310.693 905.509 z"/>
+</svg>
\ No newline at end of file
diff --git a/tests/fixtures/vectorize/pilot_avatar.png b/tests/fixtures/vectorize/pilot_avatar.png
new file mode 100644
index 000000000..71f776ea3
Binary files /dev/null and b/tests/fixtures/vectorize/pilot_avatar.png differ
diff --git a/tests/fixtures/vectorize/python_logo.png b/tests/fixtures/vectorize/python_logo.png
new file mode 100644
index 000000000..d18e7c33a
Binary files /dev/null and b/tests/fixtures/vectorize/python_logo.png differ
diff --git a/tests/fixtures/vectorize/sander_test_01.png b/tests/fixtures/vectorize/sander_test_01.png
new file mode 100644
index 000000000..0c50bd9fa
Binary files /dev/null and b/tests/fixtures/vectorize/sander_test_01.png differ