Skip to content

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

feat(svg): import SVG text and add figma.createNodeFromSvg (#1032)

Danila Poyarkova0d445988971
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3a3eb2b78..6b72ae0ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,7 @@
### Breaking changes
- The app renders `render` JSX itself and no longer accepts the pre-rendered tree that earlier versions of `openpencil-mcp` send, so an older `openpencil-mcp` fails to render into this app version; update it with the app.
-- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.
+- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGVectorizeResult` adds `texts`, the SVG's text placed in the target space, and `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.
- `SceneNode` from `@open-pencil/scene-graph` has `isExposedInstance`, whether an instance inside a component shows its properties on instances of that component, so code that builds `SceneNode` objects itself must include it. In the plugin API, `isExposedInstance` and `exposedInstances` follow that flag and Figma's rules instead of treating an instance whose swap is bound to a property as exposed: only an instance in a component's own layers whose component has properties can be exposed, and its copies in instances report it but cannot change it.
- `usePosition` from `@open-pencil/vue` reports and edits `x`, `y`, and `rotation` as Figma's properties panel does: the turned layer's box on the canvas, measured from its frame or page, and its counterclockwise angle. `getDefaultCanvasBgColor` and `CANVAS_BG_COLOR_DARK` are removed from `@open-pencil/core/constants`; new pages use `PAGE_DEFAULT_BACKGROUNDS`, keyed by interface theme.
- `SkiaRenderer.hitTestFrameTitle` no longer takes the selected IDs: it finds the name of any frame on the page or in a section under a point, selected or not.
@@ -81,6 +81,7 @@
- Preview designs progressively on the canvas as direct AI providers stream JSX, without saving partial designs or adding intermediate undo steps. A preview stays with its page: it hides while you view another page and returns when you come back.
- Write design trees as TSX with `@open-pencil/design-jsx` as the JSX import source, and render them with `renderTree`.
- Swap the component behind an instance with `instance.swapComponent(component)` in the plugin API, as in Figma.
+- Import SVG markup with `figma.createNodeFromSvg(svg)` in the plugin API, as in Figma: it builds the same layers as pasting the SVG, on the current page at its origin.
- Detach an instance from its component with `detachInstance()` in the plugin API, as in Figma, from scripts run through `eval`.
- Run scripts written for Figma's dynamic-page mode that call `figma.getNodeByIdAsync()` or `getMainComponentAsync()`; both resolve to the same nodes as their synchronous forms.
- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, titled by the document and, when several have components, its page, with a story and `select` controls per variant (a component with a behaviour gets boolean `checked`, `pressed`, `open`, and `disabled` controls instead, and each interaction state stays a story; with `--framework vue` or `--framework react`, a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea becomes a Reka UI or Radix UI component whose variants are compiled into state styles and whose text properties are string props with a text control, tabs and groups choosing a value named after each tab's or item's label, sliders, progress bars, and number fields binding a number within their range, text fields and textareas binding their text as a native input or textarea with the design's placeholder and filled look (React's number field is a native number input with its steppers wired, since Radix has none), each tab's trigger drawn with the chosen tab's look while it is active, and groups writing an item component they use once per item with the words each item shows; inside it, an instance of another generated component uses that component, also where a state draws it in place of another layer, operable from the value the design draws, and an icon is an `@iconify/vue` or `@iconify/react` component; with stories whose play function operates it), a design image per variant, and an `openpencil://` link that opens the variant in OpenPencil. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).
@@ -97,7 +98,7 @@
### Changed
-- Import SVG as editable layers, as pasting it into Figma does, from `import_svg`, dropped files, and pasted markup ([#734](https://github.com/open-pencil/open-pencil/issues/734)). Each `<g>` becomes a group and each shape its own vector, named after its `id`, element opacity is kept, and clipped content sits in a clip path group whose mask is drawn from the clip's shapes. The imported frame is white, clips its content, and is named after the root `<svg>` `id`; an SVG without a size imports as a group. Shapes are no longer merged into one multi-color vector.
+- Import SVG as editable layers, as pasting it into Figma does, from `import_svg`, dropped files, and pasted markup ([#734](https://github.com/open-pencil/open-pencil/issues/734)). Each `<g>` becomes a group, each shape its own vector, and each `<text>` a text layer with its fonts, `<tspan>` styles, alignment, and rotation, named after its `id`, element opacity is kept, and clipped content sits in a clip path group whose mask is drawn from the clip's shapes. The imported frame is white, clips its content, and is named after the root `<svg>` `id`; an SVG without a size imports as a group. Shapes are no longer merged into one multi-color vector.
- With **Snap to Pixel Grid** on, moved layers and resized edges land on whole pixels at any zoom, and drawn layers start and end on whole pixels, as in Figma; zoomed in, moves and resizes could leave fractions before, and drawing was not snapped.
- Layers inside components and instances are outlined in purple when hovered or selected, with a purple size label, as in Figma; they were blue.
- The properties panel's variable picker groups variables by collection and shows each color variable's swatch, and the variables dialog points a value at another variable with the same picker, detaching it from the picker's footer.
diff --git a/packages/core/src/editor/clipboard/assets.ts b/packages/core/src/editor/clipboard/assets.ts
index c05ebf5e9..1ca45be0f 100644
--- a/packages/core/src/editor/clipboard/assets.ts
+++ b/packages/core/src/editor/clipboard/assets.ts
@@ -10,6 +10,7 @@ import {
createSVGNodesFromImport,
isSVGMarkup,
prepareSVGImport,
+ svgImportFonts,
type SVGImportData
} from '#core/io/formats/svg'
import { computeAllLayouts } from '#core/layout'
@@ -172,23 +173,31 @@ export function createClipboardAssetActions(
return true
}
+ /** Load the fonts of imported SVG text, so it is measured and placed with them. */
+ async function loadSVGFonts(assets: PreparedAsset[]) {
+ const fonts = assets.flatMap((asset) =>
+ asset.kind === 'svg' ? svgImportFonts(asset.data) : []
+ )
+ await Promise.all(
+ fonts.map((font) => ctx.loadFont(font.family, font.style, font.characters).catch(() => null))
+ )
+ }
+
async function placeFiles(files: File[], cx: number, cy: number) {
const prepared = (await Promise.all(files.map(prepareAsset))).filter(
(asset): asset is PreparedAsset => asset !== null
)
+ await loadSVGFonts(prepared)
placeAssets(prepared, cx, cy, 'Place files')
}
/** Paste SVG markup as layers, as Figma does; false when the text is not SVG. */
- function pasteSVG(markup: string, cx: number, cy: number): boolean {
+ async function pasteSVG(markup: string, cx: number, cy: number): Promise<boolean> {
const data = isSVGMarkup(markup) ? prepareSVGImport(markup) : null
if (!data) return false
- return placeAssets(
- [{ kind: 'svg', data, width: data.width, height: data.height }],
- cx,
- cy,
- 'Paste SVG'
- )
+ const asset: PreparedAsset = { kind: 'svg', data, width: data.width, height: data.height }
+ await loadSVGFonts([asset])
+ return placeAssets([asset], cx, cy, 'Paste SVG')
}
function placeImageFiles(files: File[], cx: number, cy: number) {
diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.ts
index 9096784db..01d8fec59 100644
--- a/packages/core/src/figma-api/compatibility.ts
+++ b/packages/core/src/figma-api/compatibility.ts
@@ -25,6 +25,7 @@ export type SupportedPluginAPI = Pick<
| 'createEllipse'
| 'createFrame'
| 'createLine'
+ | 'createNodeFromSvg'
| 'createPolygon'
| 'createRectangle'
| 'createSection'
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 97738cad3..9c26e515b 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -27,6 +27,7 @@ import { textAutoResizeChanges } from '#core/editor/text/auto-resize'
import { setDefaultPageBackground } from '#core/figma-api/page-backgrounds'
import { iconify, type IconProvider } from '#core/icons'
import type { RasterCodec } from '#core/io/formats/raster'
+import { createSVGNodes } from '#core/io/formats/svg'
import { reconcileVariableLayouts } from '#core/layout/variables'
import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/status'
@@ -214,6 +215,14 @@ export class FigmaAPI implements NodeProxyHost {
return this._createNode('VECTOR') as FigmaVectorNode
}
+ /** The layers Figma makes from SVG markup, on the current page at its origin. */
+ // eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Figma Plugin API name.
+ createNodeFromSvg(svg: string): FigmaFrameNode {
+ const node = createSVGNodes(this.graph, this._currentPageId, svg, { keepEmpty: true })
+ if (!node) throw new Error('in createNodeFromSvg: Failed to convert SVG file')
+ return this.wrapNode(node.id) as FigmaFrameNode
+ }
+
createComponent(): FigmaComponentNode {
return this._createNode('COMPONENT') as FigmaComponentNode
}
diff --git a/packages/core/src/icons/svg.ts b/packages/core/src/icons/svg.ts
index 6317b1815..3fac97502 100644
--- a/packages/core/src/icons/svg.ts
+++ b/packages/core/src/icons/svg.ts
@@ -1,10 +1,5 @@
import { iconToSVG } from '@iconify/utils'
-import {
- DOMImplementation,
- type Document as XMLDocument,
- type Element,
- type Node
-} from '@xmldom/xmldom'
+import { DOMImplementation, type Document as XMLDocument, type Element } from '@xmldom/xmldom'
import svgpath from 'svgpath'
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
@@ -12,12 +7,24 @@ import type { Vector } from '@open-pencil/scene-graph/primitives'
import { parseSVGFragment } from '#core/io/formats/svg/document'
+import {
+ combinedTransform,
+ DEFAULT_PRESENTATION,
+ isElement,
+ normalizeSVGPaint,
+ num,
+ opacityValue,
+ presentationFor
+} from './svg/presentation'
+import { elementLayer, type Scope, type Traversal } from './svg/scope'
+import { textInfo } from './svg/text'
import type {
IconData,
IconifyIconEntry,
IconPathInfo,
SVGClipPathRegion,
- SVGElementLayer
+ SVGElementLayer,
+ SVGTextInfo
} from './types'
interface SVGElementInput {
@@ -36,92 +43,9 @@ const JSX_ATTRIBUTE_NAMES: Readonly<Record<string, string>> = {
xlinkHref: 'xlink:href'
}
-interface PresentationAttributes {
- fill: string
- stroke: string
- strokeWidth: string
- strokeCap: string
- strokeJoin: string
- fillRule: string
- fillOpacity: string
- strokeOpacity: string
-}
-
-const DEFAULT_PRESENTATION: PresentationAttributes = {
- fill: 'currentColor',
- stroke: 'none',
- strokeWidth: '1',
- strokeCap: 'butt',
- strokeJoin: 'miter',
- fillRule: 'nonzero',
- fillOpacity: '1',
- strokeOpacity: '1'
-}
-
const SHAPE_NAMES = new Set(['path', 'circle', 'ellipse', 'rect', 'line', 'polygon', 'polyline'])
const NON_RENDERED_CONTAINERS = new Set(['defs', 'clipPath', 'mask', 'symbol'])
-function isElement(node: Node): node is Element {
- return node.nodeType === node.ELEMENT_NODE
-}
-
-function inlineStyles(element: Element): ReadonlyMap<string, string> {
- const styles = new Map<string, string>()
- for (const declaration of (element.getAttribute('style') ?? '').split(';')) {
- const separator = declaration.indexOf(':')
- if (separator <= 0) continue
- const name = declaration.slice(0, separator).trim()
- const value = declaration.slice(separator + 1).trim()
- if (name && value) styles.set(name, value)
- }
- return styles
-}
-
-function inheritedAttribute(
- element: Element,
- styles: ReadonlyMap<string, string>,
- name: string,
- inherited: string
-): string {
- return (
- styles.get(name) ??
- (element.hasAttribute(name) ? (element.getAttribute(name) ?? inherited) : inherited)
- )
-}
-
-function presentationFor(
- element: Element,
- inherited: PresentationAttributes
-): PresentationAttributes {
- const styles = inlineStyles(element)
- return {
- fill: inheritedAttribute(element, styles, 'fill', inherited.fill),
- stroke: inheritedAttribute(element, styles, 'stroke', inherited.stroke),
- strokeWidth: inheritedAttribute(element, styles, 'stroke-width', inherited.strokeWidth),
- strokeCap: inheritedAttribute(element, styles, 'stroke-linecap', inherited.strokeCap),
- strokeJoin: inheritedAttribute(element, styles, 'stroke-linejoin', inherited.strokeJoin),
- fillRule: inheritedAttribute(element, styles, 'fill-rule', inherited.fillRule),
- fillOpacity: inheritedAttribute(element, styles, 'fill-opacity', inherited.fillOpacity),
- strokeOpacity: inheritedAttribute(element, styles, 'stroke-opacity', inherited.strokeOpacity)
- }
-}
-
-/** An SVG opacity, a number or a percentage, clamped to 0–1. */
-function opacityValue(value: string | null | undefined): number {
- if (!value) return 1
- const parsed = Number.parseFloat(value)
- if (!Number.isFinite(parsed)) return 1
- const opacity = value.trim().endsWith('%') ? parsed / 100 : parsed
- return Math.min(1, Math.max(0, opacity))
-}
-
-function num(element: Element, attr: string, fallback = 0): number {
- const value = element.getAttribute(attr)
- if (value === null) return fallback
- const parsed = Number.parseFloat(value)
- return Number.isFinite(parsed) ? parsed : fallback
-}
-
function circleToD(element: Element): string | null {
const cx = num(element, 'cx')
const cy = num(element, 'cy')
@@ -191,49 +115,6 @@ function shapeToD(tagName: string, element: Element): string | null {
}
}
-function combinedTransform(parent: string | null, element: Element): string | null {
- const current = element.getAttribute('transform')
- if (parent && current) return `${parent} ${current}`
- return current ?? parent
-}
-
-function normalizeSVGPaint(value: string | null): string | null {
- return value?.trim().toLowerCase() === 'none' ? null : value
-}
-
-interface Traversal {
- root: Element
- elementsById: ReadonlyMap<string, Element>
- nextKey: number
-}
-
-/** What an element inherits from the elements around it. */
-interface Scope {
- presentation: PresentationAttributes
- transform: string | null
- clipPaths: SVGClipPathRegion[]
- elements: SVGElementLayer[]
- useStack: ReadonlySet<Element>
- /** Drawn through `<use>` or inside a `<clipPath>`, so ids name the source, not this copy. */
- referenced: boolean
-}
-
-function elementLayer(
- traversal: Traversal,
- element: Element,
- kind: SVGElementLayer['kind'],
- scope: Pick<Scope, 'referenced'>,
- clip: number | null
-): SVGElementLayer {
- return {
- key: traversal.nextKey++,
- kind,
- name: scope.referenced ? null : element.getAttribute('id') || null,
- opacity: opacityValue(inlineStyles(element).get('opacity') ?? element.getAttribute('opacity')),
- clip
- }
-}
-
function appendShapePath(
tagName: string,
element: Element,
@@ -337,6 +218,14 @@ function collectPaths(
clipPaths
}
+ if (tagName === 'text') {
+ const text = textInfo(element, scope, result.length)
+ if (text) {
+ const layer = elementLayer(traversal, element, 'shape', scope, clip)
+ traversal.texts.push({ ...text, elements: [...scope.elements, layer] })
+ }
+ return
+ }
if (SHAPE_NAMES.has(tagName)) {
appendShapePath(
tagName,
@@ -378,13 +267,20 @@ function appendSVGElement(svgDocument: XMLDocument, parent: Element, input: SVGE
parent.appendChild(element)
}
-function collectDocumentPaths(root: Element): IconPathInfo[] {
+/** The shapes and text an SVG draws, in drawing order. */
+export interface SVGContent {
+ paths: IconPathInfo[]
+ texts: SVGTextInfo[]
+}
+
+function collectDocument(root: Element): SVGContent {
const elementsById = new Map<string, Element>()
for (const element of Array.from(root.getElementsByTagName('*'))) {
const id = element.getAttribute('id')
if (id) elementsById.set(id, element)
}
- const result: IconPathInfo[] = []
+ const paths: IconPathInfo[] = []
+ const traversal: Traversal = { root, elementsById, nextKey: 0, texts: [] }
collectPaths(
root,
{
@@ -395,10 +291,10 @@ function collectDocumentPaths(root: Element): IconPathInfo[] {
useStack: new Set(),
referenced: false
},
- { root, elementsById, nextKey: 0 },
- result
+ traversal,
+ paths
)
- return result
+ return { paths, texts: traversal.texts }
}
export function extractPathsFromElements(
@@ -409,12 +305,16 @@ export function extractPathsFromElements(
const root = svgDocument.documentElement
if (!root) return []
appendSVGElement(svgDocument, root, { type: 'svg', props: rootProps, children: elements })
- return collectDocumentPaths(root)
+ return collectDocument(root).paths
}
-export function extractPaths(svgBody: string): IconPathInfo[] {
+export function extractSVGContent(svgBody: string): SVGContent {
const root = parseSVGFragment(svgBody)?.documentElement
- return root ? collectDocumentPaths(root) : []
+ return root ? collectDocument(root) : { paths: [], texts: [] }
+}
+
+export function extractPaths(svgBody: string): IconPathInfo[] {
+ return extractSVGContent(svgBody).paths
}
export function buildIconData(
diff --git a/packages/core/src/icons/svg/presentation.ts b/packages/core/src/icons/svg/presentation.ts
new file mode 100644
index 000000000..131f9d630
--- /dev/null
+++ b/packages/core/src/icons/svg/presentation.ts
@@ -0,0 +1,118 @@
+import type { Element, Node } from '@xmldom/xmldom'
+
+/** SVG presentation attributes as an element inherits them, still as source strings. */
+export interface PresentationAttributes {
+ fill: string
+ stroke: string
+ strokeWidth: string
+ strokeCap: string
+ strokeJoin: string
+ fillRule: string
+ fillOpacity: string
+ strokeOpacity: string
+ fontFamily: string
+ fontSize: string
+ fontWeight: string
+ fontStyle: string
+ textAnchor: string
+ letterSpacing: string
+ textDecoration: string
+}
+
+export const DEFAULT_PRESENTATION: PresentationAttributes = {
+ fill: 'currentColor',
+ stroke: 'none',
+ strokeWidth: '1',
+ strokeCap: 'butt',
+ strokeJoin: 'miter',
+ fillRule: 'nonzero',
+ fillOpacity: '1',
+ strokeOpacity: '1',
+ fontFamily: '',
+ fontSize: '',
+ fontWeight: 'normal',
+ fontStyle: 'normal',
+ textAnchor: 'start',
+ letterSpacing: 'normal',
+ textDecoration: 'none'
+}
+
+export function isElement(node: Node): node is Element {
+ return node.nodeType === node.ELEMENT_NODE
+}
+
+export function inlineStyles(element: Element): ReadonlyMap<string, string> {
+ const styles = new Map<string, string>()
+ for (const declaration of (element.getAttribute('style') ?? '').split(';')) {
+ const separator = declaration.indexOf(':')
+ if (separator <= 0) continue
+ const name = declaration.slice(0, separator).trim()
+ const value = declaration.slice(separator + 1).trim()
+ if (name && value) styles.set(name, value)
+ }
+ return styles
+}
+
+function inheritedAttribute(
+ element: Element,
+ styles: ReadonlyMap<string, string>,
+ name: string,
+ inherited: string
+): string {
+ return (
+ styles.get(name) ??
+ (element.hasAttribute(name) ? (element.getAttribute(name) ?? inherited) : inherited)
+ )
+}
+
+export function presentationFor(
+ element: Element,
+ inherited: PresentationAttributes
+): PresentationAttributes {
+ const styles = inlineStyles(element)
+ const attribute = (name: string, value: string) =>
+ inheritedAttribute(element, styles, name, value)
+ return {
+ fill: attribute('fill', inherited.fill),
+ stroke: attribute('stroke', inherited.stroke),
+ strokeWidth: attribute('stroke-width', inherited.strokeWidth),
+ strokeCap: attribute('stroke-linecap', inherited.strokeCap),
+ strokeJoin: attribute('stroke-linejoin', inherited.strokeJoin),
+ fillRule: attribute('fill-rule', inherited.fillRule),
+ fillOpacity: attribute('fill-opacity', inherited.fillOpacity),
+ strokeOpacity: attribute('stroke-opacity', inherited.strokeOpacity),
+ fontFamily: attribute('font-family', inherited.fontFamily),
+ fontSize: attribute('font-size', inherited.fontSize),
+ fontWeight: attribute('font-weight', inherited.fontWeight),
+ fontStyle: attribute('font-style', inherited.fontStyle),
+ textAnchor: attribute('text-anchor', inherited.textAnchor),
+ letterSpacing: attribute('letter-spacing', inherited.letterSpacing),
+ textDecoration: attribute('text-decoration', inherited.textDecoration)
+ }
+}
+
+/** An SVG opacity, a number or a percentage, clamped to 0–1. */
+export function opacityValue(value: string | null | undefined): number {
+ if (!value) return 1
+ const parsed = Number.parseFloat(value)
+ if (!Number.isFinite(parsed)) return 1
+ const opacity = value.trim().endsWith('%') ? parsed / 100 : parsed
+ return Math.min(1, Math.max(0, opacity))
+}
+
+export function num(element: Element, attr: string, fallback = 0): number {
+ const value = element.getAttribute(attr)
+ if (value === null) return fallback
+ const parsed = Number.parseFloat(value)
+ return Number.isFinite(parsed) ? parsed : fallback
+}
+
+export function normalizeSVGPaint(value: string | null): string | null {
+ return value?.trim().toLowerCase() === 'none' ? null : value
+}
+
+export function combinedTransform(parent: string | null, element: Element): string | null {
+ const current = element.getAttribute('transform')
+ if (parent && current) return `${parent} ${current}`
+ return current ?? parent
+}
diff --git a/packages/core/src/icons/svg/scope.ts b/packages/core/src/icons/svg/scope.ts
new file mode 100644
index 000000000..08b63db7b
--- /dev/null
+++ b/packages/core/src/icons/svg/scope.ts
@@ -0,0 +1,40 @@
+import type { Element } from '@xmldom/xmldom'
+
+import type { SVGClipPathRegion, SVGElementLayer, SVGTextInfo } from '#core/icons/types'
+
+import { inlineStyles, opacityValue, type PresentationAttributes } from './presentation'
+
+export interface Traversal {
+ root: Element
+ elementsById: ReadonlyMap<string, Element>
+ nextKey: number
+ /** `<text>` elements in drawing order; each records how many paths precede it. */
+ texts: SVGTextInfo[]
+}
+
+/** What an element inherits from the elements around it. */
+export interface Scope {
+ presentation: PresentationAttributes
+ transform: string | null
+ clipPaths: SVGClipPathRegion[]
+ elements: SVGElementLayer[]
+ useStack: ReadonlySet<Element>
+ /** Drawn through `<use>` or inside a `<clipPath>`, so ids name the source, not this copy. */
+ referenced: boolean
+}
+
+export function elementLayer(
+ traversal: Traversal,
+ element: Element,
+ kind: SVGElementLayer['kind'],
+ scope: Pick<Scope, 'referenced'>,
+ clip: number | null
+): SVGElementLayer {
+ return {
+ key: traversal.nextKey++,
+ kind,
+ name: scope.referenced ? null : element.getAttribute('id') || null,
+ opacity: opacityValue(inlineStyles(element).get('opacity') ?? element.getAttribute('opacity')),
+ clip
+ }
+}
diff --git a/packages/core/src/icons/svg/text.ts b/packages/core/src/icons/svg/text.ts
new file mode 100644
index 000000000..423f9f345
--- /dev/null
+++ b/packages/core/src/icons/svg/text.ts
@@ -0,0 +1,139 @@
+import type { Element, Node } from '@xmldom/xmldom'
+
+import type { SVGTextInfo, SVGTextPiece, SVGTextRun } from '#core/icons/types'
+
+import {
+ isElement,
+ normalizeSVGPaint,
+ num,
+ opacityValue,
+ presentationFor,
+ type PresentationAttributes
+} from './presentation'
+import type { Scope } from './scope'
+
+/** Figma draws SVG text without a size at 12px. */
+const DEFAULT_FONT_SIZE = 12
+const GENERIC_FAMILIES = new Set([
+ 'serif',
+ 'sans-serif',
+ 'monospace',
+ 'cursive',
+ 'fantasy',
+ 'system-ui',
+ 'ui-sans-serif',
+ 'ui-serif',
+ 'ui-monospace'
+])
+/**
+ * Attributes that start a new layer. A `dx` alone shifts from where the text so far ends, which
+ * only layout knows, so such a `<tspan>` stays in its layer as a style run.
+ */
+const MOVES = ['x', 'y', 'dy']
+
+function fontFamily(value: string): string | null {
+ for (const entry of value.split(',')) {
+ const family = entry.trim().replace(/^['"]|['"]$/g, '')
+ if (family && !GENERIC_FAMILIES.has(family.toLowerCase())) return family
+ }
+ return null
+}
+
+function fontWeight(value: string): number {
+ const keyword = value.trim().toLowerCase()
+ if (keyword === 'bold' || keyword === 'bolder') return 700
+ if (keyword === 'lighter') return 300
+ const parsed = Number.parseFloat(keyword)
+ return Number.isFinite(parsed) ? parsed : 400
+}
+
+function textDecoration(value: string): SVGTextRun['textDecoration'] {
+ const decoration = value.toLowerCase()
+ if (decoration.includes('underline')) return 'UNDERLINE'
+ if (decoration.includes('line-through')) return 'STRIKETHROUGH'
+ return 'NONE'
+}
+
+function textRun(text: string, presentation: PresentationAttributes): SVGTextRun {
+ const size = Number.parseFloat(presentation.fontSize)
+ const spacing = Number.parseFloat(presentation.letterSpacing)
+ return {
+ text,
+ fill: normalizeSVGPaint(presentation.fill),
+ fillOpacity: opacityValue(presentation.fillOpacity),
+ fontFamily: fontFamily(presentation.fontFamily),
+ fontSize: Number.isFinite(size) && size > 0 ? size : DEFAULT_FONT_SIZE,
+ fontWeight: fontWeight(presentation.fontWeight),
+ italic: /italic|oblique/i.test(presentation.fontStyle),
+ letterSpacing: Number.isFinite(spacing) ? spacing : 0,
+ textDecoration: textDecoration(presentation.textDecoration)
+ }
+}
+
+function anchor(presentation: PresentationAttributes): SVGTextPiece['anchor'] {
+ const value = presentation.textAnchor.trim()
+ return value === 'middle' || value === 'end' ? value : 'start'
+}
+
+/** Collapse whitespace as SVG does by default: runs of it become one space, trimmed at the ends. */
+function collapseWhitespace(piece: SVGTextPiece): SVGTextPiece {
+ let afterSpace = true
+ const runs = piece.runs.map((run) => {
+ let text = run.text.replace(/\s+/g, ' ')
+ if (afterSpace) text = text.replace(/^ /, '')
+ if (text) afterSpace = text.endsWith(' ')
+ return { ...run, text }
+ })
+ const last = runs.findLastIndex((run) => run.text)
+ if (last !== -1) runs[last] = { ...runs[last], text: runs[last].text.replace(/ $/, '') }
+ return { ...piece, runs: runs.filter((run) => run.text) }
+}
+
+/** The pieces of a `<text>` element, split where a `<tspan>` moves the text position. */
+export function collectTextPieces(element: Element, scope: Scope): SVGTextPiece[] {
+ const pieces: SVGTextPiece[] = []
+ let current: SVGTextPiece = {
+ x: num(element, 'x'),
+ y: num(element, 'y'),
+ anchor: anchor(scope.presentation),
+ runs: []
+ }
+ const walk = (node: Node, presentation: PresentationAttributes) => {
+ for (const child of Array.from(node.childNodes)) {
+ if (child.nodeType === child.TEXT_NODE || child.nodeType === child.CDATA_SECTION_NODE) {
+ current.runs.push(textRun(child.nodeValue ?? '', presentation))
+ continue
+ }
+ if (!isElement(child) || (child.localName || child.tagName) !== 'tspan') continue
+ const style = presentationFor(child, presentation)
+ if (MOVES.some((name) => child.hasAttribute(name))) {
+ pieces.push(current)
+ current = {
+ x: child.hasAttribute('x') ? num(child, 'x') : current.x + num(child, 'dx'),
+ y: child.hasAttribute('y') ? num(child, 'y') : current.y + num(child, 'dy'),
+ anchor: anchor(style),
+ runs: []
+ }
+ }
+ walk(child, style)
+ }
+ }
+ walk(element, scope.presentation)
+ pieces.push(current)
+ return pieces.map(collapseWhitespace).filter((piece) => piece.runs.length > 0)
+}
+
+export function textInfo(
+ element: Element,
+ scope: Scope,
+ pathIndex: number
+): Omit<SVGTextInfo, 'elements'> | null {
+ const pieces = collectTextPieces(element, scope)
+ if (pieces.length === 0) return null
+ return {
+ pieces,
+ transform: scope.transform,
+ clipPaths: scope.clipPaths.length > 0 ? scope.clipPaths : undefined,
+ pathIndex
+ }
+}
diff --git a/packages/core/src/icons/types.ts b/packages/core/src/icons/types.ts
index 20eb35ca6..7d01612e3 100644
--- a/packages/core/src/icons/types.ts
+++ b/packages/core/src/icons/types.ts
@@ -80,6 +80,39 @@ export interface SVGElementLayer {
clip: number | null
}
+/** A stretch of SVG text in one style, such as a `<tspan>` on the same line. */
+export interface SVGTextRun {
+ text: string
+ fill: string | null
+ fillOpacity: number
+ /** The first family the SVG names that is not a generic one such as `sans-serif`. */
+ fontFamily: string | null
+ fontSize: number
+ fontWeight: number
+ italic: boolean
+ letterSpacing: number
+ textDecoration: 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH'
+}
+
+/** Text that starts at one position: a `<text>`, or a `<tspan>` that moves to a new one. */
+export interface SVGTextPiece {
+ /** The baseline origin, in the text element's own coordinates. */
+ x: number
+ y: number
+ anchor: 'start' | 'middle' | 'end'
+ runs: SVGTextRun[]
+}
+
+export interface SVGTextInfo {
+ pieces: SVGTextPiece[]
+ transform: string | null
+ clipPaths?: SVGClipPathRegion[]
+ /** As for a path; the last entry is the `<text>` element. */
+ elements: SVGElementLayer[]
+ /** How many paths come before the text in drawing order. */
+ pathIndex: number
+}
+
export type SVGClipPathInfo = Pick<IconPathInfo, 'd' | 'fillRule' | 'transform'>
export interface SVGClipPathRegion {
diff --git a/packages/core/src/io/formats/svg/import.ts b/packages/core/src/io/formats/svg/import.ts
index 109e5d96f..79951ea9c 100644
--- a/packages/core/src/io/formats/svg/import.ts
+++ b/packages/core/src/io/formats/svg/import.ts
@@ -1,3 +1,5 @@
+import { groupBy } from 'es-toolkit/array'
+
import {
fitEnclosingGroups,
WHITE,
@@ -13,10 +15,13 @@ import {
svgToVectorPaths,
type SVGVectorizeResult,
type VectorizedClip,
- type VectorizedPath
+ type VectorizedPath,
+ type VectorizedText
} from '#core/vector/vectorize/svg/to-vectors'
+import { parseSVGDocument } from './document'
import { parseSVGSize, svgRootId } from './metadata'
+import { createSVGText } from './text'
export type SVGImportData = SVGVectorizeResult &
Size & {
@@ -31,12 +36,16 @@ export interface SVGImportOptions {
defaultColor?: string
x?: number
y?: number
+ /** Keep the frame of an SVG that draws nothing, as `figma.createNodeFromSvg` does. */
+ keepEmpty?: boolean
}
+/** The layers SVG markup draws, or null when it does not parse as SVG. */
export function prepareSVGImport(
source: string,
options: Pick<SVGImportOptions, 'defaultColor'> = {}
): SVGImportData | null {
+ if (!parseSVGDocument(source)) return null
const sized = parseSVGSize(source, { width: 0, height: 0 }).width > 0
const { width, height } = parseSVGSize(source)
const vectorized = svgToVectorPaths(
@@ -46,8 +55,8 @@ export function prepareSVGImport(
defaultColor: options.defaultColor,
preserveAspectRatio: true
}
- )
- return vectorized ? { width, height, name: svgRootId(source), sized, ...vectorized } : null
+ ) ?? { paths: [], texts: [], contentBounds: { x: 0, y: 0, width: 0, height: 0 } }
+ return { width, height, name: svgRootId(source), sized, ...vectorized }
}
function createGroup(graph: SceneGraph, parentId: string, props: Partial<SceneNode>): string {
@@ -73,20 +82,66 @@ function createClipGroup(
return groupId
}
-function clipFor(path: VectorizedPath, element: SVGElementLayer): VectorizedClip | null {
- return element.clip === null ? null : (path.clips?.[element.clip] ?? null)
+function clipFor(
+ clips: VectorizedClip[] | undefined,
+ element: SVGElementLayer
+): VectorizedClip | null {
+ const clip = element.clip === null ? null : clips?.[element.clip]
+ return clip && clip.shapes.length > 0 ? clip : null
+}
+
+/** A path or a text, with the elements it was drawn in. */
+interface Drawable {
+ elements: SVGElementLayer[]
+ clips?: VectorizedClip[]
+ create: (parentId: string, element: SVGElementLayer) => void
+}
+
+/** Paths and texts in drawing order: each text goes before the path it preceded. */
+function drawables(graph: SceneGraph, data: SVGImportData, parentIds: Set<string>): Drawable[] {
+ const pathDrawable = (path: VectorizedPath): Drawable => ({
+ elements: path.elements,
+ clips: path.clips,
+ create: (parentId, element) => {
+ const vector = createPlacedVector(graph, parentId, path.vectorNetwork, {
+ name: element.name ?? 'Vector',
+ opacity: element.opacity,
+ ...vectorizedPathPaints(path)
+ })
+ if (vector) parentIds.add(parentId)
+ }
+ })
+ const textDrawable = (text: VectorizedText): Drawable => ({
+ elements: text.elements,
+ clips: text.clips,
+ create: (parentId, element) => {
+ createSVGText(graph, parentId, text, element, (groupParentId, props) => {
+ const groupId = createGroup(graph, groupParentId, props)
+ parentIds.add(groupId)
+ return groupId
+ })
+ parentIds.add(parentId)
+ }
+ })
+ const textsByPath = groupBy(data.texts, (text) => text.pathIndex)
+ const textsAt = (index: number) => (textsByPath[index] ?? []).map(textDrawable)
+ return [
+ ...data.paths.flatMap((path, index) => [...textsAt(index), pathDrawable(path)]),
+ ...textsAt(data.paths.length)
+ ]
}
/**
- * Builds the layers Figma makes from SVG: a group per `<g>`, a vector per shape, each named by
- * its `id`, and a clip group around anything clipped. Groups are fitted to their layers last.
+ * Builds the layers Figma makes from SVG: a group per `<g>`, a vector per shape and a text layer
+ * per text, each named by its `id`, and a clip group around anything clipped. Groups are fitted
+ * to their layers last.
*/
function createSVGLayers(graph: SceneGraph, rootId: string, data: SVGImportData): void {
const open: Array<{ key: number; parentId: string }> = []
const parentIds = new Set<string>()
- for (const path of data.paths) {
- const groups = path.elements.slice(0, -1)
- const shape = path.elements.at(-1)
+ for (const drawable of drawables(graph, data, parentIds)) {
+ const groups = drawable.elements.slice(0, -1)
+ const shape = drawable.elements.at(-1)
if (!shape) continue
let depth = 0
while (depth < open.length && depth < groups.length && open[depth].key === groups[depth].key) {
@@ -95,7 +150,7 @@ function createSVGLayers(graph: SceneGraph, rootId: string, data: SVGImportData)
open.length = depth
let parentId = open.at(-1)?.parentId ?? rootId
for (const element of groups.slice(depth)) {
- const clip = clipFor(path, element)
+ const clip = clipFor(drawable.clips, element)
if (clip) parentId = createClipGroup(graph, parentId, clip, parentIds)
parentId = createGroup(graph, parentId, {
name: element.name ?? 'Group',
@@ -103,14 +158,8 @@ function createSVGLayers(graph: SceneGraph, rootId: string, data: SVGImportData)
})
open.push({ key: element.key, parentId })
}
- const clip = clipFor(path, shape)
- const vectorParentId = clip ? createClipGroup(graph, parentId, clip, parentIds) : parentId
- const vector = createPlacedVector(graph, vectorParentId, path.vectorNetwork, {
- name: shape.name ?? 'Vector',
- opacity: shape.opacity,
- ...vectorizedPathPaints(path)
- })
- if (vector) parentIds.add(vectorParentId)
+ const clip = clipFor(drawable.clips, shape)
+ drawable.create(clip ? createClipGroup(graph, parentId, clip, parentIds) : parentId, shape)
}
fitEnclosingGroups(graph, [...parentIds])
}
@@ -139,7 +188,7 @@ export function createSVGNodesFromImport(
try {
createSVGLayers(graph, root.id, data)
const created = graph.getNode(root.id)
- if (created && graph.getChildren(root.id).length > 0) return created
+ if (created && (options.keepEmpty || graph.getChildren(root.id).length > 0)) return created
if (created) graph.deleteNode(root.id)
return null
} catch (error) {
diff --git a/packages/core/src/io/formats/svg/index.ts b/packages/core/src/io/formats/svg/index.ts
index 8c2905af9..d5a40b352 100644
--- a/packages/core/src/io/formats/svg/index.ts
+++ b/packages/core/src/io/formats/svg/index.ts
@@ -7,3 +7,4 @@ export {
type SVGImportOptions
} from './import'
export { isSVGMarkup } from './metadata'
+export { svgImportFonts } from './text'
diff --git a/packages/core/src/io/formats/svg/text.ts b/packages/core/src/io/formats/svg/text.ts
new file mode 100644
index 000000000..9c75d02fb
--- /dev/null
+++ b/packages/core/src/io/formats/svg/text.ts
@@ -0,0 +1,149 @@
+import { isEqual } from 'es-toolkit/predicate'
+
+import {
+ localTransformFromWorld,
+ type CharacterStyleOverride,
+ type SceneGraph,
+ type SceneNode,
+ type StyleRun
+} from '@open-pencil/scene-graph'
+import Matrix from '@open-pencil/scene-graph/matrix'
+
+import type { SVGElementLayer } from '#core/icons/types'
+import { estimateTextSize, getTextMeasurer } from '#core/layout/text-measurement'
+import { weightToStyle } from '#core/text/font/style'
+import type {
+ SVGVectorizeResult,
+ VectorizedText,
+ VectorizedTextPiece
+} from '#core/vector/vectorize/svg/to-vectors'
+
+const ALIGN = { start: 'LEFT', middle: 'CENTER', end: 'RIGHT' } as const
+/** How much of its width a text anchored this way sits left of `x`. */
+const ANCHOR_OFFSET = { start: 0, middle: 0.5, end: 1 } as const
+
+type Run = VectorizedTextPiece['runs'][number]
+
+/** A run's style in the text's own units; `scale` takes SVG units to the import's. */
+function runStyle(
+ run: Run,
+ scale: number
+): Required<
+ Pick<
+ CharacterStyleOverride,
+ | 'fontFamily'
+ | 'fontSize'
+ | 'fontWeight'
+ | 'italic'
+ | 'letterSpacing'
+ | 'textDecoration'
+ | 'fills'
+ >
+> {
+ return {
+ // Figma imports SVG text in a font it does not know as Inter.
+ fontFamily: run.fontFamily ?? 'Inter',
+ fontSize: run.fontSize * scale,
+ fontWeight: run.fontWeight,
+ italic: run.italic,
+ letterSpacing: run.letterSpacing * scale,
+ textDecoration: run.textDecoration,
+ fills: run.fills
+ }
+}
+
+/** Later runs as style runs over the first run's style, which the layer takes. */
+function styleRuns(runs: Run[], scale: number): StyleRun[] {
+ const base = runStyle(runs[0], scale)
+ const result: StyleRun[] = []
+ let start = 0
+ for (const run of runs) {
+ const style = runStyle(run, scale)
+ const override = Object.fromEntries(
+ Object.entries(style).filter(
+ ([key, value]) => !isEqual(value, base[key as keyof typeof base])
+ )
+ ) as CharacterStyleOverride
+ if (Object.keys(override).length > 0)
+ result.push({ start, length: run.text.length, style: override })
+ start += run.text.length
+ }
+ return result
+}
+
+/**
+ * A text layer sized to its characters and placed as Figma places SVG text: its top a font size
+ * above the baseline, its left, centre, or right edge on `x` by `text-anchor`.
+ */
+function createTextPiece(
+ graph: SceneGraph,
+ parentId: string,
+ piece: VectorizedTextPiece,
+ matrix: VectorizedText['matrix'],
+ props: Partial<SceneNode>
+): SceneNode {
+ const scale = Math.hypot(matrix[0], matrix[3]) || 1
+ const characters = piece.runs.map((run) => run.text).join('')
+ const node = graph.createNode('TEXT', parentId, {
+ name: characters,
+ ...props,
+ ...runStyle(piece.runs[0], scale),
+ text: characters,
+ styleRuns: styleRuns(piece.runs, scale),
+ textAlignHorizontal: ALIGN[piece.anchor],
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ lineHeight: null,
+ width: 0
+ })
+ const size = getTextMeasurer()?.(node) ?? estimateTextSize(node)
+ const width = size.width / scale
+ const left = width * ANCHOR_OFFSET[piece.anchor]
+ const world = Matrix.multiply(
+ matrix,
+ Matrix.translated(piece.x - left, piece.y - piece.runs[0].fontSize),
+ Matrix.scaled(1 / scale, 1 / scale)
+ )
+ const sized = { ...node, width: size.width, height: size.height }
+ const place = localTransformFromWorld(sized, world, Matrix.identity())
+ graph.updateNode(node.id, { width: size.width, height: size.height, ...place })
+ return node
+}
+
+/** Text layers for a `<text>`; one with several pieces is a group of them, as in Figma. */
+export function createSVGText(
+ graph: SceneGraph,
+ parentId: string,
+ text: VectorizedText,
+ element: SVGElementLayer,
+ createGroup: (parentId: string, props: Partial<SceneNode>) => string
+): void {
+ if (text.pieces.length === 1) {
+ createTextPiece(graph, parentId, text.pieces[0], text.matrix, {
+ ...(element.name ? { name: element.name } : {}),
+ opacity: element.opacity
+ })
+ return
+ }
+ const groupId = createGroup(parentId, {
+ name: element.name ?? 'Group',
+ opacity: element.opacity
+ })
+ for (const piece of text.pieces) createTextPiece(graph, groupId, piece, text.matrix, {})
+}
+
+/** The fonts an import's text is drawn in, to load before it is measured and placed. */
+export function svgImportFonts(data: Pick<SVGVectorizeResult, 'texts'>): Array<{
+ family: string
+ style: string
+ characters: string
+}> {
+ const fonts = new Map<string, { family: string; style: string; characters: string }>()
+ for (const run of data.texts.flatMap((text) => text.pieces.flatMap((piece) => piece.runs))) {
+ const family = run.fontFamily ?? 'Inter'
+ const style = weightToStyle(run.fontWeight, run.italic)
+ const key = `${family}\u0000${style}`
+ const font = fonts.get(key) ?? { family, style, characters: '' }
+ fonts.set(key, { ...font, characters: font.characters + run.text })
+ }
+ return [...fonts.values()]
+}
diff --git a/packages/core/src/tools/create/svg.ts b/packages/core/src/tools/create/svg.ts
index 0f0c387fb..e45c94f72 100644
--- a/packages/core/src/tools/create/svg.ts
+++ b/packages/core/src/tools/create/svg.ts
@@ -8,7 +8,7 @@ export const importSVG = defineTool({
name: 'import_svg',
description:
- 'Import raw SVG markup onto the canvas as editable layers, as pasting it into Figma does: a frame (a group when the SVG has no width, height, or viewBox) with a group per <g> and a vector per shape, named by their ids, and a mask group around clipped content. Supports common SVG shapes, inherited presentation attributes, opacity, transforms, gradients, clip paths, and internal <use> references.',
+ 'Import raw SVG markup onto the canvas as editable layers, as pasting it into Figma does: a frame (a group when the SVG has no width, height, or viewBox) with a group per <g>, a vector per shape, and a text layer per <text>, named by their ids, and a mask group around clipped content. Supports common SVG shapes, text with <tspan> styles, inherited presentation attributes, opacity, transforms, gradients, clip paths, and internal <use> references.',
execution: { kind: 'async', mutation: 'document' },
input: v.strictObject({
svg: v.pipe(
diff --git a/packages/core/src/vector/vectorize/svg/to-vectors.ts b/packages/core/src/vector/vectorize/svg/to-vectors.ts
index e94b62493..c2191f88d 100644
--- a/packages/core/src/vector/vectorize/svg/to-vectors.ts
+++ b/packages/core/src/vector/vectorize/svg/to-vectors.ts
@@ -10,17 +10,19 @@ import svgpath from 'svgpath'
import type { Fill, Stroke, VectorNetwork, WindingRule } from '@open-pencil/scene-graph'
import { parseColor } from '@open-pencil/scene-graph/color'
import { computeBounds } from '@open-pencil/scene-graph/geometry'
+import type { Mat3 } from '@open-pencil/scene-graph/matrix'
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
-import type { Rect, Size } from '@open-pencil/scene-graph/primitives'
+import type { Rect, Size, Vector } from '@open-pencil/scene-graph/primitives'
import { createPathStroke } from '#core/icons/path-style'
-import { extractPaths } from '#core/icons/svg'
-import type { IconPathInfo, SVGElementLayer } from '#core/icons/types'
+import { extractSVGContent } from '#core/icons/svg'
+import type { IconPathInfo, SVGElementLayer, SVGTextPiece, SVGTextRun } 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 {
+ type SVGViewportMapping,
applySVGTransformToPath,
mapSVGPathToViewport,
resolveSVGViewportMapping
@@ -79,8 +81,23 @@ export interface VectorizedPath {
elements: SVGElementLayer[]
}
+/** SVG text, placed by the matrix from its element's coordinates into the target bounds. */
+export type VectorizedTextPiece = Omit<SVGTextPiece, 'runs'> & {
+ runs: Array<SVGTextRun & { fills: Fill[] }>
+}
+
+export interface VectorizedText {
+ pieces: VectorizedTextPiece[]
+ matrix: Mat3
+ clips?: VectorizedClip[]
+ elements: SVGElementLayer[]
+ /** How many paths come before the text in drawing order. */
+ pathIndex: number
+}
+
export interface SVGVectorizeResult {
paths: VectorizedPath[]
+ texts: VectorizedText[]
/** Tight bounds of path geometry in the target coordinate space. */
contentBounds: Rect
}
@@ -90,8 +107,8 @@ export function svgToVectorPaths(
bounds: Size,
options?: { defaultColor?: string; preserveAspectRatio?: boolean }
): SVGVectorizeResult | null {
- const paths = extractPaths(svgText)
- if (paths.length === 0) return null
+ const { paths, texts } = extractSVGContent(svgText)
+ if (paths.length === 0 && texts.length === 0) return null
const space = parseSVGCoordinateSpace(svgText)
if (space.width <= 0 || space.height <= 0) return null
@@ -107,7 +124,7 @@ export function svgToVectorPaths(
const strokeScale = Math.min(viewport.scaleX, viewport.scaleY)
const vectorized: VectorizedPath[] = []
- const clipCache = new WeakMap<NonNullable<IconPathInfo['clipPaths']>, VectorizedClip[]>()
+ const clipCache: ClipCache = new WeakMap()
for (const path of paths) {
const fillRule: WindingRule = path.fillRule
const transform = path.transform ?? null
@@ -130,21 +147,58 @@ export function svgToVectorPaths(
computeAccurateBounds(network)
)
: null
- let clips: VectorizedClip[] | undefined
- if (path.clipPaths) {
- const hasObjectBoundingBoxClip = path.clipPaths.some(
- ({ units }) => units === 'objectBoundingBox'
- )
- clips = hasObjectBoundingBoxClip ? undefined : clipCache.get(path.clipPaths)
- if (!clips) {
- clips = path.clipPaths.map((clipRegion) => ({
- id: clipRegion.id,
- shapes: clipRegion.paths.map((clipPath) => {
+ const clips = path.clipPaths && vectorizeClips(path.clipPaths, viewport, pathBounds, clipCache)
+ vectorized.push({
+ vectorNetwork: network,
+ fills: gradientFill ? [{ ...gradientFill, opacity: path.fillOpacity }] : solidFills,
+ strokes,
+ clips,
+ elements: path.elements
+ })
+ }
+
+ return {
+ paths: vectorized,
+ texts: texts.map((text) => ({
+ pieces: text.pieces.map((piece) => ({
+ ...piece,
+ runs: piece.runs.map((run) => ({ ...run, fills: resolveTextFill(run, defaultColor) }))
+ })),
+ matrix: transformMatrix(text.transform, viewport),
+ clips: text.clipPaths && vectorizeClips(text.clipPaths, viewport, null, clipCache),
+ elements: text.elements,
+ pathIndex: text.pathIndex
+ })),
+ contentBounds: unionPathBounds(vectorized)
+ }
+}
+
+type ClipCache = WeakMap<NonNullable<IconPathInfo['clipPaths']>, VectorizedClip[]>
+
+/**
+ * Clip regions as networks in the target space. An objectBoundingBox clip follows the bounds of
+ * what it clips, which text has only once laid out, so without bounds such a clip has no shapes.
+ */
+function vectorizeClips(
+ clipPaths: NonNullable<IconPathInfo['clipPaths']>,
+ viewport: SVGViewportMapping,
+ objectBounds: Rect | null,
+ cache: ClipCache
+): VectorizedClip[] {
+ const hasObjectBoundingBoxClip = clipPaths.some(({ units }) => units === 'objectBoundingBox')
+ const cached = hasObjectBoundingBoxClip ? undefined : cache.get(clipPaths)
+ if (cached) return cached
+ const clips = clipPaths.map((clipRegion) => ({
+ id: clipRegion.id,
+ shapes:
+ clipRegion.units === 'objectBoundingBox' && !objectBounds
+ ? []
+ : clipRegion.paths.map((clipPath) => {
let clipData = applySVGTransformToPath(clipPath.d, clipPath.transform ?? null)
- if (clipRegion.units === 'objectBoundingBox') {
+ if (clipRegion.units === 'objectBoundingBox' && objectBounds) {
clipData = svgpath(clipData)
- .scale(pathBounds.width, pathBounds.height)
- .translate(pathBounds.x, pathBounds.y)
+ .scale(objectBounds.width, objectBounds.height)
+ .translate(objectBounds.x, objectBounds.y)
.toString()
return parseSVGPath(clipData, clipPath.fillRule, { includeOpenRegions: true })
}
@@ -152,18 +206,37 @@ export function svgToVectorPaths(
includeOpenRegions: true
})
})
- }))
- if (!hasObjectBoundingBoxClip) clipCache.set(path.clipPaths, clips)
- }
- }
- vectorized.push({
- vectorNetwork: network,
- fills: gradientFill ? [{ ...gradientFill, opacity: path.fillOpacity }] : solidFills,
- strokes,
- clips,
- elements: path.elements
+ }))
+ if (!hasObjectBoundingBoxClip) cache.set(clipPaths, clips)
+ return clips
+}
+
+/** The matrix taking an element's own coordinates, under `transform`, into the target space. */
+function transformMatrix(transform: string | null, viewport: SVGViewportMapping): Mat3 {
+ const points: Vector[] = []
+ svgpath(mapSVGPathToViewport(applySVGTransformToPath('M0 0M1 0M0 1', transform), viewport))
+ .abs()
+ .iterate((segment) => {
+ if (segment[0] === 'M') points.push({ x: segment[1], y: segment[2] })
})
- }
+ const [origin = { x: 0, y: 0 }, unitX = { x: 1, y: 0 }, unitY = { x: 0, y: 1 }] = points
+ return [
+ unitX.x - origin.x,
+ unitY.x - origin.x,
+ origin.x,
+ unitX.y - origin.y,
+ unitY.y - origin.y,
+ origin.y,
+ 0,
+ 0,
+ 1
+ ]
+}
- return { paths: vectorized, contentBounds: unionPathBounds(vectorized) }
+function resolveTextFill(run: SVGTextRun, defaultColor: string): Fill[] {
+ const color =
+ run.fill === null || run.fill === 'currentColor'
+ ? parseColor(defaultColor)
+ : parseColor(run.fill)
+ return [{ type: 'SOLID', color, opacity: run.fillOpacity, visible: true }]
}
diff --git a/packages/core/tests/editor/clipboard/svg-paste.test.ts b/packages/core/tests/editor/clipboard/svg-paste.test.ts
index 5737a8cf3..888d92648 100644
--- a/packages/core/tests/editor/clipboard/svg-paste.test.ts
+++ b/packages/core/tests/editor/clipboard/svg-paste.test.ts
@@ -6,10 +6,10 @@ const BADGE = `<?xml version="1.0"?>
<svg id="badge" viewBox="0 0 40 20"><g id="dot"><circle cx="10" cy="10" r="10"/></g></svg>`
describe('pasting SVG markup', () => {
- test('places the layers centred on the point with one selection and undo entry', () => {
+ test('places the layers centred on the point with one selection and undo entry', async () => {
const editor = createEditor()
- expect(editor.pasteSVG(BADGE, 200, 100)).toBe(true)
+ expect(await editor.pasteSVG(BADGE, 200, 100)).toBe(true)
const [frame] = editor.graph.getChildren(editor.state.currentPageId)
expect(frame).toMatchObject({ type: 'FRAME', name: 'badge', x: 180, y: 90 })
@@ -21,11 +21,11 @@ describe('pasting SVG markup', () => {
expect(editor.graph.getChildren(editor.state.currentPageId)).toHaveLength(0)
})
- test('leaves text that is not SVG to other paste handlers', () => {
+ test('leaves text that is not SVG to other paste handlers', async () => {
const editor = createEditor()
- expect(editor.pasteSVG('<p>not an svg</p>', 0, 0)).toBe(false)
- expect(editor.pasteSVG('just text with <svg> in it', 0, 0)).toBe(false)
+ expect(await editor.pasteSVG('<p>not an svg</p>', 0, 0)).toBe(false)
+ expect(await editor.pasteSVG('just text with <svg> in it', 0, 0)).toBe(false)
expect(editor.graph.getChildren(editor.state.currentPageId)).toHaveLength(0)
})
})
diff --git a/packages/core/tests/figma-api/create-node-from-svg.test.ts b/packages/core/tests/figma-api/create-node-from-svg.test.ts
new file mode 100644
index 000000000..bacdbad66
--- /dev/null
+++ b/packages/core/tests/figma-api/create-node-from-svg.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Recorded with the same calls in Figma desktop 126.
+describe('figma.createNodeFromSvg', () => {
+ test('adds the layers to the current page at its origin without selecting them', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+
+ const frame = figma.createNodeFromSvg(
+ '<svg width="10" height="10"><rect id="dot" width="10" height="10"/></svg>'
+ )
+
+ expect(frame.type).toBe('FRAME')
+ expect(frame.parent?.id).toBe(figma.currentPage.id)
+ expect([frame.x, frame.y]).toEqual([0, 0])
+ expect(frame.children.map((child) => child.name)).toEqual(['dot'])
+ expect(figma.currentPage.selection).toEqual([])
+ })
+
+ test('returns an empty frame for markup that draws nothing', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+
+ const frame = figma.createNodeFromSvg('<svg viewBox="0 0 10 10"></svg>')
+
+ expect(frame.type).toBe('FRAME')
+ expect(frame.children).toHaveLength(0)
+ })
+
+ test('returns a group for unsized markup', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+
+ const group = figma.createNodeFromSvg('<svg><text>only text</text></svg>')
+
+ // Figma's typings say FrameNode, but it returns a group here too.
+ expect<string>(group.type).toBe('GROUP')
+ expect(group.children.map((child) => child.type)).toEqual(['TEXT'])
+ })
+
+ test('throws for markup that is not SVG', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ for (const markup of [
+ '',
+ 'not svg',
+ '<svg viewBox="0 0 10 10"><rect width="10" height="10"/>'
+ ]) {
+ expect(() => figma.createNodeFromSvg(markup)).toThrow(
+ 'in createNodeFromSvg: Failed to convert SVG file'
+ )
+ }
+ })
+})
diff --git a/packages/core/tests/io/formats/svg/import-layers.test.ts b/packages/core/tests/io/formats/svg/import-layers.test.ts
index b29955a65..2f3735be5 100644
--- a/packages/core/tests/io/formats/svg/import-layers.test.ts
+++ b/packages/core/tests/io/formats/svg/import-layers.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { compact } from 'es-toolkit/array'
+import { FigmaAPI } from '@open-pencil/core/figma-api'
import { createSVGNodes } from '@open-pencil/core/io'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
@@ -245,3 +246,125 @@ test('imports SVG files that start with an XML declaration and doctype', () => {
)
expect(graph.getChildren(frame?.id ?? '').map((node) => node.name)).toEqual(['mark'])
})
+
+describe('SVG text imports as the text layers Figma makes', () => {
+ function textLayers(svg: string) {
+ const graph = new SceneGraph()
+ const root = createSVGNodes(graph, graph.getPages()[0].id, svg)
+ if (!root) throw new Error('Nothing imported')
+ const texts = [...graph.getAllNodes()].filter((node) => node.type === 'TEXT')
+ return { graph, root, texts }
+ }
+
+ test('a text layer named by id, else its characters, its top a font size above the baseline', () => {
+ const { texts } = textLayers(
+ '<svg viewBox="0 0 200 90"><text x="10" y="30" font-family="Inter" font-size="20">Hello</text><text id="title" x="10" y="70" font-size="20" font-weight="700" fill="#f00">Bold</text></svg>'
+ )
+ expect(
+ texts.map(({ name, text, x, y, fontFamily, fontSize, fontWeight, textAutoResize }) => ({
+ name,
+ text,
+ x,
+ y,
+ fontFamily,
+ fontSize,
+ fontWeight,
+ textAutoResize
+ }))
+ ).toEqual([
+ {
+ name: 'Hello',
+ text: 'Hello',
+ x: 10,
+ y: 10,
+ fontFamily: 'Inter',
+ fontSize: 20,
+ fontWeight: 400,
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ },
+ {
+ name: 'title',
+ text: 'Bold',
+ x: 10,
+ y: 50,
+ fontFamily: 'Inter',
+ fontSize: 20,
+ fontWeight: 700,
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ }
+ ])
+ expect(texts[1]?.fills[0]?.color).toEqual({ r: 1, g: 0, b: 0, a: 1 })
+ })
+
+ test('text without a font is Inter at 12px', () => {
+ const [text] = textLayers(
+ '<svg viewBox="0 0 200 60"><text x="10" y="30">Default</text></svg>'
+ ).texts
+ expect(text).toMatchObject({ fontFamily: 'Inter', fontSize: 12, y: 18 })
+ })
+
+ test('text-anchor aligns the layer and places that edge on x', () => {
+ const [middle, end] = textLayers(
+ '<svg viewBox="0 0 200 90"><text x="100" y="30" font-size="20" text-anchor="middle">Mid</text><text x="190" y="70" font-size="20" text-anchor="end">End</text></svg>'
+ ).texts
+ expect(middle?.textAlignHorizontal).toBe('CENTER')
+ expect((middle?.x ?? 0) + (middle?.width ?? 0) / 2).toBeCloseTo(100)
+ expect(end?.textAlignHorizontal).toBe('RIGHT')
+ expect((end?.x ?? 0) + (end?.width ?? 0)).toBeCloseTo(190)
+ })
+
+ test('same-line tspans style one layer; a tspan that moves starts another, grouped', () => {
+ const { graph, root, texts } = textLayers(
+ '<svg viewBox="0 0 300 90"><text x="10" y="30" font-size="20">Plain <tspan font-weight="700" fill="#00f">bold blue</tspan> end<tspan x="10" dy="30">second line</tspan></text></svg>'
+ )
+ const [group] = graph.getChildren(root.id)
+ expect(group).toMatchObject({ type: 'GROUP', name: 'Group' })
+ const figma = new FigmaAPI(graph)
+ const placed = texts.map(({ id, text }) => {
+ const proxy = figma.getNodeById(id)
+ return { text, x: proxy?.x, y: proxy?.y }
+ })
+ expect(placed).toEqual([
+ { text: 'Plain bold blue end', x: 10, y: 10 },
+ { text: 'second line', x: 10, y: 40 }
+ ])
+ expect(texts[0]?.styleRuns).toEqual([
+ {
+ start: 6,
+ length: 9,
+ style: {
+ fontWeight: 700,
+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 1, a: 1 }, opacity: 1, visible: true }]
+ }
+ }
+ ])
+ })
+
+ test('keeps a tspan that only shifts by dx in its line, as a style run', () => {
+ const { texts } = textLayers(
+ '<svg viewBox="0 0 200 60"><text x="10" y="30" font-size="20">Hello<tspan dx="5" font-weight="700">World</tspan></text></svg>'
+ )
+ expect(texts.map((text) => text.text)).toEqual(['HelloWorld'])
+ expect(texts[0]?.styleRuns).toEqual([{ start: 5, length: 5, style: { fontWeight: 700 } }])
+ })
+
+ test('keeps italic, underline, and the rotation of a transform', () => {
+ const { graph, texts } = textLayers(
+ '<svg viewBox="0 0 200 200"><text transform="translate(50 100) rotate(-30)" style="font-size: 20px; font-style: italic; text-decoration: underline">Turned</text></svg>'
+ )
+ const [text] = texts
+ expect(text).toMatchObject({ italic: true, textDecoration: 'UNDERLINE' })
+ const proxy = new FigmaAPI(graph).getNodeById(text?.id ?? '')
+ expect(proxy).toMatchObject({ rotation: expect.closeTo(30) })
+ expect(proxy?.x).toBeCloseTo(40)
+ expect(proxy?.y).toBeCloseTo(82.68)
+ })
+
+ test('collapses whitespace and imports an SVG of only text as a group', () => {
+ const { root, texts } = textLayers(
+ '<svg><text x="10" y="30"> lots of\n space </text></svg>'
+ )
+ expect(root.type).toBe('GROUP')
+ expect(texts.map((text) => text.text)).toEqual(['lots of space'])
+ })
+})
diff --git a/packages/docs/es/programmable/cli/scripting.md b/packages/docs/es/programmable/cli/scripting.md
index 9024f2f20..53c797c11 100644
--- a/packages/docs/es/programmable/cli/scripting.md
+++ b/packages/docs/es/programmable/cli/scripting.md
@@ -84,6 +84,7 @@ La API sigue el modelo de Figma Plugin API, pero actúa sobre SceneGraph y los f
- `figma.createPolygon()`
- `figma.createStar()`
- `figma.createVector()`
+- `figma.createNodeFromSvg(svg)`
- `figma.createComponent()`
- `figma.createSection()`
diff --git a/packages/docs/pl/programmable/cli/scripting.md b/packages/docs/pl/programmable/cli/scripting.md
index eeb4705d5..4fe28bcee 100644
--- a/packages/docs/pl/programmable/cli/scripting.md
+++ b/packages/docs/pl/programmable/cli/scripting.md
@@ -65,6 +65,7 @@ API jest celowo zbliżone do Figma Plugin API, ale pracuje z SceneGraph i format
- `figma.createPolygon()`
- `figma.createStar()`
- `figma.createVector()`
+- `figma.createNodeFromSvg(svg)`
- `figma.createComponent()`
- `figma.createSection()`
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 4a9061f99..d5ffcf76a 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -132,6 +132,7 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'
- `figma.createPolygon()`
- `figma.createStar()`
- `figma.createVector()`
+- `figma.createNodeFromSvg(svg)`
- `figma.createComponent()`
- `figma.createSection()`
diff --git a/packages/docs/ru/programmable/cli/scripting.md b/packages/docs/ru/programmable/cli/scripting.md
index 30ad54d16..82ffb07e6 100644
--- a/packages/docs/ru/programmable/cli/scripting.md
+++ b/packages/docs/ru/programmable/cli/scripting.md
@@ -85,6 +85,7 @@ API намеренно близок к Figma Plugin API, но работает
- `figma.createPolygon()`
- `figma.createStar()`
- `figma.createVector()`
+- `figma.createNodeFromSvg(svg)`
- `figma.createComponent()`
- `figma.createSection()`
diff --git a/src/app/editor/clipboard/paste.ts b/src/app/editor/clipboard/paste.ts
index e782eb2d3..5738044c0 100644
--- a/src/app/editor/clipboard/paste.ts
+++ b/src/app/editor/clipboard/paste.ts
@@ -27,7 +27,11 @@ export function pastePoint(editor: Editor, cursorPos?: Vector): Vector {
}
/** Paste SVG markup, such as Figma's Copy as SVG, as layers; false when the text is not SVG. */
-export function pasteSVGText(editor: Editor, text: string, cursorPos?: Vector): boolean {
+export async function pasteSVGText(
+ editor: Editor,
+ text: string,
+ cursorPos?: Vector
+): Promise<boolean> {
if (!isSVGMarkup(text)) return false
const { x, y } = pastePoint(editor, cursorPos)
return editor.pasteSVG(text, x, y)
diff --git a/src/app/editor/clipboard/system/browser.ts b/src/app/editor/clipboard/system/browser.ts
index f23af27a6..ee97aad45 100644
--- a/src/app/editor/clipboard/system/browser.ts
+++ b/src/app/editor/clipboard/system/browser.ts
@@ -104,7 +104,7 @@ async function pasteSelection(
await pasteClipboardHTML(store, result.html, cursorPos)
return true
}
- return result.text !== null && pasteSVGText(store, result.text, cursorPos)
+ return result.text !== null && (await pasteSVGText(store, result.text, cursorPos))
}
const memoryHTML = getInMemoryClipboardHTML()
diff --git a/src/app/editor/clipboard/system/tauri.ts b/src/app/editor/clipboard/system/tauri.ts
index df5b9b541..e7edcaf98 100644
--- a/src/app/editor/clipboard/system/tauri.ts
+++ b/src/app/editor/clipboard/system/tauri.ts
@@ -44,7 +44,7 @@ async function pasteSelection(store: EditorStore, cursorPos?: Vector): Promise<b
await pasteClipboardHTML(store, text, cursorPos)
return true
}
- if (text && pasteSVGText(store, text, cursorPos)) return true
+ if (text && (await pasteSVGText(store, text, cursorPos))) return true
const matchingMemoryHTML = getInMemoryClipboardHTML(text ?? '')
if (matchingMemoryHTML && isDesignClipboardHTML(matchingMemoryHTML)) {
await pasteClipboardHTML(store, matchingMemoryHTML, cursorPos)
diff --git a/src/app/shell/keyboard/clipboard.ts b/src/app/shell/keyboard/clipboard.ts
index a4c9fcb5f..494fe96b7 100644
--- a/src/app/shell/keyboard/clipboard.ts
+++ b/src/app/shell/keyboard/clipboard.ts
@@ -1,5 +1,6 @@
import { useEventListener } from '@vueuse/core'
+import { isSVGMarkup } from '@open-pencil/core/io'
import { extractImageFilesFromClipboard } from '@open-pencil/vue'
import type { EditorStore } from '@/app/editor/active-store'
@@ -85,7 +86,10 @@ export function bindEditorClipboard(store: EditorStore) {
}
const text = e.clipboardData?.getData('text/plain') ?? ''
- if (pasteSVGText(store, text, cursorPos)) return
+ if (isSVGMarkup(text)) {
+ void pasteSVGText(store, text, cursorPos)
+ return
+ }
if (html) {
void pasteClipboardHTML(store, html)
diff --git a/tests/e2e/canvas/svg-paste-visual.spec.ts b/tests/e2e/canvas/svg-paste-visual.spec.ts
index 38daa7b97..d0a329331 100644
--- a/tests/e2e/canvas/svg-paste-visual.spec.ts
+++ b/tests/e2e/canvas/svg-paste-visual.spec.ts
@@ -14,10 +14,10 @@ const CLIPPED_SVG = `<svg viewBox="0 0 200 120" width="200" height="120">
</svg>`
test('pasted SVG clip paths draw through their mask groups', async () => {
- const pasted = await editor.page.evaluate((markup) => {
+ const pasted = await editor.page.evaluate(async (markup) => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('OpenPencil store not initialized')
- const done = store.pasteSVG(markup, 220, 160)
+ const done = await store.pasteSVG(markup, 220, 160)
store.clearSelection()
store.requestRender()
return done
@@ -27,3 +27,38 @@ test('pasted SVG clip paths draw through their mask groups', async () => {
editor.canvas.assertNoErrors()
expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('svg-clip-mask-groups.png')
})
+
+// Figma 126 makes these layers 48×24, 44×24, and 35×24, the last centred on x = 100.
+const TEXT_SVG = `<svg viewBox="0 0 200 130" width="200" height="130">
+ <text x="10" y="30" font-family="Inter" font-size="20">Hello</text>
+ <text x="10" y="70" font-family="Inter" font-size="20" font-weight="700" fill="#4F46E5">Bold</text>
+ <text x="100" y="110" font-family="Inter" font-size="20" text-anchor="middle">Mid</text>
+</svg>`
+
+test('pasted SVG text measures and draws as Figma lays it out', async () => {
+ const layers = await editor.page.evaluate(async (markup) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ await store.pasteSVG(markup, 220, 160)
+ store.clearSelection()
+ store.requestRender()
+ return [...store.graph.getAllNodes()]
+ .filter((node) => node.type === 'TEXT')
+ .map(({ text, x, width, height }) => ({ text, x, width, height }))
+ }, TEXT_SVG)
+ const expected = [
+ { text: 'Hello', width: 48, height: 24 },
+ { text: 'Bold', width: 44, height: 24 },
+ { text: 'Mid', width: 35, height: 24 }
+ ]
+ expect(layers.map(({ text }) => text)).toEqual(expected.map(({ text }) => text))
+ for (const [index, layer] of layers.entries()) {
+ expect(Math.abs(layer.width - expected[index].width)).toBeLessThanOrEqual(2)
+ expect(layer.height).toBe(expected[index].height)
+ }
+ const mid = layers[2]
+ expect(mid.x + mid.width / 2).toBeCloseTo(100, 0)
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('svg-text-layers.png')
+})
diff --git a/tests/e2e/canvas/svg-paste-visual.spec.ts-snapshots/svg-text-layers-openpencil-darwin.png b/tests/e2e/canvas/svg-paste-visual.spec.ts-snapshots/svg-text-layers-openpencil-darwin.png
new file mode 100644
index 000000000..a6c7199ce
Binary files /dev/null and b/tests/e2e/canvas/svg-paste-visual.spec.ts-snapshots/svg-text-layers-openpencil-darwin.png differ