Skip to content

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

feat(svg)!: import and paste SVG as the layers Figma makes (#1026)

Danila Poyarkovd0ce4daccecf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 35c84f170..af96eaa5f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
### Breaking changes
+- `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`.
- `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.
@@ -39,6 +40,7 @@
### Added
+- Paste SVG markup copied as text, such as from a code editor or Figma's Copy as SVG, as layers.
- Show the pixel grid when zoomed in, as in Figma: from 800% on a standard display and 400% on a Retina one, toggled with **View → Pixel Grid** or <kbd>⇧</kbd><kbd>'</kbd>. <kbd>⇧</kbd><kbd>⌘</kbd><kbd>'</kbd> toggles **Snap to Pixel Grid**. The zoom menu in the properties panel lists both, with Figma's shortcuts, and labels its shortcuts for zoom to fit (<kbd>⇧</kbd><kbd>1</kbd>) and 100% (<kbd>⌘</kbd><kbd>0</kbd>); <kbd>⇧</kbd><kbd>R</kbd> toggles rulers and <kbd>⌥</kbd><kbd>⌘</kbd><kbd>\\</kbd> multiplayer cursors.
- Set a component's text, boolean, and swap properties on a design JSX `<Instance>` by name, as variants are set, such as `<Instance of="Card" Title="Hello" Badge={false} />`; `properties` accepts names too. An instance written this way still works after the document is saved to `.fig` and reopened, which gives each property a new ID ([#750](https://github.com/open-pencil/open-pencil/issues/750)).
- Save the open document to cloud storage with **File → Save to storage…**. The tab stays bound to the stored copy, so Save and auto-save write to the bucket; before storage is configured, the command opens its settings. A new Cloud Storage guide covers connecting a bucket, CORS, syncing, and provider notes.
@@ -93,6 +95,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.
- 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.
@@ -105,7 +108,7 @@
- The desktop app shows an available update in a Software Update window with formatted, scrollable release notes, a link to the full notes, and download progress you can cancel, instead of a system dialog that showed raw Markdown and could grow taller than the screen (#743). On macOS and Linux the update installs first and you choose when to restart; restarting, and on Windows installing, first asks about unsaved documents as Quit does.
- Show Go to main component and Detach instance as buttons in an instance's panel header instead of a row of links below it.
- `openpencil eval` prints the value of a script's last expression, as the `eval` tool and app automation already do, so `-c 'figma.currentPage.children.length'` prints the count without a `return`.
-- In scripts, children of groups and booleans report `x`, `y`, and `relativeTransform` in their container's space, as in Figma, and a group refits whenever a script moves, resizes, rotates, adds, or removes one of its children; a group left without children is removed. The canvas and the plugin API share the refit.
+- In scripts, children of groups and booleans report `x`, `y`, and `relativeTransform` in their container's space, as in Figma, and a group refits whenever a script moves, resizes, rotates, adds, or removes one of its children; a group left without children is removed, and a group with a mask spans the mask and the layers below it, not the masked layers. The canvas and the plugin API share the refit.
- The properties panel shows and edits X, Y, and rotation as Figma's does: X and Y are the top-left of a turned layer's box on the canvas, measured from its frame or page through any groups, rotation is counterclockwise, and a typed rotation turns the layer about its center. Previously a layer Figma shows at 30° read −30°, and a turned layer's X and Y were those of its unturned box.
- New pages and new documents take Figma's background for the interface theme: #1E1E1E in the dark theme and #F5F5F5 in the light one, from the canvas and from scripts. Existing pages keep theirs.
- In scripts, layers turn, move, and resize as in Figma: `rotation` turns a layer counterclockwise about its top-left corner, `x` and `y` are that corner in the parent, `resize()` keeps it in place, `relativeTransform` can be set, and `absoluteBoundingBox` covers the turned layer. `appendChild()` and `insertChild()` keep a layer's `x`, `y`, and rotation in its new parent, so it moves with that parent, instead of keeping its place on the canvas. The AI and MCP `create_shape`, `create_slice`, and vector tools likewise place a layer given a `parent_id` at `x` and `y` inside that parent, and `reparent_node` keeps its position inside the new parent.
@@ -139,6 +142,9 @@
### Fixed
+- Draw layers masked by a group, such as Figma's clip path groups, instead of hiding them; a group used as a mask masks with what its layers draw.
+- Import SVG files that start with an XML declaration or doctype, such as Illustrator and Inkscape exports, instead of reporting no supported elements.
+- Keep `fill-opacity` and `stroke-opacity` when importing SVG instead of drawing those paints opaque.
- Use an API key saved in Settings for the open AI chat right away, including when asking again after a failed request, instead of only after reloading; the failure's notice closes once the request is sent again.
- Renaming a section title on the canvas keeps the title's size, weight, and place. Section titles draw in Inter SemiBold rather than an emboldened regular weight, and labels that are not rotated sit on whole pixels, so they stay crisp.
- Reject an argument an AI, MCP, CLI, or WebMCP tool does not take, such as `properties: { y: 500 }` for `update_node` or `font: { family }` for `set_font`, and name it, instead of reporting success without changing anything (#977).
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index b9640f3c9..706257193 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -138,12 +138,16 @@ function renderMaskNodeContent(
canvas: Canvas,
graph: SceneGraph,
node: SceneNode,
- overlays: RenderOverlays
+ overlays: RenderOverlays,
+ absX: number,
+ absY: number
): void {
canvas.save()
canvas.translate(node.x, node.y)
applyNodeTransforms(canvas, node, overlays)
renderNodeContent(r, canvas, graph, node, {})
+ // A group or frame used as a mask masks with what its layers draw, as in Figma.
+ renderChildren(r, canvas, graph, node, overlays, absX + node.x, absY + node.y, true)
canvas.restore()
}
@@ -168,7 +172,7 @@ function renderChildIds(
(childId) => r.renderNode(canvas, graph, childId, overlays, absX, absY, hasTransformedAncestor),
(childId) => {
const child = graph.getNode(childId)
- if (child) renderMaskNodeContent(r, canvas, graph, child, overlays)
+ if (child) renderMaskNodeContent(r, canvas, graph, child, overlays, absX, absY)
},
(childId) => {
const child = graph.getNode(childId)
diff --git a/packages/core/src/editor/bridges/clipboard.ts b/packages/core/src/editor/bridges/clipboard.ts
index b4e35a84e..7272af1ad 100644
--- a/packages/core/src/editor/bridges/clipboard.ts
+++ b/packages/core/src/editor/bridges/clipboard.ts
@@ -15,6 +15,7 @@ export function createClipboardBridge(clipboard: ClipboardActions, selection: Se
storeImage: clipboard.storeImage,
placeFiles: clipboard.placeFiles,
placeImageFiles: clipboard.placeImageFiles,
+ pasteSVG: clipboard.pasteSVG,
loadFontsForNodes: clipboard.loadFontsForNodes,
copySelectionAsText: clipboard.copySelectionAsText,
copySelectionAsSVG: clipboard.copySelectionAsSVG,
diff --git a/packages/core/src/editor/clipboard/assets.ts b/packages/core/src/editor/clipboard/assets.ts
index 8ffb796fa..c05ebf5e9 100644
--- a/packages/core/src/editor/clipboard/assets.ts
+++ b/packages/core/src/editor/clipboard/assets.ts
@@ -8,6 +8,7 @@ import type { EditorContext } from '#core/editor/types'
import { computeImageHash } from '#core/figma-api'
import {
createSVGNodesFromImport,
+ isSVGMarkup,
prepareSVGImport,
type SVGImportData
} from '#core/io/formats/svg'
@@ -35,7 +36,8 @@ interface PreparedRasterAsset {
interface PreparedSVGAsset {
kind: 'svg'
data: SVGImportData
- name: string
+ /** A dropped file's name; pasted markup is named as Figma names it. */
+ name?: string
width: number
height: number
}
@@ -87,7 +89,7 @@ export function createClipboardAssetActions(
? {
kind: 'svg',
data,
- name: file.name.replace(/\.svg$/i, '') || 'SVG',
+ name: file.name.replace(/\.svg$/i, '') || undefined,
width: data.width,
height: data.height
}
@@ -131,11 +133,8 @@ export function createClipboardAssetActions(
}).id
}
- async function placeFiles(files: File[], cx: number, cy: number) {
- const prepared = (await Promise.all(files.map(prepareAsset))).filter(
- (asset): asset is PreparedAsset => asset !== null
- )
- if (prepared.length === 0) return
+ function placeAssets(prepared: PreparedAsset[], cx: number, cy: number, label: string): boolean {
+ if (prepared.length === 0) return false
const previousSelection = new Set(ctx.state.selectedIds)
const parentId = resolvePasteTarget(ctx)
@@ -165,11 +164,31 @@ export function createClipboardAssetActions(
throw error
}
- if (created.length === 0) return
+ if (created.length === 0) return false
computeAllLayouts(ctx.graph, ctx.state.currentPageId)
ctx.setSelectedIds(new Set(created))
- pushCreatedNodesUndo(created, previousSelection, 'Place files')
+ pushCreatedNodesUndo(created, previousSelection, label)
ctx.requestRender()
+ return true
+ }
+
+ async function placeFiles(files: File[], cx: number, cy: number) {
+ const prepared = (await Promise.all(files.map(prepareAsset))).filter(
+ (asset): asset is PreparedAsset => asset !== null
+ )
+ 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 {
+ 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'
+ )
}
function placeImageFiles(files: File[], cx: number, cy: number) {
@@ -180,5 +199,5 @@ export function createClipboardAssetActions(
)
}
- return { storeImage, placeFiles, placeImageFiles }
+ return { storeImage, placeFiles, placeImageFiles, pasteSVG }
}
diff --git a/packages/core/src/icons/svg.ts b/packages/core/src/icons/svg.ts
index 89421a4d6..6317b1815 100644
--- a/packages/core/src/icons/svg.ts
+++ b/packages/core/src/icons/svg.ts
@@ -12,7 +12,13 @@ import type { Vector } from '@open-pencil/scene-graph/primitives'
import { parseSVGFragment } from '#core/io/formats/svg/document'
-import type { IconData, IconifyIconEntry, IconPathInfo, SVGClipPathRegion } from './types'
+import type {
+ IconData,
+ IconifyIconEntry,
+ IconPathInfo,
+ SVGClipPathRegion,
+ SVGElementLayer
+} from './types'
interface SVGElementInput {
type: string
@@ -37,6 +43,8 @@ interface PresentationAttributes {
strokeCap: string
strokeJoin: string
fillRule: string
+ fillOpacity: string
+ strokeOpacity: string
}
const DEFAULT_PRESENTATION: PresentationAttributes = {
@@ -45,7 +53,9 @@ const DEFAULT_PRESENTATION: PresentationAttributes = {
strokeWidth: '1',
strokeCap: 'butt',
strokeJoin: 'miter',
- fillRule: 'nonzero'
+ fillRule: 'nonzero',
+ fillOpacity: '1',
+ strokeOpacity: '1'
}
const SHAPE_NAMES = new Set(['path', 'circle', 'ellipse', 'rect', 'line', 'polygon', 'polyline'])
@@ -90,10 +100,21 @@ function presentationFor(
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)
+ 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
@@ -180,17 +201,49 @@ 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,
- presentation: PresentationAttributes,
- transform: string | null,
- clipPaths: SVGClipPathRegion[],
+ scope: Scope,
+ layer: SVGElementLayer,
result: IconPathInfo[]
): void {
- if (!SHAPE_NAMES.has(tagName)) return
const pathData = tagName === 'path' ? element.getAttribute('d') : shapeToD(tagName, element)
if (!pathData) return
+ const { presentation } = scope
const strokeWidth = Number.parseFloat(presentation.strokeWidth)
result.push({
d: pathData,
@@ -200,51 +253,44 @@ function appendShapePath(
strokeCap: presentation.strokeCap,
strokeJoin: presentation.strokeJoin,
fillRule: presentation.fillRule === 'evenodd' ? 'EVENODD' : 'NONZERO',
- transform,
- clipPaths: clipPaths.length > 0 ? clipPaths : undefined
+ fillOpacity: opacityValue(presentation.fillOpacity),
+ strokeOpacity: opacityValue(presentation.strokeOpacity),
+ transform: scope.transform,
+ clipPaths: scope.clipPaths.length > 0 ? scope.clipPaths : undefined,
+ elements: [...scope.elements, layer]
})
}
function collectUsePaths(
element: Element,
- presentation: PresentationAttributes,
- transform: string | null,
- result: IconPathInfo[],
- elementsById: ReadonlyMap<string, Element>,
- useStack: ReadonlySet<Element>,
- clipPaths: SVGClipPathRegion[]
-): boolean {
- const tagName = element.localName || element.tagName
- if (tagName !== 'use') return false
+ scope: Scope,
+ traversal: Traversal,
+ result: IconPathInfo[]
+): void {
const x = num(element, 'x')
const y = num(element, 'y')
- const useTransform =
- x !== 0 || y !== 0 ? `${transform ?? ''} translate(${x} ${y})`.trim() : transform
+ const transform =
+ x !== 0 || y !== 0 ? `${scope.transform ?? ''} translate(${x} ${y})`.trim() : scope.transform
const href = element.getAttribute('href') ?? element.getAttribute('xlink:href')
- const target = href?.startsWith('#') ? elementsById.get(href.slice(1)) : null
- if (target && !useStack.has(target)) {
+ const target = href?.startsWith('#') ? traversal.elementsById.get(href.slice(1)) : null
+ if (target && !scope.useStack.has(target)) {
collectPaths(
target,
- presentation,
- useTransform,
- result,
- elementsById,
- new Set([...useStack, target]),
- true,
- clipPaths
+ { ...scope, transform, useStack: new Set([...scope.useStack, target]), referenced: true },
+ traversal,
+ result
)
}
- return true
}
function collectClipPath(
value: string | null,
parentTransform: string | null,
- elementsById: ReadonlyMap<string, Element>
+ traversal: Traversal
): SVGClipPathRegion | null {
const match = value?.trim().match(/^url\(\s*['"]?#([^'")\s]+)['"]?\s*\)$/)
- const target = match ? elementsById.get(match[1]) : null
- if (!target || (target.localName || target.tagName) !== 'clipPath') return null
+ const target = match ? traversal.elementsById.get(match[1]) : null
+ if (!match || !target || (target.localName || target.tagName) !== 'clipPath') return null
const units =
target.getAttribute('clipPathUnits') === 'objectBoundingBox'
@@ -253,14 +299,19 @@ function collectClipPath(
const paths: IconPathInfo[] = []
collectPaths(
target,
- { ...DEFAULT_PRESENTATION, fill: '#000000' },
- units === 'objectBoundingBox' ? null : parentTransform,
- paths,
- elementsById,
- new Set([target]),
- true
+ {
+ presentation: { ...DEFAULT_PRESENTATION, fill: '#000000' },
+ transform: units === 'objectBoundingBox' ? null : parentTransform,
+ clipPaths: [],
+ elements: [],
+ useStack: new Set([target]),
+ referenced: true
+ },
+ traversal,
+ paths
)
return {
+ id: match[1],
paths: paths.map(({ d, fillRule, transform }) => ({ d, fillRule, transform })),
units
}
@@ -268,38 +319,45 @@ function collectClipPath(
function collectPaths(
element: Element,
- inherited: PresentationAttributes,
- parentTransform: string | null,
- result: IconPathInfo[],
- elementsById: ReadonlyMap<string, Element>,
- useStack: ReadonlySet<Element> = new Set(),
- referenced = false,
- inheritedClipPaths: SVGClipPathRegion[] = []
+ inherited: Scope,
+ traversal: Traversal,
+ result: IconPathInfo[]
): void {
const tagName = element.localName || element.tagName
- if (NON_RENDERED_CONTAINERS.has(tagName) && !referenced) return
+ if (NON_RENDERED_CONTAINERS.has(tagName) && !inherited.referenced) return
+
+ const transform = combinedTransform(inherited.transform, element)
+ const ownClipPath = collectClipPath(element.getAttribute('clip-path'), transform, traversal)
+ const clipPaths = ownClipPath ? [...inherited.clipPaths, ownClipPath] : inherited.clipPaths
+ const clip = ownClipPath ? clipPaths.length - 1 : null
+ const scope: Scope = {
+ ...inherited,
+ presentation: presentationFor(element, inherited.presentation),
+ transform,
+ clipPaths
+ }
- const presentation = presentationFor(element, inherited)
- const transform = combinedTransform(parentTransform, element)
- const ownClipPath = collectClipPath(element.getAttribute('clip-path'), transform, elementsById)
- const clipPaths = ownClipPath ? [...inheritedClipPaths, ownClipPath] : inheritedClipPaths
- if (collectUsePaths(element, presentation, transform, result, elementsById, useStack, clipPaths))
+ if (SHAPE_NAMES.has(tagName)) {
+ appendShapePath(
+ tagName,
+ element,
+ scope,
+ elementLayer(traversal, element, 'shape', scope, clip),
+ result
+ )
return
- appendShapePath(tagName, element, presentation, transform, clipPaths, result)
-
+ }
+ // A group is a layer; another container only becomes one to keep its clip or opacity.
+ const layer = elementLayer(traversal, element, 'group', scope, clip)
+ const isLayer =
+ tagName === 'g' || clip !== null || (layer.opacity !== 1 && element !== traversal.root)
+ const childScope = isLayer ? { ...scope, elements: [...scope.elements, layer] } : scope
+ if (tagName === 'use') {
+ collectUsePaths(element, childScope, traversal, result)
+ return
+ }
for (const child of Array.from(element.childNodes)) {
- if (isElement(child)) {
- collectPaths(
- child,
- presentation,
- transform,
- result,
- elementsById,
- useStack,
- referenced,
- clipPaths
- )
- }
+ if (isElement(child)) collectPaths(child, childScope, traversal, result)
}
}
@@ -327,7 +385,19 @@ function collectDocumentPaths(root: Element): IconPathInfo[] {
if (id) elementsById.set(id, element)
}
const result: IconPathInfo[] = []
- collectPaths(root, DEFAULT_PRESENTATION, null, result, elementsById)
+ collectPaths(
+ root,
+ {
+ presentation: DEFAULT_PRESENTATION,
+ transform: null,
+ clipPaths: [],
+ elements: [],
+ useStack: new Set(),
+ referenced: false
+ },
+ { root, elementsById, nextKey: 0 },
+ result
+ )
return result
}
diff --git a/packages/core/src/icons/types.ts b/packages/core/src/icons/types.ts
index dfdb84225..20eb35ca6 100644
--- a/packages/core/src/icons/types.ts
+++ b/packages/core/src/icons/types.ts
@@ -58,15 +58,33 @@ export interface IconPathInfo {
strokeCap: string
strokeJoin: string
fillRule: WindingRule
+ fillOpacity: number
+ strokeOpacity: number
/** Nested SVG clip regions, ordered from outermost to innermost. */
clipPaths?: SVGClipPathRegion[]
/** Raw transform attribute from the source SVG element. */
transform?: string | null
+ /** The `<g>` elements around the shape, outermost first, then the shape itself. */
+ elements: SVGElementLayer[]
+}
+
+/** An element an import turns into a layer: a group or the shape. */
+export interface SVGElementLayer {
+ /** Shared by every path drawn inside the same element. */
+ key: number
+ kind: 'group' | 'shape'
+ /** The element's `id`, when it is drawn directly rather than through `<use>`. */
+ name: string | null
+ opacity: number
+ /** The clip region this element adds to `clipPaths`, by index. */
+ clip: number | null
}
export type SVGClipPathInfo = Pick<IconPathInfo, 'd' | 'fillRule' | 'transform'>
export interface SVGClipPathRegion {
+ /** The `<clipPath>` element's `id`. */
+ id: string
paths: SVGClipPathInfo[]
units: 'userSpaceOnUse' | 'objectBoundingBox'
}
diff --git a/packages/core/src/io/formats/svg/document.ts b/packages/core/src/io/formats/svg/document.ts
index 2eb1247ea..b572d1bbe 100644
--- a/packages/core/src/io/formats/svg/document.ts
+++ b/packages/core/src/io/formats/svg/document.ts
@@ -19,6 +19,9 @@ export function parseSVGDocument(source: string): Document | null {
return xmlDocument?.documentElement?.localName === 'svg' ? xmlDocument : null
}
+/** An XML declaration or doctype, which is only valid at the start of a document. */
+const XML_PROLOG = /^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!DOCTYPE[^>[]*(?:\[[^\]]*\])?\s*>)?/i
+
export function parseSVGFragment(source: string): Document | null {
- return parseXML(`<svg xmlns="${SVG_NAMESPACE}">${source}</svg>`)
+ return parseXML(`<svg xmlns="${SVG_NAMESPACE}">${source.replace(XML_PROLOG, '')}</svg>`)
}
diff --git a/packages/core/src/io/formats/svg/import.ts b/packages/core/src/io/formats/svg/import.ts
index a668decf9..109e5d96f 100644
--- a/packages/core/src/io/formats/svg/import.ts
+++ b/packages/core/src/io/formats/svg/import.ts
@@ -1,12 +1,30 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ fitEnclosingGroups,
+ WHITE,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import type { Size } from '@open-pencil/scene-graph/primitives'
-import { createFlattenedVectorFrameChildren } from '#core/vector/vectorize/placement'
-import { svgToVectorPaths, type SVGVectorizeResult } from '#core/vector/vectorize/svg/to-vectors'
+import { BLACK } from '#core/constants'
+import type { SVGElementLayer } from '#core/icons/types'
+import { createPlacedVector, vectorizedPathPaints } from '#core/vector/vectorize/placement'
+import {
+ svgToVectorPaths,
+ type SVGVectorizeResult,
+ type VectorizedClip,
+ type VectorizedPath
+} from '#core/vector/vectorize/svg/to-vectors'
-import { parseSVGSize } from './metadata'
+import { parseSVGSize, svgRootId } from './metadata'
-export type SVGImportData = SVGVectorizeResult & Size
+export type SVGImportData = SVGVectorizeResult &
+ Size & {
+ /** The root `<svg>` element's `id`, which names the imported layer. */
+ name: string | null
+ /** Without a width, height, or viewBox the SVG has no frame, only a group of its layers. */
+ sized: boolean
+ }
export interface SVGImportOptions {
name?: string
@@ -19,6 +37,7 @@ export function prepareSVGImport(
source: string,
options: Pick<SVGImportOptions, 'defaultColor'> = {}
): SVGImportData | null {
+ const sized = parseSVGSize(source, { width: 0, height: 0 }).width > 0
const { width, height } = parseSVGSize(source)
const vectorized = svgToVectorPaths(
source,
@@ -28,7 +47,72 @@ export function prepareSVGImport(
preserveAspectRatio: true
}
)
- return vectorized ? { width, height, ...vectorized } : null
+ return vectorized ? { width, height, name: svgRootId(source), sized, ...vectorized } : null
+}
+
+function createGroup(graph: SceneGraph, parentId: string, props: Partial<SceneNode>): string {
+ return graph.createNode('GROUP', parentId, { x: 0, y: 0, ...props }).id
+}
+
+/** Figma's clip wrapper: a mask group drawn from the clip's shapes, then the clipped content. */
+function createClipGroup(
+ graph: SceneGraph,
+ parentId: string,
+ clip: VectorizedClip,
+ parentIds: Set<string>
+): string {
+ const groupId = createGroup(graph, parentId, { name: 'Clip path group' })
+ const maskId = createGroup(graph, groupId, { name: clip.id, isMask: true, maskType: 'VECTOR' })
+ for (const shape of clip.shapes) {
+ createPlacedVector(graph, maskId, shape, {
+ name: 'Vector',
+ fills: [{ type: 'SOLID', color: BLACK, opacity: 1, visible: true }]
+ })
+ }
+ parentIds.add(maskId)
+ return groupId
+}
+
+function clipFor(path: VectorizedPath, element: SVGElementLayer): VectorizedClip | null {
+ return element.clip === null ? null : (path.clips?.[element.clip] ?? null)
+}
+
+/**
+ * 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.
+ */
+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)
+ if (!shape) continue
+ let depth = 0
+ while (depth < open.length && depth < groups.length && open[depth].key === groups[depth].key) {
+ depth++
+ }
+ open.length = depth
+ let parentId = open.at(-1)?.parentId ?? rootId
+ for (const element of groups.slice(depth)) {
+ const clip = clipFor(path, element)
+ if (clip) parentId = createClipGroup(graph, parentId, clip, parentIds)
+ parentId = createGroup(graph, parentId, {
+ name: element.name ?? 'Group',
+ opacity: element.opacity
+ })
+ 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)
+ }
+ fitEnclosingGroups(graph, [...parentIds])
}
export function createSVGNodesFromImport(
@@ -37,29 +121,29 @@ export function createSVGNodesFromImport(
data: SVGImportData,
options: SVGImportOptions = {}
): SceneNode | null {
- const frame = graph.createNode('FRAME', parentId, {
- name: options.name ?? 'SVG',
- x: options.x ?? 0,
- y: options.y ?? 0,
- width: data.width,
- height: data.height,
- fills: []
- })
+ const position = { x: options.x ?? 0, y: options.y ?? 0 }
+ const root = data.sized
+ ? graph.createNode('FRAME', parentId, {
+ name: options.name ?? data.name ?? 'Frame',
+ ...position,
+ width: data.width,
+ height: data.height,
+ fills: [{ type: 'SOLID', color: WHITE, opacity: 1, visible: true }],
+ clipsContent: true
+ })
+ : graph.createNode('GROUP', parentId, {
+ name: options.name ?? data.name ?? 'Group',
+ ...position
+ })
try {
- createFlattenedVectorFrameChildren(graph, frame.id, data, {
- x: frame.x,
- y: frame.y,
- width: frame.width,
- height: frame.height,
- offsetX: 0,
- offsetY: 0
- })
- if (graph.getChildren(frame.id).length > 0) return frame
- graph.deleteNode(frame.id)
+ createSVGLayers(graph, root.id, data)
+ const created = graph.getNode(root.id)
+ if (created && graph.getChildren(root.id).length > 0) return created
+ if (created) graph.deleteNode(root.id)
return null
} catch (error) {
- graph.deleteNode(frame.id)
+ graph.deleteNode(root.id)
throw error
}
}
diff --git a/packages/core/src/io/formats/svg/index.ts b/packages/core/src/io/formats/svg/index.ts
index 2af266144..8c2905af9 100644
--- a/packages/core/src/io/formats/svg/index.ts
+++ b/packages/core/src/io/formats/svg/index.ts
@@ -6,3 +6,4 @@ export {
type SVGImportData,
type SVGImportOptions
} from './import'
+export { isSVGMarkup } from './metadata'
diff --git a/packages/core/src/io/formats/svg/metadata.ts b/packages/core/src/io/formats/svg/metadata.ts
index 0c23b56bb..1eb1fb321 100644
--- a/packages/core/src/io/formats/svg/metadata.ts
+++ b/packages/core/src/io/formats/svg/metadata.ts
@@ -40,3 +40,18 @@ export function parseSVGSize(svg: string, fallback: Size = { width: 24, height:
if (viewBox) return { width: viewBox.width, height: viewBox.height }
return fallback
}
+
+/** The root `<svg>` element's `id`. */
+export function svgRootId(svg: string): string | null {
+ return rootElement(svg)?.getAttribute('id') || null
+}
+
+/** Whether text is an SVG document, such as markup copied from a code editor or Figma's Copy as SVG. */
+export function isSVGMarkup(text: string): boolean {
+ if (
+ !/^\s*(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*(?:<!DOCTYPE[^>]*>\s*)?<svg[\s>]/i.test(text)
+ ) {
+ return false
+ }
+ return (rootElement(text)?.localName ?? '') === 'svg'
+}
diff --git a/packages/core/src/io/index.ts b/packages/core/src/io/index.ts
index 1911a4a6b..417f05d1a 100644
--- a/packages/core/src/io/index.ts
+++ b/packages/core/src/io/index.ts
@@ -28,6 +28,7 @@ export {
export {
createSVGNodes,
createSVGNodesFromImport,
+ isSVGMarkup,
prepareSVGImport,
renderNodesToSVG,
geometryBlobToSVGPath,
diff --git a/packages/core/src/tools/create/svg.ts b/packages/core/src/tools/create/svg.ts
index e171ad715..0f0c387fb 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 vector nodes. Supports common SVG shapes, inherited presentation attributes, transforms, gradients, 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> 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.',
execution: { kind: 'async', mutation: 'document' },
input: v.strictObject({
svg: v.pipe(
@@ -16,7 +16,12 @@ export const importSVG = defineTool({
v.description('SVG markup string (e.g. \'<svg viewBox="0 0 24 24"><path d="M..."/></svg>\')')
),
name: v.optional(
- v.pipe(v.string(), v.description('Name for the created frame (default: "SVG")'))
+ v.pipe(
+ v.string(),
+ v.description(
+ 'Name for the created frame or group (default: the root <svg> id, else "Frame" or "Group")'
+ )
+ )
),
color: v.optional(
v.pipe(
diff --git a/packages/core/src/vector/vectorize/placement.ts b/packages/core/src/vector/vectorize/placement.ts
index a989c94a3..8cb7ba56c 100644
--- a/packages/core/src/vector/vectorize/placement.ts
+++ b/packages/core/src/vector/vectorize/placement.ts
@@ -1,16 +1,8 @@
-import type {
- Fill,
- GeometryPath,
- SceneGraph,
- SceneNode,
- VectorNetwork
-} from '@open-pencil/scene-graph'
-import { mergeVectorNetworks } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'
import type { Rect } from '@open-pencil/scene-graph/primitives'
import { pathStrokeLineStyle } from '#core/icons/path-style'
import { computeAccurateBounds } from '#core/vector/curve-math'
-import { regenerateFillGeometry } from '#core/vector/fill-geometry'
import type { SVGVectorizeResult, VectorizedPath } from './svg/to-vectors'
@@ -28,9 +20,6 @@ interface NormalizedVectorGeometry {
bounds: Rect
}
-type VectorChildPaints = Pick<SceneNode, 'fillGeometry' | 'fills' | 'strokes'> &
- Partial<Pick<SceneNode, 'isMask' | 'maskType' | 'strokeCap' | 'strokeJoin'>>
-
function shouldTightenToContent(
node: Pick<SceneNode, 'width' | 'height' | 'rotation'>,
content: Rect
@@ -99,223 +88,51 @@ function normalizeVectorToNodeBounds(network: VectorNetwork): NormalizedVectorGe
}
}
-function createNormalizedVectorChild(
+/** A vector of this geometry, in its parent's coordinates and sized to it. */
+export function createPlacedVector(
graph: SceneGraph,
- frameId: string,
- normalized: NormalizedVectorGeometry,
- index: number,
- paints: VectorChildPaints
-): void {
- graph.createNode('VECTOR', frameId, {
- name: `path ${index + 1}`,
+ parentId: string,
+ network: VectorNetwork,
+ props: Partial<SceneNode>
+): SceneNode | null {
+ const normalized = normalizeVectorToNodeBounds(network)
+ if (!normalized) return null
+ return graph.createNode('VECTOR', parentId, {
x: normalized.bounds.x,
y: normalized.bounds.y,
width: normalized.bounds.width,
height: normalized.bounds.height,
vectorNetwork: normalized.network,
- ...paints
+ ...props
})
}
-function createVectorChild(
- graph: SceneGraph,
- frameId: string,
- path: VectorizedPath,
- placement: VectorFramePlacement,
- index: number
-): void {
- const inFrame = offsetVectorNetwork(path.vectorNetwork, placement.offsetX, placement.offsetY)
- const normalized = normalizeVectorToNodeBounds(inFrame)
- if (!normalized) return
+/** The paints and stroke line style a vectorized SVG path draws with. */
+export function vectorizedPathPaints(
+ path: VectorizedPath
+): Pick<SceneNode, 'fillGeometry' | 'fills' | 'strokes'> &
+ Partial<Pick<SceneNode, 'strokeCap' | 'strokeJoin'>> {
const stroke = path.strokes.at(0)
- createNormalizedVectorChild(graph, frameId, normalized, index, {
+ return {
fillGeometry: [],
fills: path.fills,
strokes: path.strokes,
...(stroke ? pathStrokeLineStyle(stroke) : {})
- })
-}
-
-function remapFillsToBounds(fills: Fill[], source: Rect, target: Rect): Fill[] {
- return structuredClone(fills).map((fill) => {
- const transform = fill.gradientTransform
- if (
- !transform ||
- source.width <= 0 ||
- source.height <= 0 ||
- target.width <= 0 ||
- target.height <= 0
- ) {
- return fill
- }
- const scaleX = source.width / target.width
- const scaleY = source.height / target.height
- return {
- ...fill,
- gradientTransform: {
- m00: transform.m00 * scaleX,
- m01: transform.m01 * scaleX,
- m02: (source.x - target.x) / target.width + transform.m02 * scaleX,
- m10: transform.m10 * scaleY,
- m11: transform.m11 * scaleY,
- m12: (source.y - target.y) / target.height + transform.m12 * scaleY
- }
- }
- })
-}
-
-function createFlattenedVectorChild(
- graph: SceneGraph,
- frameId: string,
- paths: VectorizedPath[],
- placement: VectorFramePlacement,
- index: number
-): void {
- const prepared = paths.map((path) => {
- const network = offsetVectorNetwork(path.vectorNetwork, placement.offsetX, placement.offsetY)
- return { path, network, bounds: computeAccurateBounds(network) }
- })
- const normalized = normalizeVectorToNodeBounds(
- mergeVectorNetworks(prepared.map(({ network }) => network))
- )
- if (!normalized) return
-
- const placeholders: GeometryPath[] = prepared.flatMap(({ path, network, bounds }) => {
- const fills = remapFillsToBounds(path.fills, bounds, normalized.bounds)
- return network.regions.map((region) => ({
- windingRule: region.windingRule,
- commandsBlob: new Uint8Array(0),
- fills: structuredClone(fills)
- }))
- })
- const fills = prepared[0]
- ? remapFillsToBounds(prepared[0].path.fills, prepared[0].bounds, normalized.bounds)
- : []
-
- createNormalizedVectorChild(graph, frameId, normalized, index, {
- fillGeometry: regenerateFillGeometry(normalized.network, placeholders),
- fills,
- strokes: []
- })
-}
-
-export function createVectorFrameChildren(
- graph: SceneGraph,
- frameId: string,
- vectorized: SVGVectorizeResult,
- placement: VectorFramePlacement
-): void {
- for (const [index, path] of vectorized.paths.entries()) {
- createVectorChild(graph, frameId, path, placement, index)
- }
-}
-
-function createClipFrame(
- graph: SceneGraph,
- frameId: string,
- placement: VectorFramePlacement,
- index: number
-): SceneNode {
- return graph.createNode('FRAME', frameId, {
- name: `clip ${index + 1}`,
- x: 0,
- y: 0,
- width: placement.width,
- height: placement.height,
- fills: []
- })
-}
-
-function createClipMaskChild(
- graph: SceneGraph,
- frameId: string,
- clipNetwork: VectorNetwork,
- placement: VectorFramePlacement,
- index: number
-): void {
- const network = offsetVectorNetwork(clipNetwork, placement.offsetX, placement.offsetY)
- const normalized = normalizeVectorToNodeBounds(network)
- if (!normalized) return
- createNormalizedVectorChild(graph, frameId, normalized, index, {
- fillGeometry: [],
- fills: [
- {
- type: 'SOLID',
- color: { r: 1, g: 1, b: 1, a: 1 },
- opacity: 1,
- visible: true
- }
- ],
- strokes: [],
- isMask: true,
- maskType: 'VECTOR'
- })
-}
-
-function createClipFrames(
- graph: SceneGraph,
- frameId: string,
- clipNetworks: VectorNetwork[],
- placement: VectorFramePlacement,
- index: number
-): string {
- let targetFrameId = frameId
- for (const clipNetwork of clipNetworks) {
- const clipFrame = createClipFrame(graph, targetFrameId, placement, index)
- createClipMaskChild(graph, clipFrame.id, clipNetwork, placement, index)
- targetFrameId = clipFrame.id
}
- return targetFrameId
}
-function isFlattenableVectorPath(path: VectorizedPath): boolean {
- return path.fills.length > 0 && path.strokes.length === 0 && path.vectorNetwork.regions.length > 0
-}
-
-/** Merge adjacent fill-only SVG paths without changing their paint order. */
-export function createFlattenedVectorFrameChildren(
+export function createVectorFrameChildren(
graph: SceneGraph,
frameId: string,
vectorized: SVGVectorizeResult,
placement: VectorFramePlacement
): void {
- let run: { path: VectorizedPath; index: number }[] = []
- let runClipNetworks: VectorNetwork[] | undefined
- const flush = () => {
- if (run.length === 0) return
- const targetFrameId = runClipNetworks
- ? createClipFrames(graph, frameId, runClipNetworks, placement, run[0].index)
- : frameId
- if (run.length > 1) {
- createFlattenedVectorChild(
- graph,
- targetFrameId,
- run.map(({ path }) => path),
- placement,
- run[0].index
- )
- } else if (run[0]) {
- createVectorChild(graph, targetFrameId, run[0].path, placement, run[0].index)
- }
- run = []
- runClipNetworks = undefined
- }
-
for (const [index, path] of vectorized.paths.entries()) {
- const clipNetworks = path.clipNetworks
- if (isFlattenableVectorPath(path)) {
- if (run.length > 0 && runClipNetworks !== clipNetworks) flush()
- runClipNetworks = clipNetworks
- run.push({ path, index })
- continue
- }
- flush()
- if (clipNetworks) {
- const targetFrameId = createClipFrames(graph, frameId, clipNetworks, placement, index)
- createVectorChild(graph, targetFrameId, path, placement, index)
- } else {
- createVectorChild(graph, frameId, path, placement, index)
- }
+ createPlacedVector(
+ graph,
+ frameId,
+ offsetVectorNetwork(path.vectorNetwork, placement.offsetX, placement.offsetY),
+ { name: `path ${index + 1}`, ...vectorizedPathPaints(path) }
+ )
}
- flush()
}
diff --git a/packages/core/src/vector/vectorize/svg/to-vectors.ts b/packages/core/src/vector/vectorize/svg/to-vectors.ts
index 2ce77b301..e94b62493 100644
--- a/packages/core/src/vector/vectorize/svg/to-vectors.ts
+++ b/packages/core/src/vector/vectorize/svg/to-vectors.ts
@@ -8,7 +8,6 @@
import svgpath from 'svgpath'
import type { Fill, Stroke, VectorNetwork, WindingRule } from '@open-pencil/scene-graph'
-import { mergeVectorNetworks } from '@open-pencil/scene-graph'
import { parseColor } from '@open-pencil/scene-graph/color'
import { computeBounds } from '@open-pencil/scene-graph/geometry'
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
@@ -16,7 +15,7 @@ import type { Rect, Size } from '@open-pencil/scene-graph/primitives'
import { createPathStroke } from '#core/icons/path-style'
import { extractPaths } from '#core/icons/svg'
-import type { IconPathInfo } from '#core/icons/types'
+import type { IconPathInfo, SVGElementLayer } from '#core/icons/types'
import { parseSVGSize, parseSVGViewBox } from '#core/io/formats/svg/metadata'
import { computeAccurateBounds } from '#core/vector/curve-math'
@@ -44,7 +43,7 @@ function unionPathBounds(paths: VectorizedPath[]): Rect {
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 }]
+ return [{ type: 'SOLID', color, opacity: path.fillOpacity, visible: true }]
}
if (path.fill === null && !path.stroke) {
return [{ type: 'SOLID', color: parseColor(defaultColor), opacity: 1, visible: true }]
@@ -55,14 +54,29 @@ function resolveFill(path: IconPathInfo, defaultColor: string): Fill[] {
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)]
+ const stroke = createPathStroke(
+ color,
+ path.strokeWidth * strokeScale,
+ path.strokeCap,
+ path.strokeJoin
+ )
+ return [{ ...stroke, opacity: path.strokeOpacity }]
+}
+
+export interface VectorizedClip {
+ /** The `<clipPath>` element's `id`. */
+ id: string
+ /** One network per clip shape. */
+ shapes: VectorNetwork[]
}
export interface VectorizedPath {
vectorNetwork: VectorNetwork
fills: Fill[]
strokes: Stroke[]
- clipNetworks?: VectorNetwork[]
+ /** The clip regions around the path, ordered like `IconPathInfo.clipPaths`. */
+ clips?: VectorizedClip[]
+ elements: SVGElementLayer[]
}
export interface SVGVectorizeResult {
@@ -93,7 +107,7 @@ export function svgToVectorPaths(
const strokeScale = Math.min(viewport.scaleX, viewport.scaleY)
const vectorized: VectorizedPath[] = []
- const clipCache = new WeakMap<NonNullable<IconPathInfo['clipPaths']>, VectorNetwork[]>()
+ const clipCache = new WeakMap<NonNullable<IconPathInfo['clipPaths']>, VectorizedClip[]>()
for (const path of paths) {
const fillRule: WindingRule = path.fillRule
const transform = path.transform ?? null
@@ -116,38 +130,38 @@ export function svgToVectorPaths(
computeAccurateBounds(network)
)
: null
- let clipNetworks: VectorNetwork[] | undefined
+ let clips: VectorizedClip[] | undefined
if (path.clipPaths) {
const hasObjectBoundingBoxClip = path.clipPaths.some(
({ units }) => units === 'objectBoundingBox'
)
- clipNetworks = hasObjectBoundingBoxClip ? undefined : clipCache.get(path.clipPaths)
- if (!clipNetworks) {
- clipNetworks = path.clipPaths.map((clipRegion) =>
- mergeVectorNetworks(
- clipRegion.paths.map((clipPath) => {
- let clipData = applySVGTransformToPath(clipPath.d, clipPath.transform ?? null)
- if (clipRegion.units === 'objectBoundingBox') {
- clipData = svgpath(clipData)
- .scale(pathBounds.width, pathBounds.height)
- .translate(pathBounds.x, pathBounds.y)
- .toString()
- return parseSVGPath(clipData, clipPath.fillRule, { includeOpenRegions: true })
- }
- return parseSVGPath(mapSVGPathToViewport(clipData, viewport), clipPath.fillRule, {
- includeOpenRegions: true
- })
+ clips = hasObjectBoundingBoxClip ? undefined : clipCache.get(path.clipPaths)
+ if (!clips) {
+ clips = path.clipPaths.map((clipRegion) => ({
+ id: clipRegion.id,
+ shapes: clipRegion.paths.map((clipPath) => {
+ let clipData = applySVGTransformToPath(clipPath.d, clipPath.transform ?? null)
+ if (clipRegion.units === 'objectBoundingBox') {
+ clipData = svgpath(clipData)
+ .scale(pathBounds.width, pathBounds.height)
+ .translate(pathBounds.x, pathBounds.y)
+ .toString()
+ return parseSVGPath(clipData, clipPath.fillRule, { includeOpenRegions: true })
+ }
+ return parseSVGPath(mapSVGPathToViewport(clipData, viewport), clipPath.fillRule, {
+ includeOpenRegions: true
})
- )
- )
- if (!hasObjectBoundingBoxClip) clipCache.set(path.clipPaths, clipNetworks)
+ })
+ }))
+ if (!hasObjectBoundingBoxClip) clipCache.set(path.clipPaths, clips)
}
}
vectorized.push({
vectorNetwork: network,
- fills: gradientFill ? [gradientFill] : solidFills,
+ fills: gradientFill ? [{ ...gradientFill, opacity: path.fillOpacity }] : solidFills,
strokes,
- clipNetworks
+ clips,
+ elements: path.elements
})
}
diff --git a/packages/core/tests/editor/clipboard/svg-paste.test.ts b/packages/core/tests/editor/clipboard/svg-paste.test.ts
new file mode 100644
index 000000000..5737a8cf3
--- /dev/null
+++ b/packages/core/tests/editor/clipboard/svg-paste.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+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', () => {
+ const editor = createEditor()
+
+ expect(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 })
+ expect(editor.graph.getChildren(frame?.id ?? '').map((node) => node.name)).toEqual(['dot'])
+ expect([...editor.state.selectedIds]).toEqual([frame?.id])
+ expect(editor.undo.undoLabel).toBe('Paste SVG')
+
+ editor.undoAction()
+ expect(editor.graph.getChildren(editor.state.currentPageId)).toHaveLength(0)
+ })
+
+ test('leaves text that is not SVG to other paste handlers', () => {
+ 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(editor.graph.getChildren(editor.state.currentPageId)).toHaveLength(0)
+ })
+})
diff --git a/packages/core/tests/io/formats/svg/import-layers.test.ts b/packages/core/tests/io/formats/svg/import-layers.test.ts
new file mode 100644
index 000000000..b29955a65
--- /dev/null
+++ b/packages/core/tests/io/formats/svg/import-layers.test.ts
@@ -0,0 +1,247 @@
+import { describe, expect, test } from 'bun:test'
+
+import { compact } from 'es-toolkit/array'
+
+import { createSVGNodes } from '@open-pencil/core/io'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+/**
+ * Each tree is what Figma 126 built from the same markup, pasted as text and through
+ * `figma.createNodeFromSvg`, which agree. Positions are relative to the imported frame, as
+ * Figma reports them for layers inside groups.
+ */
+function layerTree(svg: string): string[] {
+ const graph = new SceneGraph()
+ const root = createSVGNodes(graph, graph.getPages()[0].id, svg)
+ if (!root) throw new Error('Nothing imported')
+ const lines: string[] = []
+ const walk = (node: SceneNode, depth: number, originX: number, originY: number) => {
+ const x = depth === 0 ? 0 : originX + node.x
+ const y = depth === 0 ? 0 : originY + node.y
+ const flags = compact([
+ node.opacity !== 1 && `opacity=${node.opacity}`,
+ node.isMask && `mask=${node.maskType}`
+ ])
+ lines.push(
+ `${' '.repeat(depth)}${node.type} "${node.name}" ${Math.round(x)},${Math.round(y)} ` +
+ `${Math.round(node.width)}x${Math.round(node.height)}${flags.map((f) => ` ${f}`).join('')}`
+ )
+ for (const child of graph.getChildren(node.id)) walk(child, depth + 1, x, y)
+ }
+ walk(root, 0, 0, 0)
+ return lines
+}
+
+describe('SVG import builds the layers Figma does', () => {
+ test('groups per <g>, a vector per shape, named by id', () => {
+ expect(
+ layerTree(`<svg viewBox="0 0 120 80" width="120" height="80">
+ <rect id="background" width="120" height="80" rx="8" fill="#EEF2FF"/>
+ <g id="logo">
+ <circle cx="30" cy="40" r="16" fill="#4F46E5"/>
+ <path d="M24 40l5 5 9-10" fill="none" stroke="#fff" stroke-width="3"/>
+ </g>
+ <g id="label">
+ <rect x="56" y="30" width="48" height="8" rx="4" fill="#1E1B4B"/>
+ <rect x="56" y="44" width="32" height="6" rx="3" fill="#A5B4FC"/>
+ </g>
+ </svg>`)
+ ).toEqual([
+ 'FRAME "Frame" 0,0 120x80',
+ ' VECTOR "background" 0,0 120x80',
+ ' GROUP "logo" 14,24 32x32',
+ ' VECTOR "Vector" 14,24 32x32',
+ ' VECTOR "Vector" 24,35 14x10',
+ ' GROUP "label" 56,30 48x20',
+ ' VECTOR "Vector" 56,30 48x8',
+ ' VECTOR "Vector" 56,44 32x6'
+ ])
+ })
+
+ test('names the frame after the root id; nested groups keep transforms and opacity', () => {
+ expect(
+ layerTree(
+ '<svg id="icon-root" viewBox="0 0 100 100"><g><g transform="translate(10 10)" opacity="0.5"><rect width="20" height="20" fill="red"/><rect x="30" width="20" height="20" fill="red"/></g></g><title>Hello</title></svg>'
+ )
+ ).toEqual([
+ 'FRAME "icon-root" 0,0 100x100',
+ ' GROUP "Group" 10,10 50x20',
+ ' GROUP "Group" 10,10 50x20 opacity=0.5',
+ ' VECTOR "Vector" 10,10 20x20',
+ ' VECTOR "Vector" 40,10 20x20'
+ ])
+ })
+
+ test('keeps paths with the same fill apart', () => {
+ expect(
+ layerTree(
+ '<svg viewBox="0 0 100 100"><path d="M0 0H40V40H0Z" fill="#000"/><path d="M50 0H90V40H50Z" fill="#000"/><path d="M0 50H40V90H0Z" fill="#f00"/></svg>'
+ )
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' VECTOR "Vector" 0,0 40x40',
+ ' VECTOR "Vector" 50,0 40x40',
+ ' VECTOR "Vector" 0,50 40x40'
+ ])
+ })
+
+ test('draws each <use> as its own vector, unnamed', () => {
+ expect(
+ layerTree(
+ '<svg viewBox="0 0 100 100" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><circle id="dot" r="10" fill="blue"/></defs><use href="#dot" x="20" y="20"/><use xlink:href="#dot" x="60" y="60"/></svg>'
+ )
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' VECTOR "Vector" 10,10 20x20',
+ ' VECTOR "Vector" 50,50 20x20'
+ ])
+ })
+
+ test('wraps a clipped group in a clip group sized to its mask', () => {
+ expect(
+ layerTree(
+ '<svg viewBox="0 0 100 100"><defs><clipPath id="c"><circle cx="50" cy="50" r="40"/></clipPath></defs><g clip-path="url(#c)"><rect width="100" height="50" fill="green"/><rect y="50" width="100" height="50" fill="orange"/></g></svg>'
+ )
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "Clip path group" 10,10 80x80',
+ ' GROUP "c" 10,10 80x80 mask=VECTOR',
+ ' VECTOR "Vector" 10,10 80x80',
+ ' GROUP "Group" 0,0 100x100',
+ ' VECTOR "Vector" 0,0 100x50',
+ ' VECTOR "Vector" 0,50 100x50'
+ ])
+ })
+
+ test('wraps a clipped shape, leaving its siblings outside', () => {
+ expect(
+ layerTree(
+ '<svg viewBox="0 0 100 100"><defs><clipPath id="c"><circle cx="50" cy="50" r="40"/></clipPath></defs><rect id="box" width="100" height="100" fill="red" clip-path="url(#c)"/><rect width="10" height="10" fill="blue"/></svg>'
+ )
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "Clip path group" 10,10 80x80',
+ ' GROUP "c" 10,10 80x80 mask=VECTOR',
+ ' VECTOR "Vector" 10,10 80x80',
+ ' VECTOR "box" 0,0 100x100',
+ ' VECTOR "Vector" 0,0 10x10'
+ ])
+ })
+
+ test('draws a mask vector per clip shape and keeps the clipped group named', () => {
+ expect(
+ layerTree(
+ '<svg viewBox="0 0 100 100"><defs><clipPath id="c"><rect x="10" y="10" width="80" height="80"/><circle cx="5" cy="5" r="5"/></clipPath></defs><g id="art" clip-path="url(#c)" opacity="0.5"><rect width="100" height="100" fill="green"/></g></svg>'
+ )
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "Clip path group" 0,0 90x90',
+ ' GROUP "c" 0,0 90x90 mask=VECTOR',
+ ' VECTOR "Vector" 10,10 80x80',
+ ' VECTOR "Vector" 0,0 10x10',
+ ' GROUP "art" 0,0 100x100 opacity=0.5',
+ ' VECTOR "Vector" 0,0 100x100'
+ ])
+ })
+
+ test('nests clip groups for nested clips', () => {
+ expect(
+ layerTree(
+ '<svg viewBox="0 0 100 100"><defs><clipPath id="outer"><rect x="10" y="10" width="80" height="80"/></clipPath><clipPath id="inner"><circle cx="50" cy="50" r="25"/></clipPath></defs><g clip-path="url(#outer)"><rect width="100" height="100" fill="#f00" clip-path="url(#inner)"/></g></svg>'
+ )
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "Clip path group" 10,10 80x80',
+ ' GROUP "outer" 10,10 80x80 mask=VECTOR',
+ ' VECTOR "Vector" 10,10 80x80',
+ ' GROUP "Group" 25,25 50x50',
+ ' GROUP "Clip path group" 25,25 50x50',
+ ' GROUP "inner" 25,25 50x50 mask=VECTOR',
+ ' VECTOR "Vector" 25,25 50x50',
+ ' VECTOR "Vector" 0,0 100x100'
+ ])
+ })
+
+ test('maps an objectBoundingBox clip to the shape it clips', () => {
+ expect(
+ layerTree(
+ '<svg viewBox="0 0 200 100"><defs><clipPath id="half" clipPathUnits="objectBoundingBox"><rect width="0.5" height="1"/></clipPath></defs><rect x="20" y="10" width="60" height="80" fill="#f00" clip-path="url(#half)"/></svg>'
+ )
+ ).toEqual([
+ 'FRAME "Frame" 0,0 200x100',
+ ' GROUP "Clip path group" 20,10 30x80',
+ ' GROUP "half" 20,10 30x80 mask=VECTOR',
+ ' VECTOR "Vector" 20,10 30x80',
+ ' VECTOR "Vector" 20,10 60x80'
+ ])
+ })
+
+ test('imports an SVG without a size as a group, with element opacity', () => {
+ expect(
+ layerTree(
+ '<svg><rect width="50" height="50" fill="#f00" opacity="0.5"/><rect x="60" width="50" height="50" fill="#00f" fill-opacity="0.25"/><g fill="#0f0"><circle cx="20" cy="90" r="10"/></g></svg>'
+ )
+ ).toEqual([
+ 'GROUP "Group" 0,0 110x100',
+ ' VECTOR "Vector" 0,0 50x50 opacity=0.5',
+ ' VECTOR "Vector" 60,0 50x50',
+ ' GROUP "Group" 10,80 20x20',
+ ' VECTOR "Vector" 10,80 20x20'
+ ])
+ })
+
+ test('drops empty groups and keeps single-layer groups', () => {
+ expect(
+ layerTree(
+ '<svg viewBox="0 0 100 100"><g id="empty"></g><g id="one"><rect width="10" height="10"/></g><g><g><rect x="20" width="10" height="10"/></g></g></svg>'
+ )
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "one" 0,0 10x10',
+ ' VECTOR "Vector" 0,0 10x10',
+ ' GROUP "Group" 20,0 10x10',
+ ' GROUP "Group" 20,0 10x10',
+ ' VECTOR "Vector" 20,0 10x10'
+ ])
+ })
+})
+
+describe('SVG import paints', () => {
+ test('fills the frame white and clips to it, as Figma does', () => {
+ const graph = new SceneGraph()
+ const frame = createSVGNodes(
+ graph,
+ graph.getPages()[0].id,
+ '<svg viewBox="0 0 10 10"><rect width="10" height="10"/></svg>'
+ )
+ expect(frame?.clipsContent).toBe(true)
+ expect(frame?.fills).toEqual([
+ { type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }
+ ])
+ })
+
+ test('applies fill-opacity and stroke-opacity to the paints', () => {
+ const graph = new SceneGraph()
+ const frame = createSVGNodes(
+ graph,
+ graph.getPages()[0].id,
+ '<svg viewBox="0 0 10 10"><g fill-opacity="0.25"><rect width="10" height="10" fill="#00f" stroke="#000" stroke-opacity="0.5"/></g></svg>'
+ )
+ const group = graph.getChildren(frame?.id ?? '')[0]
+ const [vector] = graph.getChildren(group?.id ?? '')
+ expect(vector?.fills[0]?.opacity).toBe(0.25)
+ expect(vector?.strokes[0]?.opacity).toBe(0.5)
+ })
+})
+
+test('imports SVG files that start with an XML declaration and doctype', () => {
+ const graph = new SceneGraph()
+ const frame = createSVGNodes(
+ graph,
+ graph.getPages()[0].id,
+ `<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect id="mark" width="10" height="10"/></svg>`
+ )
+ expect(graph.getChildren(frame?.id ?? '').map((node) => node.name)).toEqual(['mark'])
+})
diff --git a/packages/scene-graph/src/group-bounds.ts b/packages/scene-graph/src/group-bounds.ts
index 90aa62a65..aedfd46d6 100644
--- a/packages/scene-graph/src/group-bounds.ts
+++ b/packages/scene-graph/src/group-bounds.ts
@@ -45,6 +45,16 @@ function fittedAncestors(graph: SceneGraph, parentIds: Iterable<string>): SceneN
return [...found.values()].sort((a, b) => b.depth - a.depth).map(({ node }) => node)
}
+/**
+ * The layers a group's box covers. A mask hides the layers above it outside its shape, so, as in
+ * Figma, they count only through the mask: the box is the layers below it and the masks.
+ */
+function boundingChildren(children: SceneNode[]): SceneNode[] {
+ const firstMask = children.findIndex((child) => child.isMask)
+ if (firstMask === -1) return children
+ return [...children.slice(0, firstMask), ...children.slice(firstMask).filter((c) => c.isMask)]
+}
+
/** Moves the group to its children's bounds, shifting them back so they stay put. */
function fitGroup(
graph: SceneGraph,
@@ -56,7 +66,7 @@ function fitGroup(
if (!group.parentId || group.rotation !== 0 || group.flipX || group.flipY) return
const bounds =
(group.type === 'BOOLEAN_OPERATION' ? options.booleanBounds?.(group) : null) ??
- getAxisAlignedBoundsInParent(children, group.parentId, graph)
+ getAxisAlignedBoundsInParent(boundingChildren(children), group.parentId, graph)
const dx = bounds.x - group.x
const dy = bounds.y - group.y
if (dx === 0 && dy === 0 && bounds.width === group.width && bounds.height === group.height) {
diff --git a/packages/scene-graph/tests/group-bounds.test.ts b/packages/scene-graph/tests/group-bounds.test.ts
new file mode 100644
index 000000000..87ae14a9b
--- /dev/null
+++ b/packages/scene-graph/tests/group-bounds.test.ts
@@ -0,0 +1,24 @@
+import { expect, test } from 'bun:test'
+
+import { fitEnclosingGroups, SceneGraph } from '@open-pencil/scene-graph'
+
+// Live Figma 126: a group holding a rectangle, then a mask ellipse, then a larger rectangle
+// measures 0,0 150×150, and moving the masked rectangle leaves it unchanged.
+test('a group with a mask spans the layers below the mask and the mask', () => {
+ const graph = new SceneGraph()
+ const group = graph.createNode('GROUP', graph.getPages()[0].id, { width: 1, height: 1 })
+ graph.createNode('RECTANGLE', group.id, { x: 0, y: 0, width: 20, height: 20 })
+ graph.createNode('ELLIPSE', group.id, { x: 100, y: 100, width: 50, height: 50, isMask: true })
+ const masked = graph.createNode('RECTANGLE', group.id, { x: 50, y: 50, width: 200, height: 200 })
+
+ fitEnclosingGroups(graph, [group.id])
+ const bounds = () => {
+ const { x, y, width, height } = graph.getNode(group.id) ?? group
+ return { x, y, width, height }
+ }
+ expect(bounds()).toEqual({ x: 0, y: 0, width: 150, height: 150 })
+
+ graph.updateNode(masked.id, { x: 300, y: 300 })
+ fitEnclosingGroups(graph, [group.id])
+ expect(bounds()).toEqual({ x: 0, y: 0, width: 150, height: 150 })
+})
diff --git a/src/app/editor/clipboard/paste.ts b/src/app/editor/clipboard/paste.ts
index c10c96837..e782eb2d3 100644
--- a/src/app/editor/clipboard/paste.ts
+++ b/src/app/editor/clipboard/paste.ts
@@ -1,4 +1,5 @@
import type { Editor } from '@open-pencil/core/editor'
+import { isSVGMarkup } from '@open-pencil/core/io'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import { matchingClipboardSnapshot } from './memory'
@@ -13,3 +14,21 @@ export async function pasteClipboardHTML(
if (snapshot) await editor.pasteSnapshot(snapshot, cursorPos, options)
else await editor.pasteFromHTML(html, cursorPos, options)
}
+
+/** Where a paste without a copied position goes: the cursor, else the middle of the view. */
+export function pastePoint(editor: Editor, cursorPos?: Vector): Vector {
+ const { panX, panY, zoom } = editor.state
+ return (
+ cursorPos ?? {
+ x: (-panX + window.innerWidth / 2) / zoom,
+ y: (-panY + window.innerHeight / 2) / zoom
+ }
+ )
+}
+
+/** 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 {
+ 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 7d5837d54..f23af27a6 100644
--- a/src/app/editor/clipboard/system/browser.ts
+++ b/src/app/editor/clipboard/system/browser.ts
@@ -9,7 +9,7 @@ import {
getInMemoryClipboardHTML,
setInMemoryClipboardPayload
} from '@/app/editor/clipboard/memory'
-import { pasteClipboardHTML } from '@/app/editor/clipboard/paste'
+import { pasteClipboardHTML, pasteSVGText } from '@/app/editor/clipboard/paste'
import type {
BrowserClipboardIO,
BrowserClipboardReadResult,
@@ -46,7 +46,11 @@ async function writeBrowserClipboard(payload: Promise<ClipboardPayload>): Promis
})
}
-async function readBrowserClipboardHTML(): Promise<BrowserClipboardReadResult> {
+async function readItemText(item: ClipboardItem, type: string): Promise<string | null> {
+ return item.types.includes(type) ? (await item.getType(type)).text() : null
+}
+
+async function readBrowserClipboard(): Promise<BrowserClipboardReadResult> {
if (
typeof navigator === 'undefined' ||
typeof (navigator as Partial<Navigator>).clipboard?.read !== 'function'
@@ -54,12 +58,13 @@ async function readBrowserClipboardHTML(): Promise<BrowserClipboardReadResult> {
return { available: false }
}
try {
- const items = await navigator.clipboard.read()
- for (const item of items) {
- if (!item.types.includes('text/html')) continue
- return { available: true, html: await (await item.getType('text/html')).text() }
+ const item = (await navigator.clipboard.read()).at(0)
+ if (!item) return { available: true, html: null, text: null }
+ return {
+ available: true,
+ html: await readItemText(item, 'text/html'),
+ text: await readItemText(item, 'text/plain')
}
- return { available: true, html: null }
} catch (error) {
console.warn('Browser clipboard read failed', error)
return { available: false }
@@ -68,7 +73,7 @@ async function readBrowserClipboardHTML(): Promise<BrowserClipboardReadResult> {
const browserClipboardIO: BrowserClipboardIO = {
write: writeBrowserClipboard,
- readHTML: readBrowserClipboardHTML
+ read: readBrowserClipboard
}
async function copySelection(store: EditorStore, io: BrowserClipboardIO): Promise<boolean> {
@@ -93,13 +98,13 @@ async function pasteSelection(
cursorPos: Vector | undefined,
io: BrowserClipboardIO
): Promise<boolean> {
- const result = await io.readHTML()
+ const result = await io.read()
if (result.available) {
if (result.html && isDesignClipboardHTML(result.html)) {
await pasteClipboardHTML(store, result.html, cursorPos)
return true
}
- return false
+ return result.text !== null && 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 dd9c2cad8..df5b9b541 100644
--- a/src/app/editor/clipboard/system/tauri.ts
+++ b/src/app/editor/clipboard/system/tauri.ts
@@ -7,7 +7,7 @@ import {
getInMemoryClipboardHTML,
setInMemoryClipboardPayload
} from '@/app/editor/clipboard/memory'
-import { pasteClipboardHTML } from '@/app/editor/clipboard/paste'
+import { pasteClipboardHTML, pasteSVGText } from '@/app/editor/clipboard/paste'
import type { SystemClipboard } from '@/app/editor/clipboard/system/types'
import {
readTauriClipboardText,
@@ -44,6 +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
const matchingMemoryHTML = getInMemoryClipboardHTML(text ?? '')
if (matchingMemoryHTML && isDesignClipboardHTML(matchingMemoryHTML)) {
await pasteClipboardHTML(store, matchingMemoryHTML, cursorPos)
diff --git a/src/app/editor/clipboard/system/types.ts b/src/app/editor/clipboard/system/types.ts
index ad41dd8f8..d03f234da 100644
--- a/src/app/editor/clipboard/system/types.ts
+++ b/src/app/editor/clipboard/system/types.ts
@@ -11,9 +11,9 @@ export interface SystemClipboard {
export type BrowserClipboardReadResult =
| { available: false }
- | { available: true; html: string | null }
+ | { available: true; html: string | null; text: string | null }
export interface BrowserClipboardIO {
write(payload: Promise<ClipboardPayload>): Promise<boolean>
- readHTML(): Promise<BrowserClipboardReadResult>
+ read(): Promise<BrowserClipboardReadResult>
}
diff --git a/src/app/shell/keyboard/clipboard.ts b/src/app/shell/keyboard/clipboard.ts
index 5bd2774dd..a4c9fcb5f 100644
--- a/src/app/shell/keyboard/clipboard.ts
+++ b/src/app/shell/keyboard/clipboard.ts
@@ -3,8 +3,9 @@ import { useEventListener } from '@vueuse/core'
import { extractImageFilesFromClipboard } from '@open-pencil/vue'
import type { EditorStore } from '@/app/editor/active-store'
+import { isDesignClipboardHTML } from '@/app/editor/clipboard/html'
import { getInMemoryClipboardHTML } from '@/app/editor/clipboard/memory'
-import { pasteClipboardHTML } from '@/app/editor/clipboard/paste'
+import { pasteClipboardHTML, pastePoint, pasteSVGText } from '@/app/editor/clipboard/paste'
import { browserSystemClipboard } from '@/app/editor/clipboard/system/browser'
import { tauriSystemClipboard } from '@/app/editor/clipboard/system/tauri'
import type { SystemClipboard } from '@/app/editor/clipboard/system/types'
@@ -71,14 +72,21 @@ export function bindEditorClipboard(store: EditorStore) {
const imageFiles = extractImageFilesFromClipboard(e)
if (imageFiles.length) {
- const cx = cursorPos?.x ?? (-store.state.panX + window.innerWidth / 2) / store.state.zoom
- const cy = cursorPos?.y ?? (-store.state.panY + window.innerHeight / 2) / store.state.zoom
- void store.placeImageFiles(imageFiles, cx, cy)
+ const { x, y } = pastePoint(store, cursorPos)
+ void store.placeImageFiles(imageFiles, x, y)
return
}
// Like Figma, Paste keeps the copied position; Paste here in the canvas menu uses the cursor.
const html = e.clipboardData?.getData('text/html') ?? ''
+ if (html && isDesignClipboardHTML(html)) {
+ void pasteClipboardHTML(store, html)
+ return
+ }
+
+ const text = e.clipboardData?.getData('text/plain') ?? ''
+ if (pasteSVGText(store, text, cursorPos)) return
+
if (html) {
void pasteClipboardHTML(store, html)
return
diff --git a/tests/app/editor/clipboard/system/browser.test.ts b/tests/app/editor/clipboard/system/browser.test.ts
new file mode 100644
index 000000000..e28c3afc6
--- /dev/null
+++ b/tests/app/editor/clipboard/system/browser.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, mock, test } from 'bun:test'
+
+import { createBrowserSystemClipboard } from '@/app/editor/clipboard/system/browser'
+import { createEditorStore } from '@/app/editor/session/create'
+
+const SVG = '<svg viewBox="0 0 10 10"><rect id="square" width="10" height="10"/></svg>'
+
+describe('browser clipboard paste', () => {
+ test('pastes SVG markup copied as text as layers at the cursor', async () => {
+ const store = createEditorStore()
+ const clipboard = createBrowserSystemClipboard({
+ write: async () => true,
+ read: async () => ({ available: true, html: null, text: SVG })
+ })
+
+ expect(await clipboard.paste(store, { x: 50, y: 50 })).toBe(true)
+
+ const [frame] = store.graph.getChildren(store.state.currentPageId)
+ expect(frame).toMatchObject({ type: 'FRAME', x: 45, y: 45 })
+ expect(store.graph.getChildren(frame?.id ?? '').map((node) => node.name)).toEqual(['square'])
+ })
+
+ test('prefers copied OpenPencil layers over SVG text', async () => {
+ const store = createEditorStore()
+ const paste = mock(async () => undefined)
+ store.pasteFromHTML = paste
+ const clipboard = createBrowserSystemClipboard({
+ write: async () => true,
+ read: async () => ({
+ available: true,
+ html: '<!--(openpencil)layers(/openpencil)-->',
+ text: SVG
+ })
+ })
+
+ expect(await clipboard.paste(store)).toBe(true)
+ expect(paste).toHaveBeenCalledTimes(1)
+ expect(store.graph.getChildren(store.state.currentPageId)).toHaveLength(0)
+ })
+})
diff --git a/tests/e2e/canvas/svg-paste-visual.spec.ts b/tests/e2e/canvas/svg-paste-visual.spec.ts
new file mode 100644
index 000000000..38daa7b97
--- /dev/null
+++ b/tests/e2e/canvas/svg-paste-visual.spec.ts
@@ -0,0 +1,29 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+const CLIPPED_SVG = `<svg viewBox="0 0 200 120" width="200" height="120">
+ <defs>
+ <clipPath id="badge"><circle cx="60" cy="60" r="44"/><rect x="120" y="20" width="60" height="80" rx="12"/></clipPath>
+ </defs>
+ <g id="art" clip-path="url(#badge)">
+ <rect width="200" height="60" fill="#4F46E5"/>
+ <rect y="60" width="200" height="60" fill="#F59E0B"/>
+ </g>
+ <path d="M40 60l14 14 26-30" fill="none" stroke="#fff" stroke-width="8" stroke-linecap="round"/>
+</svg>`
+
+test('pasted SVG clip paths draw through their mask groups', async () => {
+ const pasted = await editor.page.evaluate((markup) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const done = store.pasteSVG(markup, 220, 160)
+ store.clearSelection()
+ store.requestRender()
+ return done
+ }, CLIPPED_SVG)
+ expect(pasted).toBe(true)
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('svg-clip-mask-groups.png')
+})
diff --git a/tests/e2e/canvas/svg-paste-visual.spec.ts-snapshots/svg-clip-mask-groups-openpencil-darwin.png b/tests/e2e/canvas/svg-paste-visual.spec.ts-snapshots/svg-clip-mask-groups-openpencil-darwin.png
new file mode 100644
index 000000000..323b0dea7
Binary files /dev/null and b/tests/e2e/canvas/svg-paste-visual.spec.ts-snapshots/svg-clip-mask-groups-openpencil-darwin.png differ
diff --git a/tests/engine/app/clipboard/memory.test.ts b/tests/engine/app/clipboard/memory.test.ts
index e3a755426..724f580f3 100644
--- a/tests/engine/app/clipboard/memory.test.ts
+++ b/tests/engine/app/clipboard/memory.test.ts
@@ -29,7 +29,7 @@ const unavailableClipboard: SystemClipboard = {
const memoryIO: BrowserClipboardIO = {
write: async () => true,
- readHTML: async () => ({ available: false })
+ read: async () => ({ available: false })
}
const memoryClipboard = createBrowserSystemClipboard(memoryIO)
@@ -80,7 +80,7 @@ describe('in-memory clipboard', () => {
const write = mock(async (_payload: Promise<ClipboardPayload>) => true)
const clipboard = createBrowserSystemClipboard({
write,
- readHTML: async () => ({ available: false })
+ read: async () => ({ available: false })
})
const success = await clipboard.copy(store)
@@ -104,7 +104,7 @@ describe('in-memory clipboard', () => {
await payload
return true
},
- readHTML: async () => ({ available: false })
+ read: async () => ({ available: false })
})
const copying = clipboard.copy(store)
expect(writerStarted).toBe(true)
@@ -124,7 +124,7 @@ describe('in-memory clipboard', () => {
await payload
return true
},
- readHTML: async () => ({ available: false })
+ read: async () => ({ available: false })
})
expect(await executeClipboardCommand(store, 'cut', undefined, clipboard)).toBe(false)
expect(store.graph.getNode(node.id)).toBeDefined()
@@ -205,7 +205,7 @@ describe('in-memory clipboard', () => {
await payload
return false
},
- readHTML: async () => ({ available: false })
+ read: async () => ({ available: false })
})
expect(await failing.copy(second)).toBe(false)
expect(getInMemoryClipboardHTML()).toBe('')
@@ -225,7 +225,7 @@ describe('in-memory clipboard', () => {
const clipboard = createBrowserSystemClipboard({
write: async () => false,
- readHTML: async () => ({ available: false })
+ read: async () => ({ available: false })
})
const success = await clipboard.copy(store)
expect(success).toBe(false)
@@ -238,7 +238,7 @@ describe('in-memory clipboard', () => {
store.pasteFromHTML = paste
const clipboard = createBrowserSystemClipboard({
write: async () => true,
- readHTML: async () => ({ available: true, html: '<p>ordinary current clipboard</p>' })
+ read: async () => ({ available: true, html: '<p>ordinary current clipboard</p>', text: null })
})
expect(await clipboard.paste(store)).toBe(false)
@@ -252,7 +252,7 @@ describe('in-memory clipboard', () => {
store.pasteFromHTML = paste
const clipboard = createBrowserSystemClipboard({
write: async () => true,
- readHTML: async () => ({ available: true, html: null })
+ read: async () => ({ available: true, html: null, text: null })
})
expect(await clipboard.paste(store)).toBe(false)
diff --git a/tests/engine/io/svg/import.test.ts b/tests/engine/io/svg/import.test.ts
index 0aaa811a2..de417446c 100644
--- a/tests/engine/io/svg/import.test.ts
+++ b/tests/engine/io/svg/import.test.ts
@@ -37,7 +37,7 @@ describe('import_svg', () => {
).toBeGreaterThan(0)
})
- test('flattens compatible filled shapes into one vector', async () => {
+ test('imports each filled shape as its own vector', async () => {
const result = (await importSVG.execute(figma, {
svg: `<svg viewBox="0 0 100 100">
<rect x="0" y="0" width="50" height="50" fill="#ff0000"/>
@@ -47,15 +47,10 @@ describe('import_svg', () => {
})) as { id: string }
const children = graph.getChildren(result.id)
- expect(children).toHaveLength(1)
- const vector = expectDefined(children[0])
- expect(vector.type).toBe('VECTOR')
- expect(expectDefined(vector.vectorNetwork).regions).toHaveLength(3)
- expect(vector.fillGeometry).toHaveLength(3)
- expect(expectDefined(vector.fillGeometry[0]?.fills?.[0]).color.r).toBeCloseTo(1)
- expect(expectDefined(vector.fillGeometry[1]?.fills?.[0]).color.g).toBeCloseTo(1)
- expect(expectDefined(vector.fillGeometry[2]?.fills?.[0]).color.b).toBeCloseTo(1)
- expect(vector.fillGeometry.every(({ commandsBlob }) => commandsBlob.length > 0)).toBe(true)
+ expect(children.map((child) => child.type)).toEqual(['VECTOR', 'VECTOR', 'VECTOR'])
+ expect(expectDefined(children[0].fills[0]).color.r).toBeCloseTo(1)
+ expect(expectDefined(children[1].fills[0]).color.g).toBeCloseTo(1)
+ expect(expectDefined(children[2].fills[0]).color.b).toBeCloseTo(1)
const page = expectDefined(graph.getPages()[0])
const exported = expectDefined(renderNodesToSVG(graph, page.id, [result.id]))
@@ -64,21 +59,19 @@ describe('import_svg', () => {
expect(exported.match(/fill="#0000FF"/g)).toHaveLength(1)
})
- test('flattens a real multi-path provider SVG', async () => {
+ test('imports a real multi-path provider SVG shape by shape', async () => {
const svg = readFileSync(
join(process.cwd(), 'tests/fixtures/vectorize/euro_shield.recraft.svg'),
'utf8'
)
const result = (await importSVG.execute(figma, { svg })) as { id: string }
- const vector = expectDefined(graph.getChildren(result.id)[0])
- const network = expectDefined(vector.vectorNetwork)
- expect(graph.getChildren(result.id)).toHaveLength(1)
- expect(network.regions.length).toBeGreaterThan(10)
- expect(vector.fillGeometry).toHaveLength(network.regions.length)
+ const children = graph.getChildren(result.id)
+ expect(children).toHaveLength(svg.match(/<path\b/g)?.length ?? 0)
+ expect(children.every((child) => child.type === 'VECTOR')).toBe(true)
})
- test('preserves paint order around stroked paths', async () => {
+ test('keeps paint order around stroked paths', async () => {
const result = (await importSVG.execute(figma, {
svg: `<svg viewBox="0 0 100 100">
<rect x="0" y="0" width="20" height="20" fill="#ff0000"/>
@@ -90,24 +83,20 @@ describe('import_svg', () => {
})) as { id: string }
const children = graph.getChildren(result.id)
- expect(children).toHaveLength(3)
- expect(expectDefined(children[0]).fillGeometry).toHaveLength(2)
- expect(expectDefined(children[1]).strokes).toHaveLength(1)
- expect(expectDefined(children[2]).fillGeometry).toHaveLength(2)
+ expect(children.map((child) => child.strokes.length)).toEqual([0, 0, 1, 0, 0])
+ expect(children.map((child) => Math.round(child.y))).toEqual([0, 0, 30, 40, 40])
})
- test('remaps path gradients into flattened vector bounds', async () => {
+ test('maps each shape gradient to its own vector bounds', async () => {
const result = (await importSVG.execute(figma, {
svg: `<svg viewBox="0 0 100 50"><defs><linearGradient id="g"><stop offset="0" stop-color="#000"/><stop offset="1" stop-color="#fff"/></linearGradient></defs><rect width="50" height="50" fill="url(#g)"/><rect x="50" width="50" height="50" fill="url(#g)"/></svg>`
})) as { id: string }
- const vector = expectDefined(graph.getChildren(result.id)[0])
- const left = expectDefined(vector.fillGeometry[0]?.fills?.[0]?.gradientTransform)
- const right = expectDefined(vector.fillGeometry[1]?.fills?.[0]?.gradientTransform)
- expect(left.m00).toBeCloseTo(0.5)
- expect(left.m02).toBeCloseTo(0)
- expect(right.m00).toBeCloseTo(0.5)
- expect(right.m02).toBeCloseTo(0.5)
+ for (const vector of graph.getChildren(result.id)) {
+ const transform = expectDefined(vector.fills[0]?.gradientTransform)
+ expect(transform.m00).toBeCloseTo(1)
+ expect(transform.m02).toBeCloseTo(0)
+ }
const page = expectDefined(graph.getPages()[0])
const exported = expectDefined(renderNodesToSVG(graph, page.id, [result.id]))
@@ -212,10 +201,10 @@ describe('import_svg', () => {
</svg>`
})) as { id: string }
- // SVG fills a polyline as if it were closed, so both flatten into one filled vector.
+ // SVG fills a polyline as if it were closed.
const children = graph.getChildren(result.id)
- expect(children).toHaveLength(1)
- expect(expectDefined(children[0].vectorNetwork).regions).toHaveLength(2)
+ expect(children).toHaveLength(2)
+ for (const child of children) expect(expectDefined(child.vectorNetwork).regions).toHaveLength(1)
})
test('applies nested transforms through the XML tree', async () => {
@@ -265,7 +254,7 @@ describe('import_svg', () => {
expect(path.fills[0].color.b).toBeCloseTo(1)
})
- test('imports clip paths as masks for clipped paint runs', async () => {
+ test('imports a clip path as a mask group around the clipped layers', async () => {
const result = (await importSVG.execute(figma, {
svg: `<svg viewBox="0 0 100 100">
<defs><path id="mark" d="M10 10H90V90H10Z"/></defs>
@@ -278,20 +267,19 @@ describe('import_svg', () => {
</svg>`
})) as { id: string }
- const children = graph.getChildren(result.id)
- expect(children).toHaveLength(2)
- const clippedGroup = expectDefined(children[0])
- expect(clippedGroup.type).toBe('FRAME')
- const clippedChildren = graph.getChildren(clippedGroup.id)
- expect(clippedChildren).toHaveLength(2)
- expect(clippedChildren[0].isMask).toBe(true)
- expect(clippedChildren[0].maskType).toBe('VECTOR')
- expect(expectDefined(clippedChildren[0].vectorNetwork).regions).toHaveLength(1)
- expect(clippedChildren[1].fillGeometry).toHaveLength(2)
- expect(children[1].isMask).toBe(false)
+ const [clipGroup, circle] = graph.getChildren(result.id)
+ expect(clipGroup?.name).toBe('Clip path group')
+ const [mask, content] = graph.getChildren(expectDefined(clipGroup).id)
+ expect(mask?.type).toBe('GROUP')
+ expect(mask?.name).toBe('clip')
+ expect(mask?.isMask).toBe(true)
+ expect(mask?.maskType).toBe('VECTOR')
+ expect(graph.getChildren(expectDefined(mask).id)).toHaveLength(1)
+ expect(graph.getChildren(expectDefined(content).id)).toHaveLength(2)
+ expect(circle?.isMask).toBe(false)
})
- test('preserves inherited clips when expanding use elements', async () => {
+ test('keeps an inherited clip when expanding use elements', async () => {
const result = (await importSVG.execute(figma, {
svg: `<svg viewBox="0 0 100 100">
<defs>
@@ -302,11 +290,11 @@ describe('import_svg', () => {
</svg>`
})) as { id: string }
- const clipFrame = expectDefined(graph.getChildren(result.id)[0])
- const clippedChildren = graph.getChildren(clipFrame.id)
- expect(clippedChildren).toHaveLength(2)
- expect(clippedChildren[0].isMask).toBe(true)
- expect(clippedChildren[1].fills[0].color.r).toBeCloseTo(1)
+ const clipGroup = expectDefined(graph.getChildren(result.id)[0])
+ const [mask, content] = graph.getChildren(clipGroup.id)
+ expect(mask?.isMask).toBe(true)
+ const [tile] = graph.getChildren(expectDefined(content).id)
+ expect(tile?.fills[0]?.color.r).toBeCloseTo(1)
})
test('applies nested clip paths from outermost to innermost', async () => {
@@ -322,14 +310,13 @@ describe('import_svg', () => {
</svg>`
})) as { id: string }
- const outerFrame = expectDefined(graph.getChildren(result.id)[0])
- const outerChildren = graph.getChildren(outerFrame.id)
- expect(outerChildren[0].isMask).toBe(true)
- const innerFrame = expectDefined(outerChildren[1])
- expect(innerFrame.type).toBe('FRAME')
- const innerChildren = graph.getChildren(innerFrame.id)
- expect(innerChildren[0].isMask).toBe(true)
- expect(innerChildren[1].type).toBe('VECTOR')
+ const outer = expectDefined(graph.getChildren(result.id)[0])
+ const [outerMask, outerContent] = graph.getChildren(outer.id)
+ expect(outerMask?.name).toBe('outer')
+ const inner = expectDefined(graph.getChildren(expectDefined(outerContent).id)[0])
+ const [innerMask, rect] = graph.getChildren(inner.id)
+ expect(innerMask?.name).toBe('inner')
+ expect(rect?.type).toBe('VECTOR')
})
test('maps objectBoundingBox clip paths to each painted path bounds', async () => {
@@ -345,17 +332,17 @@ describe('import_svg', () => {
</svg>`
})) as { id: string }
- const [leftFrame, rightFrame] = graph.getChildren(result.id)
- const leftMask = expectDefined(graph.getChildren(expectDefined(leftFrame).id)[0])
- const rightMask = expectDefined(graph.getChildren(expectDefined(rightFrame).id)[0])
- expect(leftMask.x).toBeCloseTo(20)
- expect(leftMask.y).toBeCloseTo(10)
- expect(leftMask.width).toBeCloseTo(30)
- expect(leftMask.height).toBeCloseTo(80)
- expect(rightMask.x).toBeCloseTo(120)
- expect(rightMask.y).toBeCloseTo(20)
- expect(rightMask.width).toBeCloseTo(20)
- expect(rightMask.height).toBeCloseTo(60)
+ const masks = graph
+ .getChildren(result.id)
+ .map((clipGroup) => expectDefined(graph.getChildren(clipGroup.id)[0]))
+ expect(masks.map(({ x, y, width, height }) => [x, y, width, height])).toEqual([
+ [0, 0, 30, 80],
+ [0, 0, 20, 60]
+ ])
+ expect(graph.getChildren(result.id).map(({ x, y }) => [x, y])).toEqual([
+ [20, 10],
+ [120, 20]
+ ])
})
test('imports gradient fills through the shared SVG pipeline', async () => {