AI-native design editor. Open-source Figma alternative.
feat(tools): add import_svg tool
Danila Poyarkova2050a98603c
diff --git a/packages/core/src/icons/svg.ts b/packages/core/src/icons/svg.tsindex f7d2fedaf..e9d341157 100644--- a/packages/core/src/icons/svg.ts+++ b/packages/core/src/icons/svg.ts@@ -85,7 +85,7 @@ function resolveAttr(return fallback}-function extractPaths(svgBody: string): IconPathInfo[] {+export function extractPaths(svgBody: string): IconPathInfo[] {const groupAttrs = {fill: null as string | null,stroke: null as string | null,diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsindex b1f4796fb..af122542d 100644--- a/packages/core/src/tools/create.ts+++ b/packages/core/src/tools/create.ts@@ -2,4 +2,5 @@ export { createPage, createShape, createSlice } from './create/basic'export { createComponent, createInstance } from './create/components'export { fetchIconsTool, insertIcon, searchIconsTool } from './create-icons'export { render } from './create/render'+export { importSvg } from './create/svg'export { createVector } from './create/vector'diff --git a/packages/core/src/tools/create/svg.ts b/packages/core/src/tools/create/svg.tsnew file mode 100644index 000000000..533a82726--- /dev/null+++ b/packages/core/src/tools/create/svg.ts@@ -0,0 +1,145 @@+import { parseColor } from '#core/color'+import { extractPaths } from '#core/icons/svg'+import { parseSVGPath } from '#core/io/formats/svg/parse-path'+import { defineTool } from '#core/tools/schema'++import type { IconPathInfo } from '#core/icons/types'+import type { SceneNode, Stroke } from '#core/scene-graph'++const STROKE_CAP_MAP: Record<string, SceneNode['strokeCap']> = {+ butt: 'NONE',+ round: 'ROUND',+ square: 'SQUARE'+}++const STROKE_JOIN_MAP: Record<string, SceneNode['strokeJoin']> = {+ miter: 'MITER',+ round: 'ROUND',+ bevel: 'BEVEL'+}++import type { Rect } from '#core/types'++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 = 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,+ width: number,+ height: number,+ parentId: string,+ defaultColor: string+) {+ const vectorNetwork = parseSVGPath(path.d, path.fillRule)+ const vector = figma.graph.createNode('VECTOR', parentId, {+ name: 'path',+ width,+ height,+ vectorNetwork+ })+ vector.x = 0+ vector.y = 0++ if (path.fill && path.fill !== 'none') {+ const fillColor =+ path.fill === 'currentColor' ? parseColor(defaultColor) : parseColor(path.fill)+ figma.graph.updateNode(vector.id, {+ fills: [{ type: 'SOLID', color: fillColor, opacity: 1, visible: true }]+ })+ } else if (path.fill === null && !path.stroke) {+ const fillColor = parseColor(defaultColor)+ figma.graph.updateNode(vector.id, {+ fills: [{ type: 'SOLID', color: fillColor, opacity: 1, visible: true }]+ })+ } else {+ figma.graph.updateNode(vector.id, { fills: [] })+ }++ if (path.stroke && path.stroke !== 'none') {+ const strokeColor =+ path.stroke === 'currentColor' ? parseColor(defaultColor) : parseColor(path.stroke)+ const stroke: Stroke = {+ color: strokeColor,+ weight: path.strokeWidth,+ opacity: 1,+ visible: true,+ align: 'CENTER',+ cap: STROKE_CAP_MAP[path.strokeCap] ?? 'NONE',+ join: STROKE_JOIN_MAP[path.strokeJoin] ?? 'MITER'+ }+ figma.graph.updateNode(vector.id, { strokes: [stroke] })+ }++ return vector+}++export const importSvg = defineTool({+ name: 'import_svg',+ mutates: true,+ description:+ 'Import raw SVG markup onto the canvas. Parses <path>, <circle>, <ellipse>, <rect>, <line>, <polygon>, <polyline> elements and creates vector nodes. Supports fill, stroke, stroke-width, viewBox sizing.',+ params: {+ svg: {+ type: 'string',+ description: 'SVG markup string (e.g. \'<svg viewBox="0 0 24 24"><path d="M..."/></svg>\')',+ required: true+ },+ name: { type: 'string', description: 'Name for the created frame (default: "SVG")' },+ color: {+ type: 'color',+ description: 'Default color for currentColor fills/strokes (default: #000000)'+ },+ parent_id: { type: 'string', description: 'Parent node ID' },+ x: { type: 'number', description: 'X position' },+ y: { type: 'number', description: 'Y position' }+ },+ execute: async (figma, args) => {+ const svg = args.svg+ if (!svg || typeof svg !== 'string') return { error: 'svg parameter is required' }++ const paths = extractPaths(svg)+ if (paths.length === 0) return { error: 'No supported SVG elements found in the markup' }++ const { width, height } = parseSvgSize(svg)+ const defaultColor = args.color ?? '#000000'+ const parentId = args.parent_id ?? figma.currentPage.id++ const frame = figma.graph.createNode('FRAME', parentId, {+ name: args.name ?? 'SVG',+ width,+ height,+ fills: []+ })++ if (args.x !== undefined) frame.x = args.x+ if (args.y !== undefined) frame.y = args.y++ for (const path of paths) {+ createVectorFromPath(figma, path, width, height, frame.id, defaultColor)+ }++ return { id: frame.id, name: frame.name, type: frame.type }+ }+})diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex f0db6dcd2..88cada854 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -7,3 +7,4 @@ export { toolsToAI, buildDebugLog } from './ai-adapter'export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './ai-adapter'export { calcClusterConfidence } from './analyze'export { setPexelsApiKey, setUnsplashAccessKey } from './stock-photo'+export { importSvg } from './create'diff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.tsindex 3ec2457bd..0eb63f590 100644--- a/packages/core/src/tools/registry-extended.ts+++ b/packages/core/src/tools/registry-extended.ts@@ -15,6 +15,7 @@ import {createSlice,createVector,fetchIconsTool,+ importSvg,insertIcon,searchIconsTool} from './create'@@ -120,6 +121,7 @@ export const EXTENDED_TOOLS: ToolDef[] = [createPage,createVector,createSlice,+ importSvg,// Modify (advanced)setEffects,setOpacity,diff --git a/tests/engine/import-svg.test.ts b/tests/engine/import-svg.test.tsnew file mode 100644index 000000000..69496eafc--- /dev/null+++ b/tests/engine/import-svg.test.ts@@ -0,0 +1,148 @@+import { describe, test, expect, beforeEach } from 'bun:test'++import { FigmaAPI, SceneGraph } from '@open-pencil/core'+import { importSvg } from '@open-pencil/core/tools'++let graph: SceneGraph+let figma: FigmaAPI++beforeEach(() => {+ graph = new SceneGraph()+ figma = new FigmaAPI(graph)+})++describe('import_svg', () => {+ test('imports a simple path', async () => {+ const result = (await importSvg.execute(figma, {+ svg: '<svg viewBox="0 0 24 24"><path d="M12 2L2 22h20Z"/></svg>'+ })) as { id: string; name: string; type: string }++ expect(result.id).toBeDefined()+ expect(result.type).toBe('FRAME')++ const frame = graph.getNode(result.id)+ expect(frame).not.toBeUndefined()+ expect(frame!.width).toBe(24)+ expect(frame!.height).toBe(24)++ const children = graph.getChildren(result.id)+ expect(children.length).toBe(1)+ expect(children[0].type).toBe('VECTOR')+ expect(children[0].vectorNetwork).toBeDefined()+ expect(children[0].vectorNetwork!.vertices.length).toBeGreaterThan(0)+ })++ test('imports multiple shapes', async () => {+ const result = (await importSvg.execute(figma, {+ svg: `<svg viewBox="0 0 100 100">+ <rect x="10" y="10" width="30" height="30"/>+ <circle cx="70" cy="30" r="20"/>+ <path d="M10 70 L90 70"/>+ </svg>`+ })) as { id: string }++ const children = graph.getChildren(result.id)+ expect(children.length).toBe(3)+ expect(children.every((c) => c.type === 'VECTOR')).toBe(true)+ })++ test('respects viewBox dimensions', async () => {+ const result = (await importSvg.execute(figma, {+ svg: '<svg viewBox="0 0 200 100"><path d="M0 0 L200 100"/></svg>'+ })) as { id: string }++ const frame = graph.getNode(result.id)+ expect(frame!.width).toBe(200)+ expect(frame!.height).toBe(100)+ })++ test('uses width/height attributes when no viewBox', async () => {+ const result = (await importSvg.execute(figma, {+ svg: '<svg width="48" height="48"><path d="M0 0 L48 48"/></svg>'+ })) as { id: string }++ const frame = graph.getNode(result.id)+ expect(frame!.width).toBe(48)+ expect(frame!.height).toBe(48)+ })++ test('sets custom name', async () => {+ const result = (await importSvg.execute(figma, {+ svg: '<svg viewBox="0 0 24 24"><path d="M0 0 L24 24"/></svg>',+ name: 'Arrow'+ })) as { id: string; name: string }++ expect(result.name).toBe('Arrow')+ })++ test('applies fill color', async () => {+ const result = (await importSvg.execute(figma, {+ svg: '<svg viewBox="0 0 24 24"><path d="M0 0 L24 24" fill="#FF0000"/></svg>'+ })) as { id: string }++ const children = graph.getChildren(result.id)+ expect(children[0].fills.length).toBe(1)+ expect(children[0].fills[0].color.r).toBeCloseTo(1, 1)+ expect(children[0].fills[0].color.g).toBeCloseTo(0, 1)+ })++ test('applies stroke', async () => {+ const result = (await importSvg.execute(figma, {+ svg: '<svg viewBox="0 0 24 24"><path d="M0 0 L24 24" fill="none" stroke="#00FF00" stroke-width="2"/></svg>'+ })) as { id: string }++ const children = graph.getChildren(result.id)+ expect(children[0].fills.length).toBe(0)+ expect(children[0].strokes.length).toBe(1)+ expect(children[0].strokes[0].color.g).toBeCloseTo(1, 1)+ expect(children[0].strokes[0].weight).toBe(2)+ })++ test('uses currentColor with custom color arg', async () => {+ const result = (await importSvg.execute(figma, {+ svg: '<svg viewBox="0 0 24 24"><path d="M0 0 L24 24" fill="currentColor"/></svg>',+ color: '#0000FF'+ })) as { id: string }++ const children = graph.getChildren(result.id)+ expect(children[0].fills[0].color.b).toBeCloseTo(1, 1)+ expect(children[0].fills[0].color.r).toBeCloseTo(0, 1)+ })++ test('sets position', async () => {+ const result = (await importSvg.execute(figma, {+ svg: '<svg viewBox="0 0 24 24"><path d="M0 0 L24 24"/></svg>',+ x: 100,+ y: 200+ })) as { id: string }++ const frame = graph.getNode(result.id)+ expect(frame!.x).toBe(100)+ expect(frame!.y).toBe(200)+ })++ test('returns error for empty SVG', async () => {+ const result = (await importSvg.execute(figma, {+ svg: '<svg viewBox="0 0 24 24"></svg>'+ })) as { error: string }++ expect(result.error).toContain('No supported SVG elements')+ })++ test('returns error for missing svg param', async () => {+ const result = (await importSvg.execute(figma, {})) as { error: string }+ expect(result.error).toContain('required')+ })++ test('handles polygon and polyline', async () => {+ const result = (await importSvg.execute(figma, {+ svg: `<svg viewBox="0 0 100 100">+ <polygon points="50,5 95,97 5,97"/>+ <polyline points="10,10 40,40 70,10"/>+ </svg>`+ })) as { id: string }++ const children = graph.getChildren(result.id)+ expect(children.length).toBe(2)+ })+})