AI-native design editor. Open-source Figma alternative.
fix(fig): address instance rendering review
Victor Wads54abfca3349c
diff --git a/packages/core/src/canvas/renderer/retained-backing.ts b/packages/core/src/canvas/renderer/retained-backing.tsindex 6ef836361..de95c28e8 100644--- a/packages/core/src/canvas/renderer/retained-backing.ts+++ b/packages/core/src/canvas/renderer/retained-backing.ts@@ -1,6 +1,6 @@import type { Canvas, Image as CKImage, Surface } from 'canvaskit-wasm'-import { getAbsolutePositionFull, type SceneGraph } from '@open-pencil/scene-graph'+import { getWorldMatrix, TransformMatrix, type SceneGraph } from '@open-pencil/scene-graph'import {computeDescendantVisualBounds,effectOverflow,@@ -257,14 +257,25 @@ export function computeRetainedSubtreeBounds(const node = graph.getNode(nodeId)if (!node?.visible) continue- const absolute = getAbsolutePositionFull(node, graph)const stroke = strokeOverflow(node.strokes)const effects = effectOverflow(node.effects)+ const points = TransformMatrix.mapPoints(getWorldMatrix(node, graph), [+ -stroke - effects.left,+ -stroke - effects.top,+ node.width + stroke + effects.right,+ -stroke - effects.top,+ node.width + stroke + effects.right,+ node.height + stroke + effects.bottom,+ -stroke - effects.left,+ node.height + stroke + effects.bottom+ ])+ const xs = [points[0], points[2], points[4], points[6]]+ const ys = [points[1], points[3], points[5], points[7]]transformedBounds = unionVisualBounds(transformedBounds, {- minX: absolute.boundX - stroke - effects.left,- minY: absolute.boundY - stroke - effects.top,- maxX: absolute.boundX + absolute.width + stroke + effects.right,- maxY: absolute.boundY + absolute.height + stroke + effects.bottom+ minX: Math.min(...xs),+ minY: Math.min(...ys),+ maxX: Math.max(...xs),+ maxY: Math.max(...ys)})pending.push(...node.childIds)}diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.tsindex 0f08dc79e..0dbab466f 100644--- a/packages/core/src/editor/text.ts+++ b/packages/core/src/editor/text.ts@@ -115,7 +115,9 @@ export function createTextActions(ctx: EditorContext) {styleRuns: after.styleRuns,...sizeChanges})- applyTextInstanceOverride(ctx, containingInstances, result.nodeId, after.text)+ if (before.text !== after.text) {+ applyTextInstanceOverride(ctx, containingInstances, result.nodeId, after.text)+ }const instanceOverridesAfter = snapshotInstanceOverrides(ctx, containingInstances)ctx.state.editingTextId = nullactiveSession = nulldiff --git a/packages/core/src/kiwi/fig/import.ts b/packages/core/src/kiwi/fig/import.tsindex c285c0017..d510f20c9 100644--- a/packages/core/src/kiwi/fig/import.ts+++ b/packages/core/src/kiwi/fig/import.ts@@ -53,7 +53,7 @@ function buildAssetRefMap(changeMap: Map<string, NodeChange>): Map<string, strinconst refs = new Map<string, string>()for (const [id, nc] of changeMap) {if (typeof nc.key !== 'string') continue- refs.set(nc.key, id)+ if (typeof nc.version !== 'string' || !refs.has(nc.key)) refs.set(nc.key, id)if (typeof nc.version === 'string')refs.set(assetRefKey({ key: nc.key, version: nc.version }), id)if (typeof nc.userFacingVersion === 'string') {diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.tsindex b5aae3380..4da1f0242 100644--- a/packages/fig/src/node-change/serialize.ts+++ b/packages/fig/src/node-change/serialize.ts@@ -474,8 +474,8 @@ function computeExportTransform(node: SceneNode): Matrix {const sin = Math.sin((node.rotation * Math.PI) / 180)const m00 = cos * sx- const m01 = -sin- const m10 = sin * sx+ const m01 = -sin * sx+ const m10 = sinconst m11 = cosconst corners = [{ x: 0, y: 0 },diff --git a/packages/fig/src/node-change/style-refs.ts b/packages/fig/src/node-change/style-refs.tsindex 2b6439f57..dea557eea 100644--- a/packages/fig/src/node-change/style-refs.ts+++ b/packages/fig/src/node-change/style-refs.ts@@ -1,4 +1,4 @@-import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'+import type { NodeChange, StyleReference } from '@open-pencil/kiwi/fig/codec'import { guidToString } from '@open-pencil/kiwi/fig/guid'const TEXT_STYLE_FIELDS = [@@ -10,16 +10,7 @@ const TEXT_STYLE_FIELDS = ['textCase'] as const-type StyleRefFields = Record<string, unknown> & {- styleIdForFill?: StyleReference- styleIdForStrokeFill?: StyleReference- styleIdForText?: StyleReference- styleIdForEffect?: StyleReference- styleIdForGrid?: StyleReference-}--type AssetRef = { key: string; version?: string }-type StyleReference = { guid?: GUID; assetRef?: AssetRef }+type StyleRefFields = NodeChangetype StyleSource = Pick<NodeChange,@@ -88,7 +79,7 @@ function applyTextStyleRef(if (style?.type !== 'TEXT' || style.styleType !== 'TEXT') returnfor (const field of TEXT_STYLE_FIELDS) {if (field === 'textDecoration') fields.textDecoration = style.textDecoration- else if (style[field] !== undefined) fields[field] = style[field]+ else if (style[field] !== undefined) Object.assign(fields, { [field]: style[field] })}}diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.tsindex cae125439..c6ac1a8e8 100644--- a/packages/kiwi/src/fig/codec.ts+++ b/packages/kiwi/src/fig/codec.ts@@ -282,6 +282,13 @@ export interface PluginRelaunchData {isDeleted: boolean}+export interface AssetRef {+ key: string+ version?: string+}++export type StyleReference = { guid: GUID; assetRef?: never } | { guid?: never; assetRef: AssetRef }+export interface NodeChange {[key: string]: unknownguid?: GUID@@ -385,9 +392,11 @@ export interface NodeChange {truncatedHeight?: number}styleType?: string- styleIdForText?: { guid?: GUID }- styleIdForFill?: { guid?: GUID }- styleIdForStrokeFill?: { guid?: GUID }+ styleIdForText?: StyleReference+ styleIdForFill?: StyleReference+ styleIdForStrokeFill?: StyleReference+ styleIdForEffect?: StyleReference+ styleIdForGrid?: StyleReferencetextUserLayoutVersion?: numbertextExplicitLayoutVersion?: numbertextBidiVersion?: numberdiff --git a/tests/engine/io/fig/import/schema-coverage.test.ts b/tests/engine/io/fig/import/schema-coverage.test.tsindex b243438d6..9ffe8f5ac 100644--- a/tests/engine/io/fig/import/schema-coverage.test.ts+++ b/tests/engine/io/fig/import/schema-coverage.test.ts@@ -373,10 +373,10 @@ describe('Figma Kiwi schema coverage', () => {expect(Object.fromEntries([...buckets].map(([bucket, items]) => [bucket, items.length]))).toEqual({- modeled: 114,+ modeled: 116,schemaTag: 60,internalBookkeeping: 17,- rawPreserved: 51,+ rawPreserved: 49,styleLibraryMetadata: 39,componentInstanceMetadata: 33,textMetadata: 23,diff --git a/tests/engine/io/fig/import/style-refs.test.ts b/tests/engine/io/fig/import/style-refs.test.tsindex 6d2fac8a0..f08114358 100644--- a/tests/engine/io/fig/import/style-refs.test.ts+++ b/tests/engine/io/fig/import/style-refs.test.ts@@ -1,32 +1,72 @@import { describe, expect, test } from 'bun:test'+import { importNodeChanges } from '@open-pencil/core'import { applyStyleRefsToFields } from '@open-pencil/fig/node-change'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'describe('fig import style refs', () => {test('resolves library paint styles referenced by asset key and version', () => {- const stylePaint = {+ const fallbackPaint = {type: 'SOLID' as const,- color: { r: 0.96, g: 0.82, b: 1, a: 1 },+ color: { r: 0.2, g: 0.4, b: 0.9, a: 1 },opacity: 1,visible: true,blendMode: 'NORMAL' as const}- const fields: Record<string, unknown> = {- styleIdForFill: { assetRef: { key: 'purple-light', version: '109:20' } },- fillPaints: []+ const versionedPaint = {+ type: 'SOLID' as const,+ color: { r: 0.96, g: 0.82, b: 1, a: 1 },+ opacity: 1,+ visible: true,+ blendMode: 'NORMAL' as const}+ const parentIndex = { guid: { sessionID: 0, localID: 1 }, position: '!' }+ const graph = importNodeChanges([+ { guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT', phase: 'CREATED' },+ {+ guid: { sessionID: 0, localID: 1 },+ parentIndex: { guid: { sessionID: 0, localID: 0 }, position: '!' },+ type: 'CANVAS',+ phase: 'CREATED'+ },+ {+ guid: { sessionID: 1, localID: 700 },+ parentIndex,+ type: 'RECTANGLE',+ name: 'Fallback style',+ styleType: 'FILL',+ key: 'purple-light',+ fillPaints: [fallbackPaint]+ },+ {+ guid: { sessionID: 1, localID: 708 },+ parentIndex,+ type: 'RECTANGLE',+ name: 'Versioned style',+ styleType: 'FILL',+ key: 'purple-light',+ version: '109:20',+ fillPaints: [versionedPaint]+ },+ {+ guid: { sessionID: 2, localID: 1 },+ parentIndex,+ type: 'RECTANGLE',+ name: 'Versioned target',+ styleIdForFill: { assetRef: { key: 'purple-light', version: '109:20' } }+ },+ {+ guid: { sessionID: 2, localID: 2 },+ parentIndex,+ type: 'RECTANGLE',+ name: 'Fallback target',+ styleIdForFill: { assetRef: { key: 'purple-light' } }+ }+ ] as NodeChange[])- applyStyleRefsToFields(- new Map([['1:708', { styleType: 'FILL', fillPaints: [stylePaint] }]]),- fields,- new Map([- ['purple-light', '1:708'],- ['purple-light@109:20', '1:708']- ])- )-- expect(fields.fillPaints).toEqual([stylePaint])+ const nodes = [...graph.getAllNodes()]+ expect(nodes.find((node) => node.name === 'Versioned target')?.fills).toEqual([versionedPaint])+ expect(nodes.find((node) => node.name === 'Fallback target')?.fills).toEqual([fallbackPaint])})test('effect and grid styles replace stale direct payloads', () => {diff --git a/tests/engine/render/canvas/retained-backing.test.ts b/tests/engine/render/canvas/retained-backing.test.tsindex 981c86d7d..a647ed89a 100644--- a/tests/engine/render/canvas/retained-backing.test.ts+++ b/tests/engine/render/canvas/retained-backing.test.ts@@ -109,6 +109,35 @@ test('retained subtree bounds include descendants transformed by rotated ancestoexpect(bounds.maxY).toBeGreaterThanOrEqual(exact.boundY + exact.height)})+test('retained subtree bounds rotate directional effect overflow into world space', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ if (!page) throw new Error('Expected the default page')+ const node = graph.createNode('RECTANGLE', page.id, {+ x: 100,+ y: 100,+ width: 100,+ height: 50,+ rotation: 90,+ effects: [+ {+ type: 'DROP_SHADOW',+ color: { r: 0, g: 0, b: 0, a: 1 },+ offset: { x: 20, y: 0 },+ radius: 0,+ spread: 0,+ visible: true+ }+ ]+ })++ const base = getAbsolutePositionFull(node, graph)+ const bounds = computeRetainedSubtreeBounds(graph, node.id)++ if (!bounds) throw new Error('Expected retained subtree bounds')+ expect(bounds.maxY).toBeCloseTo(base.boundY + base.height + 20)+})+test('retained scene backing falls back when CanvasKit cannot create an offscreen surface', () => {const r = createRenderer(() => null)const canvas = createCanvas()diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.tsindex 164f16145..417e260bb 100644--- a/tests/engine/text/edit-undo.test.ts+++ b/tests/engine/text/edit-undo.test.ts@@ -137,6 +137,24 @@ describe('text edit undo', () => {expect(getNodeOrThrow(graph, instanceText.id).text).toBe('')})+ test('does not create a text override for a style-only instance edit', () => {+ const { graph, textEditor, actions } = setup()+ const page = graph.getPages()[0]+ const component = graph.createNode('COMPONENT', page.id, { width: 100, height: 20 })+ graph.createNode('TEXT', component.id, { text: 'Label', width: 100, height: 20 })+ const instance = expectDefined(graph.createInstance(component.id, page.id), 'instance')+ const instanceText = getNodeOrThrow(graph, instance.childIds[0])++ actions.startTextEditing(instanceText.id)+ const state = expectDefined(textEditor.state, 'text editor state')+ graph.updateNode(instanceText.id, {+ styleRuns: [{ start: 0, length: state.text.length, style: { fontWeight: 700 } }]+ })+ actions.commitTextEdit()++ expect(`${instanceText.id}:text` in getNodeOrThrow(graph, instance.id).overrides).toBe(false)+ })+test('commitTextEdit preserves auto-height text bounds', () => {const { graph, undo, textEditor, textNode, actions } = setup()graph.updateNode(textNode.id, { textAutoResize: 'HEIGHT', height: 18 })