Skip to content

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

fix(editor): preserve edits over imported metadata

Danila Poyarkovda9dbbb9c66f
diff --git a/packages/core/src/canvaskit.ts b/packages/core/src/canvaskit.ts
index f669a2bf3..839934ec5 100644
--- a/packages/core/src/canvaskit.ts
+++ b/packages/core/src/canvaskit.ts
@@ -15,7 +15,7 @@ export async function getCanvasKit(options?: CanvasKitOptions): Promise<CanvasKi
const defaultLocate = (file: string) => {
if (!IS_BROWSER) {
const ckPath = import.meta.resolve('canvaskit-wasm')
- return new URL(file, ckPath).pathname
+ return decodeURIComponent(new URL(file, ckPath).pathname)
}
const base = 'env' in import.meta ? import.meta.env.BASE_URL : '/'
const prefix = base === '/' ? '' : base.replace(/\/$/, '')
diff --git a/packages/core/src/kiwi/fig/import.ts b/packages/core/src/kiwi/fig/import.ts
index 9bc552316..e4a470d8b 100644
--- a/packages/core/src/kiwi/fig/import.ts
+++ b/packages/core/src/kiwi/fig/import.ts
@@ -466,13 +466,15 @@ export function importNodeChanges(
? [firstPageId, ...componentPageIds].filter(isNotNil)
: undefined
- populateAndApplyOverrides(
- graph,
- changeMap as Map<string, InstanceNodeChange>,
- guidToNodeId,
- blobs,
- activeRootIds
- )
+ graph.preserveSourceMetadataDuring(() => {
+ populateAndApplyOverrides(
+ graph,
+ changeMap as Map<string, InstanceNodeChange>,
+ guidToNodeId,
+ blobs,
+ activeRootIds
+ )
+ })
if (activeRootIds) rememberLazyFigImportContext(graph, changeMap, guidToNodeId, blobs, activeRootIds)
diff --git a/packages/core/src/scene-graph/index.ts b/packages/core/src/scene-graph/index.ts
index f196b89ad..7a2e3e3d0 100644
--- a/packages/core/src/scene-graph/index.ts
+++ b/packages/core/src/scene-graph/index.ts
@@ -7,6 +7,8 @@ import * as HitTest from './hit-test'
import * as Instances from './instances'
import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'
import { updateNodePreview } from './preview'
+import { clearEditedSourceMetadata } from './source-metadata'
+import { TEXT_PICTURE_KEYS } from './text-picture'
import * as Variables from './variables'
import { normalizeVectorNetwork } from './vector-network'
@@ -50,6 +52,7 @@ export class SceneGraph {
readonly emitter: Emitter<SceneGraphEvents> = createNanoEvents()
private absPosCache = new Map<string, Vector>()
private previewMutationDepth = 0
+ private sourceMetadataPreservationDepth = 0
positionPreviewVersion = 0
instanceIndex = new Map<string, Set<string>>()
@@ -97,11 +100,6 @@ export class SceneGraph {
}
}
- /**
- * Count all descendants of a node (children, grandchildren, etc.).
- * Used for per-page node counts in the renderer to determine if a page
- * is "large" without counting nodes on other pages.
- */
countDescendants(nodeId: string): number {
const node = this.nodes.get(nodeId)
if (!node) return 0
@@ -113,9 +111,6 @@ export class SceneGraph {
count++
const child = this.nodes.get(id)
if (child) {
- // Use a for-of loop instead of spread: stack.push(...ids) places every
- // element on the call stack as function arguments and crashes V8/JSC
- // with RangeError on nodes with >~125k direct children.
for (const childId of child.childIds) {
stack.push(childId)
}
@@ -289,14 +284,8 @@ export class SceneGraph {
return node
}
- /**
- * Properties that affect absolute position computation (getNodeLocalMatrix).
- * Changing any of these on a node invalidates the absPosCache for that node
- * and all its descendants. Other changes (fills, strokes, effects, plugin data)
- * do NOT affect absolute position and can skip the expensive cache clear.
- *
- * These names MUST match the actual SceneNode field names (not Figma API proxy names).
- */
+ static TEXT_PICTURE_KEYS: ReadonlySet<string> = TEXT_PICTURE_KEYS
+
static LAYOUT_AFFECTING_KEYS: ReadonlySet<string> = new Set([
'x',
'y',
@@ -336,24 +325,7 @@ export class SceneGraph {
'maxHeight'
])
- static TEXT_PICTURE_KEYS: ReadonlySet<string> = new Set([
- 'text',
- 'fontSize',
- 'fontFamily',
- 'fontWeight',
- 'italic',
- 'textAlignHorizontal',
- 'textDirection',
- 'textAlignVertical',
- 'lineHeight',
- 'letterSpacing',
- 'textDecoration',
- 'textCase',
- 'styleRuns',
- 'fills',
- 'width',
- 'height'
- ])
+
runPreviewUpdates(fn: () => void): void {
this.previewMutationDepth++
@@ -363,6 +335,14 @@ export class SceneGraph {
this.previewMutationDepth--
}
}
+ preserveSourceMetadataDuring(fn: () => void): void {
+ this.sourceMetadataPreservationDepth++
+ try {
+ fn()
+ } finally {
+ this.sourceMetadataPreservationDepth--
+ }
+ }
updateNodePositionPreview(id: string, x: number, y: number): void {
this.updateNodePreview(id, { x, y })
}
@@ -398,7 +378,7 @@ export class SceneGraph {
}
}
if (node.type === 'TEXT') {
- const textChanged = Object.keys(changes).some((k) => SceneGraph.TEXT_PICTURE_KEYS.has(k))
+ const textChanged = Object.keys(changes).some((k) => TEXT_PICTURE_KEYS.has(k))
if (node.textPicture && textChanged) node.textPicture = null
if (node.figmaDerivedTextGlyphs && 'text' in changes) node.figmaDerivedTextGlyphs = null
}
@@ -406,6 +386,9 @@ export class SceneGraph {
changes = Object.fromEntries(
entries.filter(([, value]) => value !== undefined)
) as Partial<SceneNode>
+ if (this.sourceMetadataPreservationDepth === 0) {
+ clearEditedSourceMetadata(node, Object.keys(changes))
+ }
if (changes.vectorNetwork) {
changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }
}
diff --git a/packages/core/src/scene-graph/source-metadata.ts b/packages/core/src/scene-graph/source-metadata.ts
new file mode 100644
index 000000000..99f8d7695
--- /dev/null
+++ b/packages/core/src/scene-graph/source-metadata.ts
@@ -0,0 +1,72 @@
+import type { SceneNode } from './types'
+
+const RAW_SIZE_KEYS = new Set(['width', 'height'])
+
+const RAW_TRANSFORM_KEYS = new Set(['x', 'y', 'rotation', 'flipX', 'flipY'])
+
+const RAW_NODE_FIELD_KEYS = new Set([
+ 'visible',
+ 'opacity',
+ 'blendMode',
+ 'fills',
+ 'strokes',
+ 'effects',
+ 'cornerRadius',
+ 'topLeftRadius',
+ 'topRightRadius',
+ 'bottomRightRadius',
+ 'bottomLeftRadius',
+ 'independentCorners',
+ 'cornerSmoothing',
+ 'text',
+ 'fontSize',
+ 'fontFamily',
+ 'fontWeight',
+ 'italic',
+ 'textAlignHorizontal',
+ 'textAlignVertical',
+ 'textAutoResize',
+ 'textCase',
+ 'textDecoration',
+ 'lineHeight',
+ 'letterSpacing',
+ 'maxLines',
+ 'styleRuns',
+ 'textTruncation',
+ 'layoutMode',
+ 'itemSpacing',
+ 'paddingTop',
+ 'paddingBottom',
+ 'paddingLeft',
+ 'paddingRight',
+ 'primaryAxisSizing',
+ 'counterAxisSizing',
+ 'primaryAxisAlign',
+ 'counterAxisAlign',
+ 'layoutWrap',
+ 'counterAxisSpacing',
+ 'layoutPositioning',
+ 'layoutGrow',
+ 'layoutAlignSelf',
+ 'counterAxisAlignContent',
+ 'itemReverseZIndex',
+ 'strokesIncludedInLayout',
+ 'layoutDirection',
+ 'horizontalConstraint',
+ 'verticalConstraint',
+ 'strokeCap',
+ 'strokeJoin',
+ 'strokeMiterLimit',
+ 'dashPattern',
+ 'arcData',
+ 'vectorNetwork',
+ 'fillGeometry',
+ 'strokeGeometry',
+ 'clipsContent'
+])
+
+export function clearEditedSourceMetadata(node: SceneNode, changeKeys: string[]): void {
+ if (changeKeys.some((key) => RAW_SIZE_KEYS.has(key))) node.source.fig.rawSize = null
+ if (changeKeys.some((key) => RAW_TRANSFORM_KEYS.has(key))) node.source.fig.rawTransform = null
+ if (changeKeys.some((key) => RAW_NODE_FIELD_KEYS.has(key))) node.source.fig.rawNodeFields = {}
+}
diff --git a/packages/core/src/scene-graph/text-picture.ts b/packages/core/src/scene-graph/text-picture.ts
new file mode 100644
index 000000000..b1d565c45
--- /dev/null
+++ b/packages/core/src/scene-graph/text-picture.ts
@@ -0,0 +1,18 @@
+export const TEXT_PICTURE_KEYS: ReadonlySet<string> = new Set([
+ 'text',
+ 'fontSize',
+ 'fontFamily',
+ 'fontWeight',
+ 'italic',
+ 'textAlignHorizontal',
+ 'textDirection',
+ 'textAlignVertical',
+ 'lineHeight',
+ 'letterSpacing',
+ 'textDecoration',
+ 'textCase',
+ 'styleRuns',
+ 'fills',
+ 'width',
+ 'height'
+])
diff --git a/packages/vue/src/canvas/surface/render-loop.ts b/packages/vue/src/canvas/surface/render-loop.ts
index 2a30878c5..0b0b1e994 100644
--- a/packages/vue/src/canvas/surface/render-loop.ts
+++ b/packages/vue/src/canvas/surface/render-loop.ts
@@ -88,9 +88,7 @@ export function createCanvasRenderLoop(
editor.onEditorEvent('viewport:changed', scheduleRender)
]
- if (options.layer !== 'scene') {
- unsubscribe.push(editor.onEditorEvent('repaint:requested', scheduleRender))
- }
+ unsubscribe.push(editor.onEditorEvent('repaint:requested', scheduleRender))
if (shouldScheduleForSelection(options.layer)) {
unsubscribe.push(editor.onEditorEvent('selection:changed', scheduleRender))
diff --git a/packages/vue/src/shared/input/move.ts b/packages/vue/src/shared/input/move.ts
index 0621828c9..9bdcf3b21 100644
--- a/packages/vue/src/shared/input/move.ts
+++ b/packages/vue/src/shared/input/move.ts
@@ -169,7 +169,15 @@ export function handleMoveUp(d: DragMove, editor: Editor) {
}
if (d.duplicated) {
- editor.commitDuplicateMove([...d.originals.keys()], d.duplicatedPreviousSelection ?? new Set())
+ const previousSelection = d.duplicatedPreviousSelection ?? new Set<string>()
+ if (!moved) {
+ for (const id of [...d.originals.keys()].toReversed()) editor.graph.deleteNode(id)
+ editor.select([...previousSelection])
+ editor.requestRender()
+ editor.setDropTarget(null)
+ return
+ }
+ editor.commitDuplicateMove([...d.originals.keys()], previousSelection)
} else if (moved) {
editor.commitMoveWithReparent(d.originals)
}
diff --git a/tests/engine/io/fig/roundtrip/source-metadata.test.ts b/tests/engine/io/fig/roundtrip/source-metadata.test.ts
index b12d7420c..d0a1400cc 100644
--- a/tests/engine/io/fig/roundtrip/source-metadata.test.ts
+++ b/tests/engine/io/fig/roundtrip/source-metadata.test.ts
@@ -1,6 +1,6 @@
import { beforeAll, describe, expect, test } from 'bun:test'
-import { exportFigFile, initCodec, SceneGraph } from '@open-pencil/core'
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
import { parseFigBuffer } from '@open-pencil/core/kiwi/fig/parse/core'
import { guidToString } from '@open-pencil/core/kiwi/fig/node-change/convert'
@@ -68,6 +68,64 @@ describe('fig roundtrip source metadata', () => {
expect(changes.get('4:4813')?.parentIndex?.position).toBe('~~~~~~~~~~3')
})
+ test('edited imported nodes export current geometry and paints', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const rect = graph.createNode('RECTANGLE', page.id, {
+ name: 'Edited imported rect',
+ x: 10,
+ y: 20,
+ width: 100,
+ height: 50,
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 1, a: 1 },
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ ]
+ })
+ rect.source.format = 'fig'
+ rect.source.id = '4:500'
+ rect.source.fig.rawSize = { x: 80, y: 40 }
+ rect.source.fig.rawTransform = { m00: 1, m01: 0, m02: 1, m10: 0, m11: 1, m12: 2 }
+ rect.source.fig.rawNodeFields.fillPaints = [
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ ]
+
+ graph.updateNode(rect.id, {
+ x: 30,
+ width: 120,
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 1, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ ]
+ })
+
+ const reimported = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)
+ const exportedRect = [...reimported.getAllNodes()].find((node) => node.name === rect.name)
+
+ expect(exportedRect?.x).toBe(30)
+ expect(exportedRect?.width).toBe(120)
+ expect(exportedRect?.fills[0]?.type).toBe('SOLID')
+ if (exportedRect?.fills[0]?.type === 'SOLID') {
+ expect(exportedRect.fills[0].color).toEqual({ r: 0, g: 1, b: 0, a: 1 })
+ }
+ })
+
test('exports imported raw vector payloads without regenerating vector data', async () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
diff --git a/tests/engine/vue/canvas/render-loop.test.ts b/tests/engine/vue/canvas/render-loop.test.ts
index 1f1a32edf..7d34632fa 100644
--- a/tests/engine/vue/canvas/render-loop.test.ts
+++ b/tests/engine/vue/canvas/render-loop.test.ts
@@ -106,7 +106,7 @@ describe('canvas render loop', () => {
}
})
- test('scene layers ignore overlay-only repaint and selection events', () => {
+ test('scene layers render on repaint but ignore selection events', () => {
const scheduler = createFrameScheduler()
try {
const { editor, emit } = createEditor()
@@ -119,11 +119,10 @@ describe('canvas render loop', () => {
{ layer: 'scene' }
)
- emit('repaint:requested')
emit('selection:changed')
expect(scheduler.pendingCount).toBe(0)
- emit('viewport:changed')
+ emit('repaint:requested')
expect(scheduler.pendingCount).toBe(1)
scheduler.flush()
expect(renders).toBe(1)
diff --git a/tests/engine/vue/input/move-threshold.test.ts b/tests/engine/vue/input/move-threshold.test.ts
index 4dbf0c953..a01e08657 100644
--- a/tests/engine/vue/input/move-threshold.test.ts
+++ b/tests/engine/vue/input/move-threshold.test.ts
@@ -46,4 +46,26 @@ describe('selection move drag threshold', () => {
expect(node?.y).toBe(27)
expect(drag.dragStarted).toBe(true)
})
+
+ test('removes duplicate created for alt-click without movement', () => {
+ const editor = createEditor()
+ const pageId = editor.state.currentPageId
+ const node = editor.graph.createNode('RECTANGLE', pageId, {
+ name: 'Box',
+ x: 10,
+ y: 20,
+ width: 100,
+ height: 80
+ })
+ editor.select([node.id])
+
+ const drag = createSelectionMoveDrag(10, 20, 100, 200, editor, true)
+ if (drag.type !== 'move') throw new Error('Expected move drag')
+ expect(editor.graph.getChildren(pageId)).toHaveLength(2)
+
+ handleMoveUp(drag, editor)
+
+ expect(editor.graph.getChildren(pageId).map((child) => child.id)).toEqual([node.id])
+ expect([...editor.state.selectedIds]).toEqual([node.id])
+ })
})