Skip to content

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

feat(fig): occurrence-scoped instance interpretation as the single .fig reader

Danila Poyarkov68c2af560017
diff --git a/AGENTS.md b/AGENTS.md
index 197dbf483..730cb0310 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -44,7 +44,7 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun
- Across package/app boundaries import the owning package's public exports, never workspace internals or forwarding-only shims. `@open-pencil/scene-graph` owns graph types and primitives; `@open-pencil/kiwi` owns low-level Kiwi/FIG helpers; `@open-pencil/core` provides the compatibility barrel plus the subpaths listed in `packages/core/package.json`.
- `bun run check:arch` enforces: public workspace exports, framework-neutral Core, no app services in views or shared UI, property-panel internals scoped to that panel.
-- Package aliases are `#core/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#dom-css/*`, `#design-jsx/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.
+- Package aliases are `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#dom-css/*`, `#design-jsx/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.
- Reuse named types from `@open-pencil/scene-graph`; do not respell `Color`, `Vector`, `SceneNode`, `Effect`, `Fill`, or `Stroke`.
## Code conventions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index abd8a1fca..3d5e2066e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
### Breaking changes
- The desktop app now requires macOS 13 or later; the web app supports Chrome 111, Edge 111, Firefox 128, and Safari 16.4 or later.
+- `.fig` reading moved to one reader, so the previous importer's exports are gone. `importNodeChanges` (`@open-pencil/core` and `@open-pencil/core/kiwi`) and `importClipboardNodes` (`@open-pencil/fig/clipboard`) are replaced by `parseFigFile` and `parseFigmaClipboard`; `populateLazyFigImportRoots` and `populateAllLazyFigImportRoots` (`@open-pencil/core/kiwi`) are replaced by `populateFigPage` and `populateAllFigPages` on `@open-pencil/core/io/formats/fig`; `populateAndApplyOverrides` (`@open-pencil/fig/instance-overrides`) is replaced by `interpretInstance` with `materializeInstance`. `FIG_PACKAGE_STATUS` now reads `document-reader`, and `assertFigPackageReady()` is gone, because `@open-pencil/fig` reads an archive into a SceneGraph itself rather than directing callers to Core.
- `sceneNodeToJSX` and `selectionToJSX` in `@open-pencil/core` produce only OpenPencil JSX, and `JSXFormat` and `JSXExportOptions` are removed. For Tailwind JSX, use `sceneNodesToTailwindJSX(graph, nodeIds)` from `@open-pencil/dom-css` or the browser-safe `@open-pencil/dom-css/export`.
- Color conversion and management and text/layout direction helpers moved from `@open-pencil/core/color` and `@open-pencil/core/text` to `@open-pencil/scene-graph/color` and `@open-pencil/scene-graph/text-direction`, and `@open-pencil/core/bytes` is removed in favor of `js-base64`; the `@open-pencil/core` root exports are unchanged. `@open-pencil/dom-css` no longer requires `@open-pencil/core`, and `exportHTMLBundle` takes a font resolver in `fonts` instead of `'assets'`; pass one built on `exportWebFontFaceAssets` from `@open-pencil/core/text/web-font/assets` to keep font files in standalone exports.
- Design JSX moved from `@open-pencil/core` to the new `@open-pencil/design-jsx` package, which depends only on `@open-pencil/scene-graph`. Import elements, paint and effect helpers, variables, `JSX_REFERENCE`, `buildComponent`, `sceneNodeToJSX`, and `selectionToJSX` from `@open-pencil/design-jsx`; `@open-pencil/core/design-jsx` now exports only `renderJSX` and `renderTree`, which render with OpenPencil's icons and layout. The `@open-pencil/core` root keeps `renderJSX` and `renderTree` and drops the other design JSX exports, `renderTreeNode` is removed in favor of `renderTree`, and the `@open-pencil/core/io/formats/jsx` subpath is removed.
@@ -32,6 +33,9 @@
- Keep an AI reply running in the chat panel, with its Stop button, when you switch pages, instead of detaching the panel from the reply in progress.
- Undo an AI edit while another page is on screen; undo previously did nothing until you returned to the page the AI changed.
- Type `parameterConsumptionMap`, `propRefValue`, and `expressionValue` in the Kiwi `NodeChange` codec, which `fig.kiwi` declares but the TypeScript definitions omitted, so reading them no longer needs a cast.
+- Read `.fig` text bound to a string variable, in a component and through an instance override, and keep the bound value where Figma does instead of applying a literal override the layer's binding retires. Text bindings also survive export.
+- Draw a `.fig` fill or stroke bound to a colour variable at the variable's own transparency, which was previously ignored in favour of the paint's own opacity — so a translucent token drew opaque, and an opacity left over from an override the binding supersedes drew in its place.
+- Export the instance overrides you make in OpenPencil to `.fig` beyond text and fill colour — strokes, size, padding and spacing, sizing modes, text styles, visibility, name, opacity, and variable bindings, including the variable bound to an overridden fill — addressed through nested instances so Figma applies each one to the right layer.
- Reject malformed effects assigned to `node.effects` in the plugin API with an error naming the invalid field, as Figma does, instead of storing them. `node.effects` now reads back in Figma's shape: layer blurs are `LAYER_BLUR` with `blurType`, and blurs no longer carry shadow fields (#786).
- Render fragments (`<>…</>`) nested inside other elements in JSX from the AI and MCP `render` tool, which previously failed with `Unknown element: <>`.
- Judge text contrast in the AI and MCP `describe` tool by its WCAG 2 ratio (4.5:1, or 3:1 for large text), the same ratio the `color-contrast` lint rule computes. It no longer reports passing dark text on mid-tone backgrounds as "dark on dark", now reports low-contrast light text, measures translucent and faded text as it is drawn, skips text whose color is bound to a variable, and says the ratio and the threshold it missed (#735).
@@ -50,6 +54,10 @@
- Load the Medium, Semibold, Bold, and other styles of installed variable fonts such as SF Pro on macOS instead of reporting them as substituted (#752).
- Ship the MIT license text in every published npm package, and add READMEs for `@open-pencil/core`, `@open-pencil/cli`, and `@open-pencil/mcp` on npm.
+### Performance
+
+- Open multi-page `.fig` documents faster: the archive is indexed once rather than once for every page, each page resolves only the layers it adds instead of rescanning the whole document, placing an instance no longer re-synchronises every other instance of its component, and archive records are copied directly rather than through `structuredClone`. A 33-page file loads about a fifth quicker, and a page of repeated components opens three to four times faster once a document is already open.
+
### Security
- Evaluate `calc` expressions through `jsep` and an arithmetic allowlist that never compiles input into JavaScript, replacing the `expr-eval` dependency and its unpatched critical code-execution advisory (GHSA-q9v2-7m5w-4693).
diff --git a/package.json b/package.json
index 5945b649b..e0122eb3c 100644
--- a/package.json
+++ b/package.json
@@ -84,7 +84,7 @@
"test:coverage": "bun tools/dev/unit-tests/src/run.ts all --include-heavy -- --coverage",
"test:type-shapes": "bun tools/checks/type-shapes/src/index.ts",
"test:tools": "bun --filter '@open-pencil/*-tools' test && bun --filter @open-pencil/harness test",
- "test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/design-jsx/src packages/core/src packages/cli/src packages/dom-css/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",
+ "test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/design-jsx/src packages/core/src packages/cli/src packages/dom-css/src packages/fig/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",
"test:packages": "bun tools/checks/package-quality/src/cli.ts verify",
"build:packages": "bun tools/release/package-artifacts/src/build.ts",
"open-pencil": "bun packages/cli/src/index.ts",
diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.ts
index a0f529539..9cc51ca6f 100644
--- a/packages/cli/src/headless.ts
+++ b/packages/cli/src/headless.ts
@@ -1,7 +1,7 @@
import { readFile } from 'node:fs/promises'
import { BUILTIN_IO_FORMATS, IORegistry, initCanvasKit } from '@open-pencil/core/io'
-import { populateAllLazyFigImportRoots, populateLazyFigImportRoots } from '@open-pencil/core/kiwi'
+import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formats/fig'
import { computeAllLayouts } from '@open-pencil/core/layout'
import type { SceneGraph } from '@open-pencil/scene-graph'
@@ -19,13 +19,13 @@ export async function loadDocument(filePath: string): Promise<SceneGraph> {
}
export function populateDocumentPage(graph: SceneGraph, pageId: string): boolean {
- const changed = populateLazyFigImportRoots(graph, [pageId])
+ const changed = populateFigPage(graph, pageId)
if (changed) computeAllLayouts(graph, pageId)
return changed
}
export function populateWholeDocument(graph: SceneGraph): boolean {
- const changed = populateAllLazyFigImportRoots(graph)
+ const changed = populateAllFigPages(graph)
if (changed) computeAllLayouts(graph)
return changed
}
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index bdadc8b1e..99ef6c298 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -41,6 +41,7 @@ import {
} from './strokes'
import { withTextParagraph } from './text'
import {
+ canDrawSavedText,
drawDerivedText,
drawReflowedPathTextSilhouettes,
isReflowedPathText
@@ -923,6 +924,10 @@ function drawResolvedPathText(
)
}
+function drawSavedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): boolean {
+ return canDrawSavedText(node, fill) && drawDerivedText(r, canvas, node)
+}
+
export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): void {
const text = node.text
if (!text) return
@@ -932,6 +937,10 @@ export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fil
canvas.clipRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.ck.ClipOp.Intersect, false)
}
+ if (drawSavedText(r, canvas, node, fill)) {
+ canvas.restore()
+ return
+ }
const fontReadiness = r.nodeFontReadiness(node)
if (fontReadiness === 'pending') {
canvas.restore()
diff --git a/packages/core/src/canvas/text/derived.ts b/packages/core/src/canvas/text/derived.ts
index afc1c4fdd..18970fbe6 100644
--- a/packages/core/src/canvas/text/derived.ts
+++ b/packages/core/src/canvas/text/derived.ts
@@ -376,12 +376,33 @@ export function drawReflowedPathTextSilhouettes(
* black fills vs white strokeGeometry
* 4. scale(fontSize,-fs) — font units → px; Y flip (font space is up-positive)
*/
+function savedTextEligibility(node: SceneNode): boolean {
+ return (
+ node.styleRuns.length === 0 ||
+ (node.fills.filter((paint) => paint.visible).length === 1 &&
+ !!node.derivedTextGlyphs?.every((glyph) => glyph.firstCharacter !== undefined) &&
+ node.styleRuns.every(
+ (run) =>
+ !run.style.fills ||
+ run.style.fills.every(
+ (paint) => paint.type === 'SOLID' && (!paint.blendMode || paint.blendMode === 'NORMAL')
+ )
+ ))
+ )
+}
+
+export function canDrawSavedText(node: SceneNode, fill?: Fill): boolean {
+ if (fill && fill.type !== 'SOLID') return false
+ return savedTextEligibility(node)
+}
+
export function drawDerivedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boolean {
if (!node.derivedTextGlyphs?.length) return false
// Pixel-snap is for horizontal Figma baselines only — on a curve it stair-steps
// letter positions and breaks registration with strokeGeometry.
const snapBaselines = !hasRotatedDerivedGlyphs(node)
+ const savedTextEligible = savedTextEligibility(node)
let underlineBaselineY = 0
for (const glyph of node.derivedTextGlyphs) {
const glyphY = snapBaselines ? snapDerivedGlyphBaseline(glyph.y) : glyph.y
@@ -391,7 +412,29 @@ export function drawDerivedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode
applyGlyphEmTransform(canvas, glyph, glyphY)
const shouldUseHardCoverage = shouldUseHardDerivedGlyphCoverage(node)
if (shouldUseHardCoverage) r.fillPaint.setAntiAlias(false)
- canvas.drawPath(path, r.fillPaint)
+ const run =
+ glyph.firstCharacter === undefined
+ ? undefined
+ : node.styleRuns.find(
+ (run) =>
+ glyph.firstCharacter !== undefined &&
+ glyph.firstCharacter >= run.start &&
+ glyph.firstCharacter < run.start + run.length
+ )
+ const fills = run?.style.fills
+ if (fills && savedTextEligible) {
+ const paint = r.fillPaint.copy()
+ try {
+ for (const fill of fills) {
+ if (!fill.visible || fill.type !== 'SOLID') continue
+ const color = fill.color
+ paint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a * fill.opacity))
+ canvas.drawPath(path, paint)
+ }
+ } finally {
+ paint.delete()
+ }
+ } else canvas.drawPath(path, r.fillPaint)
if (shouldUseHardCoverage) r.fillPaint.setAntiAlias(true)
canvas.restore()
path.delete()
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index e1dc7d620..a0383a97b 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -1,14 +1,17 @@
import { embedClipboardImages, encodeFigmaClipboard } from '@open-pencil/fig/clipboard'
-export {
- parseFigmaClipboard,
- importClipboardNodes,
- figmaNodesBounds
-} from '@open-pencil/fig/clipboard'
+export { parseFigmaClipboard, figmaNodesBounds } from '@open-pencil/fig/clipboard'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import type { GUID, NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/codec'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ appendVariableNodeChanges,
+ assignSharedStyleGuids,
+ assignVariableGuids
+} from '#core/io/formats/fig/variable-export'
+
import { shapeTextForClipboard } from './canvas/text/clipboard'
+import { prepareClipboardImport } from './clipboard/fig-import'
import {
sceneNodeToKiwi,
makeDocumentNodeChange,
@@ -22,6 +25,26 @@ export async function prefetchFigmaSchema(): Promise<void> {
await initCodec()
}
+export function importClipboardNodes(
+ nodeChanges: KiwiNodeChange[],
+ graph: SceneGraph,
+ targetParentId: string,
+ offsetX = 0,
+ offsetY = 0,
+ blobs: Uint8Array[] = []
+): string[] {
+ const operation = prepareClipboardImport(
+ nodeChanges,
+ graph,
+ targetParentId,
+ blobs,
+ offsetX,
+ offsetY
+ )
+ operation.commit()
+ return operation.plan.rootIds
+}
+
export async function buildFigmaClipboardHTML(
nodes: SceneNode[],
graph: SceneGraph
@@ -49,26 +72,72 @@ export async function buildFigmaClipboardHTML(
const nodeIdToGuid = new Map<string, GUID>()
const assignedGuidValues = new Set<string>()
const blobs: Uint8Array[] = []
+ const variableIds = new Map<string, GUID>()
+ const modeIds = new Map<string, GUID>()
+ assignVariableGuids(graph, localIdCounter, variableIds, modeIds, assignedGuidValues, new Set())
+ assignSharedStyleGuids(
+ [...graph.nodes.values()].filter((node) => node.sharedStyleType !== null),
+ localIdCounter,
+ nodeIdToGuid,
+ assignedGuidValues
+ )
for (let i = 0; i < nodes.length; i++) {
collectTextNodes(nodes[i])
nodeChanges.push(
- ...sceneNodeToKiwi(
- nodes[i],
- canvasGuid,
- i,
- localIdCounter,
- graph,
- blobs,
+ ...sceneNodeToKiwi(nodes[i], canvasGuid, i, localIdCounter, graph, blobs, {
+ nodeIdToGuid,
+ fontDigestMap,
+ varIdToGuid: variableIds,
+ assignedGuidValues,
+ modeIdToGuid: modeIds
+ })
+ )
+ }
+
+ const dependencies = new Map<string, SceneNode>()
+ const selected = new Set<string>()
+ const mark = (node: SceneNode): void => {
+ selected.add(node.id)
+ for (const child of graph.getChildren(node.id)) mark(child)
+ }
+ for (const node of nodes) mark(node)
+ const visitDependencies = (node: SceneNode): void => {
+ if (
+ node.type === 'INSTANCE' &&
+ node.componentId &&
+ !selected.has(node.componentId) &&
+ !dependencies.has(node.componentId)
+ ) {
+ const component = graph.getNode(node.componentId)
+ if (!component) throw new Error(`Missing clipboard component ${node.componentId}`)
+ dependencies.set(component.id, component)
+ visitDependencies(component)
+ }
+ for (const child of graph.getChildren(node.id)) visitDependencies(child)
+ }
+ for (const node of nodes) visitDependencies(node)
+ for (const node of graph.getAllNodes())
+ if (node.sharedStyleType && !selected.has(node.id)) dependencies.set(node.id, node)
+ const dependencyCanvas = { sessionID: 0, localID: 2 }
+ if (dependencies.size || graph.variableCollections.size)
+ nodeChanges.push({
+ ...makeCanvasNodeChange(dependencyCanvas, docGuid, '"', 'Clipboard dependencies'),
+ internalOnly: true
+ })
+ for (const component of dependencies.values()) {
+ collectTextNodes(component)
+ nodeChanges.push(
+ ...sceneNodeToKiwi(component, dependencyCanvas, 0, localIdCounter, graph, blobs, {
nodeIdToGuid,
fontDigestMap,
- undefined,
- undefined,
- undefined,
- assignedGuidValues
- )
+ varIdToGuid: variableIds,
+ assignedGuidValues,
+ modeIdToGuid: modeIds
+ })
)
}
+ appendVariableNodeChanges(graph, nodeChanges, dependencyCanvas, variableIds, modeIds)
const textNodeQueue = [...exportedTextNodes]
await Promise.all(
nodeChanges.map(async (change) => {
diff --git a/packages/core/src/clipboard/fig-import.ts b/packages/core/src/clipboard/fig-import.ts
new file mode 100644
index 000000000..60eb3eb63
--- /dev/null
+++ b/packages/core/src/clipboard/fig-import.ts
@@ -0,0 +1,46 @@
+import { materializeFigFragment } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import {
+ captureTransferredState,
+ removeGraphTransfer,
+ applyGraphTransfer,
+ prepareGraphTransfer,
+ type SceneGraph
+} from '@open-pencil/scene-graph'
+
+/** Interpret in isolation before any destination mutation. */
+export function prepareClipboardImport(
+ changes: NodeChange[],
+ graph: SceneGraph,
+ parentId: string,
+ blobs: Uint8Array[] = [],
+ offsetX = 0,
+ offsetY = 0
+) {
+ const fragment = materializeFigFragment(changes, blobs, { missingComponent: 'detach-empty' })
+ const plan = prepareGraphTransfer({
+ source: fragment.graph,
+ rootIds: fragment.rootIds,
+ dependencyPageIds: fragment.dependencyPageIds,
+ target: graph,
+ parentId
+ })
+ const roots = new Set(plan.rootIds)
+ for (const node of plan.nodes)
+ if (roots.has(node.id)) {
+ node.props.x = (node.props.x ?? 0) + offsetX
+ node.props.y = (node.props.y ?? 0) + offsetY
+ }
+ let snapshot = plan
+ const operation = {
+ sourceIds: fragment.sources,
+ plan,
+ capture: () => {
+ snapshot = captureTransferredState(graph, plan)
+ },
+ undo: () => removeGraphTransfer(graph, snapshot),
+ redo: () => applyGraphTransfer(graph, snapshot),
+ commit: () => applyGraphTransfer(graph, plan)
+ }
+ return operation
+}
diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.ts
index 9391e8f9a..13c8dbb7b 100644
--- a/packages/core/src/editor/clipboard.ts
+++ b/packages/core/src/editor/clipboard.ts
@@ -1,11 +1,9 @@
+import { CommittedGraphEventError } from '@open-pencil/scene-graph'
import type { SceneNode } from '@open-pencil/scene-graph'
import type { Vector } from '@open-pencil/scene-graph/primitives'
-import {
- importClipboardNodes,
- parseFigmaClipboard,
- parseOpenPencilClipboard
-} from '#core/clipboard'
+import { parseFigmaClipboard, parseOpenPencilClipboard } from '#core/clipboard'
+import { prepareClipboardImport } from '#core/clipboard/fig-import'
import { computeAllLayouts } from '#core/layout'
import { createClipboardAssetActions } from './clipboard/assets'
@@ -15,6 +13,7 @@ import { importClipboardDependencies } from './clipboard/dependencies'
import { createClipboardExportActions } from './clipboard/export'
import { createClipboardFontActions } from './clipboard/fonts'
import { deleteIds, recreateSnapshots, restoreDeletedEntries } from './clipboard/history'
+import type { PasteHistoryOperation } from './clipboard/paste-replace'
import { replaceTargetsWithCreated, selectedReplacementTargets } from './clipboard/paste-replace'
import { resolvePasteTarget } from './clipboard/paste-target'
import { createClipboardPlacementActions } from './clipboard/placement'
@@ -68,18 +67,26 @@ export function createClipboardActions(ctx: EditorContext) {
}
}
- function pushCreatedNodesUndo(created: string[], prevSelection: Set<string>, label = 'Paste') {
+ function pushCreatedNodesUndo(
+ created: string[],
+ prevSelection: Set<string>,
+ label = 'Paste',
+ operation?: PasteHistoryOperation
+ ) {
const allNodes = collectSubtrees(ctx.graph, created)
const pageId = ctx.state.currentPageId
+ operation?.capture()
ctx.undo.push({
label,
forward: () => {
- recreateSnapshots(ctx, allNodes, pageId)
+ if (operation) operation.redo()
+ else recreateSnapshots(ctx, allNodes, pageId)
computeAllLayouts(ctx.graph, pageId)
ctx.setSelectedIds(new Set(created))
},
inverse: () => {
- deleteIds(ctx, created)
+ if (operation) operation.undo()
+ else deleteIds(ctx, created)
computeAllLayouts(ctx.graph, pageId)
ctx.setSelectedIds(prevSelection)
}
@@ -146,7 +153,15 @@ export function createClipboardActions(ctx: EditorContext) {
const prevSelection = new Set(ctx.state.selectedIds)
const replacementTargets = options.replaceSelection ? selectedReplacementTargets(ctx) : []
const pasteTarget = replacementTargets[0]?.parentId ?? resolvePasteTarget(ctx)
- const created = importClipboardNodes(figma.nodes, ctx.graph, pasteTarget, 0, 0, figma.blobs)
+ const operation = prepareClipboardImport(figma.nodes, ctx.graph, pasteTarget, figma.blobs)
+ let deliveryError: CommittedGraphEventError | undefined
+ try {
+ operation.commit()
+ } catch (error) {
+ if (!(error instanceof CommittedGraphEventError)) throw error
+ deliveryError = error
+ }
+ const created = operation.plan.rootIds
if (created.length === 0) return
if (replacementTargets.length > 0) {
@@ -155,7 +170,8 @@ export function createClipboardActions(ctx: EditorContext) {
placementActions.centerNodesAt,
created,
replacementTargets,
- prevSelection
+ prevSelection,
+ operation
)
} else {
const { width: viewW, height: viewH } = ctx.getViewportSize()
@@ -164,9 +180,10 @@ export function createClipboardActions(ctx: EditorContext) {
placementActions.centerNodesAt(created, cx, cy)
computeAllLayouts(ctx.graph, ctx.state.currentPageId)
ctx.setSelectedIds(new Set(created))
- pushCreatedNodesUndo(created, prevSelection)
+ pushCreatedNodesUndo(created, prevSelection, 'Paste', operation)
}
+ if (deliveryError) throw deliveryError
await Promise.all([
hydrateFigmaClipboardImages(figma.meta.fileKey, created),
fontActions.loadFontsForNodes(created)
diff --git a/packages/core/src/editor/clipboard/copy.ts b/packages/core/src/editor/clipboard/copy.ts
index 3933c247d..bb48b0adb 100644
--- a/packages/core/src/editor/clipboard/copy.ts
+++ b/packages/core/src/editor/clipboard/copy.ts
@@ -13,6 +13,10 @@ export interface ClipboardPayload {
plainText: string
}
+/**
+ * The Figma payload is encoded from the snapshot alone, so everything the encoder resolves
+ * by id — component dependencies, styles, variables — has to be indexed alongside the nodes.
+ */
function graphForSnapshot(ctx: EditorContext, snapshot: ClipboardSnapshot): SceneGraph {
const graph = new SceneGraph()
graph.documentColorSpace = ctx.graph.documentColorSpace
@@ -22,6 +26,12 @@ function graphForSnapshot(ctx: EditorContext, snapshot: ClipboardSnapshot): Scen
for (const child of node.children ?? []) index(child)
}
for (const node of snapshot.nodes) index(node)
+ for (const node of snapshot.componentDependencies) index(node)
+ for (const node of snapshot.styleDefinitions) index(node)
+ for (const collection of snapshot.variableDependencies.collections)
+ graph.variableCollections.set(collection.id, collection)
+ for (const variable of snapshot.variableDependencies.variables)
+ graph.variables.set(variable.id, variable)
return graph
}
diff --git a/packages/core/src/editor/clipboard/paste-replace.ts b/packages/core/src/editor/clipboard/paste-replace.ts
index a3d033db5..57bca3901 100644
--- a/packages/core/src/editor/clipboard/paste-replace.ts
+++ b/packages/core/src/editor/clipboard/paste-replace.ts
@@ -8,6 +8,12 @@ import { computeAllLayouts } from '#core/layout'
import { deleteIds, type DeletedEntry, recreateSnapshots, restoreDeletedEntries } from './history'
import { collectSubtrees, snapshotSubtree } from './subtree-history'
+export interface PasteHistoryOperation {
+ capture: () => void
+ undo: () => void
+ redo: () => void
+}
+
type CenterNodesAt = (nodeIds: string[], cx: number, cy: number) => void
export function selectedReplacementTargets(ctx: EditorContext) {
@@ -38,21 +44,28 @@ function pushPasteReplaceUndo(
ctx: EditorContext,
created: string[],
deleted: DeletedEntry[],
- prevSelection: Set<string>
+ prevSelection: Set<string>,
+ operation?: PasteHistoryOperation
) {
const createdSnapshots = collectSubtrees(ctx.graph, created)
const pageId = ctx.state.currentPageId
+ operation?.capture()
ctx.undo.push({
label: 'Paste to replace',
forward: () => {
- for (const { id } of deleted) ctx.graph.deleteNode(id)
- recreateSnapshots(ctx, createdSnapshots, pageId)
- reorderCreatedAtReplacementIndex(ctx, created, deleted)
+ ctx.graph.withBufferedEvents(() => {
+ // Restore first: validation or insertion failure must not delete the original targets.
+ if (operation) operation.redo()
+ else recreateSnapshots(ctx, createdSnapshots, pageId)
+ for (const { id } of deleted) ctx.graph.deleteNode(id)
+ reorderCreatedAtReplacementIndex(ctx, created, deleted)
+ })
computeAllLayouts(ctx.graph, pageId)
ctx.setSelectedIds(new Set(created))
},
inverse: () => {
- deleteIds(ctx, created)
+ if (operation) operation.undo()
+ else deleteIds(ctx, created)
restoreDeletedEntries(ctx, deleted)
computeAllLayouts(ctx.graph, pageId)
ctx.setSelectedIds(prevSelection)
@@ -65,7 +78,8 @@ export function replaceTargetsWithCreated(
centerNodesAt: CenterNodesAt,
created: string[],
targets: SceneNode[],
- prevSelection: Set<string>
+ prevSelection: Set<string>,
+ operation?: PasteHistoryOperation
) {
if (created.length === 0 || targets.length === 0) return false
const deleted = targets.map((node) => {
@@ -89,6 +103,6 @@ export function replaceTargetsWithCreated(
for (const { id } of deleted) ctx.graph.deleteNode(id)
computeAllLayouts(ctx.graph, ctx.state.currentPageId)
ctx.setSelectedIds(new Set(created))
- pushPasteReplaceUndo(ctx, created, deleted, prevSelection)
+ pushPasteReplaceUndo(ctx, created, deleted, prevSelection, operation)
return true
}
diff --git a/packages/core/src/editor/component-sync.ts b/packages/core/src/editor/component-sync.ts
index 5b60a0ef6..ac69effe8 100644
--- a/packages/core/src/editor/component-sync.ts
+++ b/packages/core/src/editor/component-sync.ts
@@ -2,6 +2,38 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { computeAllLayouts } from '#core/layout'
+function componentSyncOrder(graph: SceneGraph, seeds: Set<string>): string[] {
+ const dependents = new Map<string, Set<string>>()
+ const discover = (id: string): void => {
+ if (dependents.has(id)) return
+ const parents = new Set<string>()
+ dependents.set(id, parents)
+ for (const instance of graph.getInstances(id)) {
+ let parent = instance.parentId ? graph.getNode(instance.parentId) : undefined
+ while (parent && parent.type !== 'COMPONENT') {
+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
+ }
+ if (parent) parents.add(parent.id)
+ }
+ for (const parent of parents) discover(parent)
+ }
+ for (const id of seeds) discover(id)
+ const result: string[] = []
+ const active = new Set<string>()
+ const visited = new Set<string>()
+ const visit = (id: string): void => {
+ if (active.has(id)) throw new Error('Cyclic component synchronization dependency')
+ if (visited.has(id)) return
+ active.add(id)
+ for (const parent of dependents.get(id) ?? []) visit(parent)
+ active.delete(id)
+ visited.add(id)
+ result.push(id)
+ }
+ for (const id of seeds) visit(id)
+ return result.reverse()
+}
+
type ComputeLayouts = (graph: SceneGraph, scopeId?: string) => void
/** Pages are `CANVAS` nodes; layout recomputation is scoped to them. */
@@ -63,7 +95,7 @@ export function createComponentSyncScheduler(
current = current.parentId ? graph.getNode(current.parentId) : undefined
}
}
- for (const compId of componentIds) {
+ for (const compId of componentSyncOrder(graph, componentIds)) {
graph.syncInstances(compId)
}
if (componentIds.size > 0) {
diff --git a/packages/core/src/editor/components/properties.ts b/packages/core/src/editor/components/properties.ts
index 29dd1889b..a31c886cf 100644
--- a/packages/core/src/editor/components/properties.ts
+++ b/packages/core/src/editor/components/properties.ts
@@ -3,7 +3,8 @@ import {
cloneInstanceOverrideState,
componentPropertyDefinitions,
findComponentPropertyTarget,
- resolveComponentPropertyValue
+ resolveComponentPropertyValue,
+ setInstanceOverride
} from '@open-pencil/scene-graph'
import type {
ComponentPropertyDefinition,
@@ -120,11 +121,11 @@ export function createComponentPropertyActions(
inverse: () => {
const live = ctx.graph.getNode(instanceId)
if (live) {
+ const restoredTarget = propertyTarget(ctx, live, propertyId)
ctx.graph.updateNode(instanceId, {
componentPropertyAssignments: previousAssignments,
instanceOverrides: cloneInstanceOverrideState(previousOverrides)
})
- const restoredTarget = propertyTarget(ctx, live, propertyId)
if (restoredTarget?.field === 'TEXT' && restoredTarget.node.type === 'TEXT') {
ctx.graph.updateNode(restoredTarget.node.id, { text: previousValue })
} else if (restoredTarget?.field === 'VISIBLE') {
@@ -133,6 +134,14 @@ export function createComponentPropertyActions(
const componentId = swapTargetId(ctx, previousValue)
if (componentId && restoredTarget.node.type === 'INSTANCE') {
ctx.graph.swapInstanceComponent(restoredTarget.node.id, componentId)
+ setInstanceOverride(
+ live.instanceOverrides,
+ live.id,
+ restoredTarget.node.id,
+ 'sourceComponentId',
+ restoredTarget.source.id
+ )
+ ctx.graph.updateNode(live.id, { instanceOverrides: live.instanceOverrides })
}
}
}
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 0abb14a80..2b7c10b1a 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -8,10 +8,10 @@ import { UndoManager } from '@open-pencil/scene-graph/undo'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { prefetchFigmaSchema } from '#core/clipboard'
import { IS_BROWSER } from '#core/constants'
-import { clearLazyFigImportContext } from '#core/kiwi/fig/lazy-import'
import { releaseFigPopulationWorker } from '#core/kiwi/fig/population/client'
import { releaseOriginalFigArchive } from '#core/kiwi/fig/session/original-archive'
import { setTextMeasurer } from '#core/layout'
+import { createLayoutRunner } from '#core/layout/mutations'
import { emitNavigationTrace } from '#core/profiler'
import { TextEditor } from '#core/text/editor'
import { fontManager } from '#core/text/fonts'
@@ -29,7 +29,6 @@ import { createComponentActions } from './components'
import { createGraphEventSubscription } from './graph-events'
import { createGraphReadActions } from './graph-reads'
import { createGuideActions } from './guides'
-import { createLayoutRunner } from './layout-runner'
import { createNodeActions } from './nodes'
import { createPageActions } from './pages'
import { createSelectionActions } from './selection'
@@ -287,7 +286,6 @@ export function createEditor(options?: EditorOptions) {
function releaseGraphResources() {
releaseFigPopulationWorker(_graph)
releaseOriginalFigArchive(_graph)
- clearLazyFigImportContext(_graph)
}
return {
diff --git a/packages/core/src/editor/graph-events.ts b/packages/core/src/editor/graph-events.ts
index f34fdecbb..ccad4f94e 100644
--- a/packages/core/src/editor/graph-events.ts
+++ b/packages/core/src/editor/graph-events.ts
@@ -1,4 +1,9 @@
-import type { SceneGraph, SceneGraphEvents, SceneNode } from '@open-pencil/scene-graph'
+import {
+ TRANSFORM_FIELDS,
+ type SceneGraph,
+ type SceneGraphEvents,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import type { SkiaRenderer } from '#core/canvas/renderer'
@@ -36,14 +41,7 @@ const TILED_CHUNK_TOPOLOGY_KEYS = new Set<keyof SceneNode>([
'maskType'
])
-const NODE_PICTURE_STABLE_PREVIEW_KEYS = new Set<keyof SceneNode>([
- 'x',
- 'y',
- 'rotation',
- 'flipX',
- 'flipY',
- 'parentId'
-])
+const NODE_PICTURE_STABLE_PREVIEW_KEYS = new Set<keyof SceneNode>([...TRANSFORM_FIELDS, 'parentId'])
export type RendererInvalidation = {
geometryCache: boolean
diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts
index cc19d2860..56e060923 100644
--- a/packages/core/src/editor/nodes.ts
+++ b/packages/core/src/editor/nodes.ts
@@ -1,6 +1,14 @@
import { pick } from 'es-toolkit/object'
-import { styleDetachmentChanges, type SceneNode } from '@open-pencil/scene-graph'
+import {
+ styleDetachmentChanges,
+ findInstanceAncestor,
+ cloneInstanceOverrideState,
+ recordInstanceOverride,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import { reconcileVariableLayouts } from '#core/layout/variables'
import { createLayoutModeActions } from './layout-mode'
import { createNodePreviewActions } from './node-preview'
@@ -24,6 +32,11 @@ export function createNodeActions(ctx: EditorContext) {
const nudgeActions = createNudgeActions(ctx)
const variableBindingActions = createVariableBindingActions(ctx)
+ function runChangedLayout(id: string, changes: Partial<SceneNode>) {
+ if (changes.variableModes) reconcileVariableLayouts(ctx.graph)
+ ctx.runLayoutForNode(id)
+ }
+
function updateNode(id: string, changes: Partial<SceneNode>) {
const node = ctx.graph.getNode(id)
if (!node) return
@@ -35,7 +48,8 @@ export function createNodeActions(ctx: EditorContext) {
...pathTextEditChanges(node, changes)
})
ctx.graph.updateNode(id, nextChanges)
- ctx.runLayoutForNode(id)
+ recordInstanceOverride(ctx.graph, id, Object.keys(nextChanges))
+ runChangedLayout(id, nextChanges)
}
function updateNodeWithUndo(id: string, changes: Partial<SceneNode>, label = 'Update') {
@@ -47,21 +61,31 @@ export function createNodeActions(ctx: EditorContext) {
...textAutoResizeChanges(node, changes),
...pathTextEditChanges(node, changes)
})
+ const owner = findInstanceAncestor(ctx.graph, id)
+ const previousOverrides = owner
+ ? cloneInstanceOverrideState(owner.instanceOverrides)
+ : undefined
const previous = pick(
node,
Object.keys(nextChanges) as (keyof SceneNode)[]
) as Partial<SceneNode>
ctx.graph.updateNode(id, nextChanges)
- ctx.runLayoutForNode(id)
+ recordInstanceOverride(ctx.graph, id, Object.keys(nextChanges))
+ runChangedLayout(id, nextChanges)
ctx.undo.push({
label,
forward: () => {
ctx.graph.updateNode(id, nextChanges)
- ctx.runLayoutForNode(id)
+ recordInstanceOverride(ctx.graph, id, Object.keys(nextChanges))
+ runChangedLayout(id, nextChanges)
},
inverse: () => {
ctx.graph.updateNode(id, previous)
- ctx.runLayoutForNode(id)
+ if (owner && previousOverrides)
+ ctx.graph.updateNode(owner.id, {
+ instanceOverrides: cloneInstanceOverrideState(previousOverrides)
+ })
+ runChangedLayout(id, nextChanges)
}
})
ctx.requestRender()
diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.ts
index c7a69aa6d..010808e8c 100644
--- a/packages/core/src/editor/pages.ts
+++ b/packages/core/src/editor/pages.ts
@@ -2,11 +2,11 @@ import { limitAsync } from 'es-toolkit/promise'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { populateLazyFigImportRoots } from '#core/kiwi/fig/lazy-import'
import {
canUseFigPopulationWorker,
createFigPopulationWorker
} from '#core/kiwi/fig/population/client'
+import { isReaderPagePending, recoverReaderPage } from '#core/kiwi/fig/session/document-state'
import { computeAllLayouts } from '#core/layout'
import { fontManager } from '#core/text/fonts'
import { collectGraphFontRequirements } from '#core/text/requirements'
@@ -71,7 +71,10 @@ export function createPageActions(ctx: EditorContext) {
if (workerResult !== null) return workerResult
worker?.terminate()
populationWorkerInstance = undefined
- return populateLazyFigImportRoots(ctx.graph, [pageId])
+ if (isReaderPagePending(ctx.graph, pageId)) {
+ return recoverReaderPage(ctx.graph, pageId)
+ }
+ return false
}
async function resolvePageFonts(
diff --git a/packages/core/src/editor/structure/state.ts b/packages/core/src/editor/structure/state.ts
index e62ceda4f..13a14f637 100644
--- a/packages/core/src/editor/structure/state.ts
+++ b/packages/core/src/editor/structure/state.ts
@@ -1,3 +1,5 @@
+import { findInstanceAncestor, setInstanceOverride } from '@open-pencil/scene-graph'
+
import { assertNodeEditable } from '#core/editor/capabilities'
import type { EditorContext } from '#core/editor/types'
@@ -6,6 +8,8 @@ export function createStructureStateActions(ctx: EditorContext) {
assertNodeEditable(ctx.graph, id)
const node = ctx.graph.getNode(id)
if (!node) return
+ const owner = findInstanceAncestor(ctx.graph, id)
+ if (owner) setInstanceOverride(owner.instanceOverrides, owner.id, id, 'visible', true)
ctx.graph.updateNode(id, { visible: !node.visible })
if (node.parentId) ctx.runLayoutForNode(node.parentId)
}
diff --git a/packages/core/src/editor/text/auto-resize.ts b/packages/core/src/editor/text/auto-resize.ts
index dbbeeceb1..01ae7cb86 100644
--- a/packages/core/src/editor/text/auto-resize.ts
+++ b/packages/core/src/editor/text/auto-resize.ts
@@ -1,35 +1,16 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
+import { TEXT_METRIC_FIELDS, type SceneNode } from '@open-pencil/scene-graph'
import { estimateTextSize, getTextMeasurer } from '#core/layout/text-measurement'
export const TEXT_AUTO_RESIZE_KEYS = new Set<keyof SceneNode>([
- 'text',
- 'fontSize',
- 'fontFamily',
- 'fontWeight',
- 'italic',
+ ...TEXT_METRIC_FIELDS,
'lineHeight',
- 'letterSpacing',
- 'styleRuns',
- 'fontVariations',
- 'fontFeatures',
'textAutoResize',
'width',
'maxLines'
])
-const TEXT_AUTO_WIDTH_KEYS = new Set<keyof SceneNode>([
- 'text',
- 'fontSize',
- 'fontFamily',
- 'fontWeight',
- 'italic',
- 'letterSpacing',
- 'styleRuns',
- 'fontVariations',
- 'fontFeatures',
- 'textAutoResize'
-])
+const TEXT_AUTO_WIDTH_KEYS = new Set<keyof SceneNode>([...TEXT_METRIC_FIELDS, 'textAutoResize'])
export function hasTextAutoResizeChange(changes: Partial<SceneNode>): boolean {
return Object.keys(changes).some((key) => TEXT_AUTO_RESIZE_KEYS.has(key as keyof SceneNode))
diff --git a/packages/core/src/editor/variable-bindings.ts b/packages/core/src/editor/variable-bindings.ts
index 3498d27e8..25c521c43 100644
--- a/packages/core/src/editor/variable-bindings.ts
+++ b/packages/core/src/editor/variable-bindings.ts
@@ -1,61 +1,76 @@
+import {
+ cloneInstanceOverrideState,
+ findInstanceAncestor,
+ variableBindingOwner,
+ isNumericVariableBindingField,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import { reconcileVariableLayouts } from '#core/layout/variables'
+
import type { EditorContext } from './types'
export function createVariableBindingActions(ctx: EditorContext) {
- function bindVariable(nodeId: string, path: string, variableId: string) {
- const node = ctx.graph.getNode(nodeId)
- if (!node) return
- const prevVarId = node.boundVariables[path]
- ctx.graph.bindVariable(nodeId, path, variableId)
- ctx.undo.push({
- label: 'Bind variable',
- forward: () => {
- try {
- ctx.graph.bindVariable(nodeId, path, variableId)
- ctx.requestRender()
- } catch (e) {
- console.warn('Redo bindVariable failed:', e instanceof Error ? e.message : String(e))
- }
- },
- inverse: () => {
- try {
- if (prevVarId) ctx.graph.bindVariable(nodeId, path, prevVarId)
- else ctx.graph.unbindVariable(nodeId, path)
- ctx.requestRender()
- } catch (e) {
- console.warn('Undo bindVariable failed:', e instanceof Error ? e.message : String(e))
- }
- }
- })
+ function refreshBindings() {
+ reconcileVariableLayouts(ctx.graph)
ctx.requestRender()
}
- function unbindVariable(nodeId: string, path: string) {
+ function changeBinding(nodeId: string, path: string, variableId?: string) {
const node = ctx.graph.getNode(nodeId)
- if (!node) return
- const prevVarId = node.boundVariables[path]
- if (!prevVarId) return
- ctx.graph.unbindVariable(nodeId, path)
+ if (!node || (variableId === undefined && !(path in node.boundVariables))) return
+ const previous = {
+ boundVariables: { ...node.boundVariables },
+ variableBindingScales: { ...node.variableBindingScales },
+ ...(isNumericVariableBindingField(path) ? { [path]: node[path as keyof SceneNode] } : {})
+ }
+ const owner = variableBindingOwner(ctx.graph, node)
+ const nearest = findInstanceAncestor(ctx.graph, nodeId)
+ const owners = new Map(
+ [owner, ...(nearest ? [nearest] : [])].map(
+ (item) => [item.id, cloneInstanceOverrideState(item.instanceOverrides)] as const
+ )
+ )
+ const apply = () => {
+ if (variableId === undefined) ctx.graph.unbindVariable(nodeId, path)
+ else ctx.graph.bindVariable(nodeId, path, variableId)
+ refreshBindings()
+ }
+ apply()
ctx.undo.push({
- label: 'Unbind variable',
+ label: variableId === undefined ? 'Unbind variable' : 'Bind variable',
forward: () => {
try {
- ctx.graph.unbindVariable(nodeId, path)
- ctx.requestRender()
- } catch (e) {
- console.warn('Redo unbindVariable failed:', e instanceof Error ? e.message : String(e))
+ apply()
+ } catch (error) {
+ console.warn(
+ 'Redo variable binding failed:',
+ error instanceof Error ? error.message : String(error)
+ )
}
},
inverse: () => {
- try {
- ctx.graph.bindVariable(nodeId, path, prevVarId)
- ctx.requestRender()
- } catch (e) {
- console.warn('Undo unbindVariable failed:', e instanceof Error ? e.message : String(e))
+ for (const [id, state] of owners) {
+ ctx.graph.updateNode(id, { instanceOverrides: cloneInstanceOverrideState(state) })
}
+ const restored = structuredClone(previous)
+ restored.boundVariables = Object.fromEntries(
+ Object.entries(restored.boundVariables).filter(([, id]) => ctx.graph.variables.has(id))
+ )
+ restored.variableBindingScales = Object.fromEntries(
+ Object.entries(restored.variableBindingScales).filter(
+ ([field]) => field in restored.boundVariables
+ )
+ )
+ ctx.graph.updateNode(nodeId, restored)
+ refreshBindings()
}
})
- ctx.requestRender()
}
- return { bindVariable, unbindVariable }
+ return {
+ bindVariable: (nodeId: string, path: string, variableId: string) =>
+ changeBinding(nodeId, path, variableId),
+ unbindVariable: (nodeId: string, path: string) => changeBinding(nodeId, path)
+ }
}
diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.ts
index 33e63331c..1e1060eb7 100644
--- a/packages/core/src/editor/variables.ts
+++ b/packages/core/src/editor/variables.ts
@@ -5,11 +5,16 @@ import type {
VariableValue
} from '@open-pencil/scene-graph'
+import { reconcileVariableLayouts } from '#core/layout/variables'
import { randomHex } from '#core/random'
import type { EditorContext } from './types'
export function createVariableActions(ctx: EditorContext) {
+ function refreshVariables() {
+ reconcileVariableLayouts(ctx.graph)
+ ctx.requestRender()
+ }
function getVariablesByType(type: VariableType) {
return ctx.graph.getVariablesByType(type)
}
@@ -73,14 +78,14 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Add collection',
forward: () => {
ctx.graph.addCollection(collection)
- ctx.requestRender()
+ refreshVariables()
},
inverse: () => {
ctx.graph.removeCollection(collection.id)
- ctx.requestRender()
+ refreshVariables()
}
})
- ctx.requestRender()
+ refreshVariables()
}
function removeCollection(id: string) {
@@ -96,15 +101,15 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Remove collection',
forward: () => {
ctx.graph.removeCollection(id)
- ctx.requestRender()
+ refreshVariables()
},
inverse: () => {
ctx.graph.addCollection(snapshot)
for (const v of variables) ctx.graph.addVariable(v)
- ctx.requestRender()
+ refreshVariables()
}
})
- ctx.requestRender()
+ refreshVariables()
}
function addVariable(variable: Variable) {
@@ -113,14 +118,14 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Add variable',
forward: () => {
ctx.graph.addVariable(variable)
- ctx.requestRender()
+ refreshVariables()
},
inverse: () => {
ctx.graph.removeVariable(variable.id)
- ctx.requestRender()
+ refreshVariables()
}
})
- ctx.requestRender()
+ refreshVariables()
}
function removeVariable(id: string) {
@@ -132,14 +137,14 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Remove variable',
forward: () => {
ctx.graph.removeVariable(id)
- ctx.requestRender()
+ refreshVariables()
},
inverse: () => {
ctx.graph.addVariable(snapshot)
- ctx.requestRender()
+ refreshVariables()
}
})
- ctx.requestRender()
+ refreshVariables()
}
function renameVariable(id: string, newName: string) {
@@ -173,14 +178,14 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Add mode',
forward: () => {
ctx.graph.addMode(collectionId, modeId, modeName)
- ctx.requestRender()
+ refreshVariables()
},
inverse: () => {
ctx.graph.removeMode(collectionId, modeId)
- ctx.requestRender()
+ refreshVariables()
}
})
- ctx.requestRender()
+ refreshVariables()
return modeId
}
@@ -202,7 +207,7 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Remove mode',
forward: () => {
ctx.graph.removeMode(collectionId, modeId)
- ctx.requestRender()
+ refreshVariables()
},
inverse: () => {
ctx.graph.addMode(collectionId, modeId, modeName)
@@ -216,10 +221,10 @@ export function createVariableActions(ctx: EditorContext) {
if (v) v.valuesByMode[modeId] = structuredClone(value)
}
if (wasDefault) ctx.graph.setDefaultMode(collectionId, modeId)
- ctx.requestRender()
+ refreshVariables()
}
})
- ctx.requestRender()
+ refreshVariables()
}
function renameMode(collectionId: string, modeId: string, newName: string) {
@@ -252,14 +257,14 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Set default mode',
forward: () => {
ctx.graph.setDefaultMode(collectionId, modeId)
- ctx.requestRender()
+ refreshVariables()
},
inverse: () => {
ctx.graph.setDefaultMode(collectionId, prevDefault)
- ctx.requestRender()
+ refreshVariables()
}
})
- ctx.requestRender()
+ refreshVariables()
}
function duplicateMode(collectionId: string, sourceModeId: string): string | undefined {
@@ -274,20 +279,20 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Duplicate mode',
forward: () => {
ctx.graph.addMode(collectionId, modeId, modeName, sourceModeId)
- ctx.requestRender()
+ refreshVariables()
},
inverse: () => {
ctx.graph.removeMode(collectionId, modeId)
- ctx.requestRender()
+ refreshVariables()
}
})
- ctx.requestRender()
+ refreshVariables()
return modeId
}
function setActiveMode(collectionId: string, modeId: string) {
ctx.graph.setActiveMode(collectionId, modeId)
- ctx.requestRender()
+ refreshVariables()
}
function updateVariableValue(id: string, modeId: string, value: VariableValue) {
@@ -301,15 +306,15 @@ export function createVariableActions(ctx: EditorContext) {
forward: () => {
const v = ctx.graph.variables.get(id)
if (v) v.valuesByMode[modeId] = structuredClone(newValue)
- ctx.requestRender()
+ refreshVariables()
},
inverse: () => {
const v = ctx.graph.variables.get(id)
if (v) v.valuesByMode[modeId] = structuredClone(prevValue)
- ctx.requestRender()
+ refreshVariables()
}
})
- ctx.requestRender()
+ refreshVariables()
}
return {
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index 9f32a207c..76bb82cc3 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -1,4 +1,11 @@
-import { getNodeLocalMatrix, getWorldMatrix, type SceneNode } from '@open-pencil/scene-graph'
+import {
+ getNodeLocalMatrix,
+ getWorldMatrix,
+ TRANSFORM_FIELDS as NODE_TRANSFORM_FIELDS,
+ findInstanceAncestor,
+ rescaleNodeTree,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import type { Rect } from '@open-pencil/scene-graph/primitives'
import { assertNodeEditable } from '#core/editor/capabilities'
@@ -6,15 +13,15 @@ import {
graph,
nodeId,
raw,
+ updateNode,
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
import type { NodeProxyHost } from '#core/figma-api/proxy'
import { computeAbsoluteRenderBounds } from '#core/figma-api/render-bounds'
-import { rescaleNodeTree } from '#core/figma-api/rescale'
import type { FigmaTransform } from '#core/figma-api/types'
-const TRANSFORM_FIELDS = new Set(['x', 'y', 'rotation', 'flipX', 'flipY'])
+const TRANSFORM_FIELDS: ReadonlySet<string> = new Set(NODE_TRANSFORM_FIELDS)
function assertEditable(target: ProxyThis, internals: NodeProxyInternals): void {
assertNodeEditable(graph(target, internals), nodeId(target, internals))
@@ -61,8 +68,7 @@ export function installBasicNodeProxyAccessors(
return raw(this, internals).name
},
set(this: ProxyThis, value: string) {
- assertEditable(this, internals)
- graph(this, internals).updateNode(nodeId(this, internals), { name: value })
+ updateNode(this, internals, { name: value })
}
},
removed: {
@@ -148,15 +154,18 @@ export function installBasicNodeProxyAccessors(
Object.assign(prototype, {
resize(this: ProxyThis, width: number, height: number): void {
- assertEditable(this, internals)
- graph(this, internals).updateNode(nodeId(this, internals), { width, height })
+ updateNode(this, internals, { width, height })
},
resizeWithoutConstraints(this: ProxyThis, width: number, height: number): void {
;(this as { resize(width: number, height: number): void }).resize(width, height)
},
rescale(this: ProxyThis, scale: number): void {
assertEditable(this, internals)
- rescaleNodeTree(graph(this, internals), nodeId(this, internals), scale)
+ const scene = graph(this, internals)
+ const node = raw(this, internals)
+ if (node.parentId && findInstanceAncestor(scene, node.parentId))
+ throw new Error('This property cannot be overridden in an instance: size')
+ rescaleNodeTree(scene, node.id, scale)
}
})
}
diff --git a/packages/core/src/figma-api/accessors/text.ts b/packages/core/src/figma-api/accessors/text.ts
index db6f7fafc..391f35f74 100644
--- a/packages/core/src/figma-api/accessors/text.ts
+++ b/packages/core/src/figma-api/accessors/text.ts
@@ -48,6 +48,14 @@ export function installTextNodeProxyAccessors(
}
},
fontSize: field(internals, 'fontSize'),
+ textStyleId: {
+ get(this: ProxyThis): string {
+ return raw(this, internals).textStyleId ?? ''
+ },
+ set(this: ProxyThis, value: string) {
+ updateNode(this, internals, { textStyleId: value || null })
+ }
+ },
fontWeight: field(internals, 'fontWeight'),
textAlignHorizontal: field(internals, 'textAlignHorizontal'),
textAlignVertical: field(internals, 'textAlignVertical'),
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index 191edf545..eca0e86e7 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -10,6 +10,20 @@ import {
} from '#core/figma-api/accessor-utils'
import { parseFigmaEffects, toFigmaEffect, type FigmaEffect } from '#core/figma-api/effects'
+function styleReference(
+ internals: NodeProxyInternals,
+ field: 'fillStyleId' | 'strokeStyleId' | 'effectStyleId' | 'gridStyleId'
+): PropertyDescriptor {
+ return {
+ get(this: ProxyThis): string {
+ return raw(this, internals)[field] ?? ''
+ },
+ set(this: ProxyThis, value: string) {
+ updateNode(this, internals, { [field]: value || null })
+ }
+ }
+}
+
export function installVisualNodeProxyAccessors(
prototype: object,
internals: NodeProxyInternals,
@@ -51,6 +65,11 @@ export function installVisualNodeProxyAccessors(
updateNode(this, internals, { effects: parseFigmaEffects(value) })
}
},
+ // Applied shared styles, as Figma exposes them; an assignment inside an instance is an override.
+ fillStyleId: styleReference(internals, 'fillStyleId'),
+ strokeStyleId: styleReference(internals, 'strokeStyleId'),
+ effectStyleId: styleReference(internals, 'effectStyleId'),
+ gridStyleId: styleReference(internals, 'gridStyleId'),
opacity: {
get(this: ProxyThis): number {
return raw(this, internals).opacity
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 8f17a5327..dc62b835d 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -20,6 +20,7 @@ import { canMakeBooleanSourceNode } from '#core/canvas/boolean'
import { flattenNodesToVectorProps } from '#core/canvas/flatten'
import { IS_BROWSER } from '#core/constants'
import type { RasterExportFormat } from '#core/io/formats/raster'
+import { reconcileVariableLayouts } from '#core/layout/variables'
import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/status'
import { combineComponentsAsVariants, exposeInstanceSwap } from './components'
@@ -357,7 +358,8 @@ export class FigmaAPI implements NodeProxyHost {
setVariableValue(variableId: string, modeId: string, value: VariableValue): void {
const variable = this.graph.variables.get(variableId)
if (!variable) throw new Error(`Variable "${variableId}" not found`)
- variable.valuesByMode[modeId] = value
+ variable.valuesByMode[modeId] = structuredClone(value)
+ reconcileVariableLayouts(this.graph)
}
deleteVariable(id: string): void {
@@ -374,10 +376,12 @@ export class FigmaAPI implements NodeProxyHost {
bindVariable(nodeId: string, field: string, variableId: string): void {
this.graph.bindVariable(nodeId, field, variableId)
+ reconcileVariableLayouts(this.graph)
}
unbindVariable(nodeId: string, field: string): void {
this.graph.unbindVariable(nodeId, field)
+ reconcileVariableLayouts(this.graph)
}
// --- Boolean Operations ---
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index df0cf9205..bee8ed2c5 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -324,7 +324,6 @@ export { readPenFile, parsePenFile } from '@open-pencil/pen'
export {
readFigFile,
parseFigFile,
- importNodeChanges,
initCodec,
encodeMessage,
decodeMessage,
diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.ts
index 47f2f0905..82ff35850 100644
--- a/packages/core/src/io/formats/fig/export.ts
+++ b/packages/core/src/io/formats/fig/export.ts
@@ -13,7 +13,7 @@ import {
import { initCodec, getCompiledSchema, getSchemaBytes } from '@open-pencil/kiwi/fig/codec'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi/schema-runtime'
-import type { SceneGraph, VariableValue } from '@open-pencil/scene-graph'
+import type { SceneGraph } from '@open-pencil/scene-graph'
import type { GUID } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas'
@@ -21,18 +21,24 @@ import { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '#core/constants'
import { applyEnabledLibrariesPluginData } from '#core/io/formats/fig/library-metadata'
import { findFigThumbnailPageId } from '#core/io/formats/fig/thumbnail-page'
import { renderThumbnail } from '#core/io/formats/raster'
-import { populateAllLazyFigImportRoots } from '#core/kiwi/fig/lazy-import'
import {
sceneNodeToKiwi,
fractionalPosition,
buildFontDigestMap,
- safeColor,
makeDocumentNodeChange,
makeCanvasNodeChange
} from '#core/kiwi/fig/node-change/serialize'
import { cloneSceneGraphForFigExport } from '#core/kiwi/fig/parse/transfer'
+import { populateReaderExport } from '#core/kiwi/fig/session/document-state'
import { originalFigArchive } from '#core/kiwi/fig/session/original-archive'
+import {
+ appendVariableNodeChanges,
+ assignSharedStyleGuids,
+ assignVariableGuid,
+ assignVariableGuids
+} from './variable-export'
+
const THUMBNAIL_1X1 = toUint8Array(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='
)
@@ -46,39 +52,6 @@ interface CanvasExportEntry {
canvasNc: KiwiNodeChange
}
-function variableValueToKiwi(
- value: VariableValue,
- type: string,
- varIdToGuid: Map<string, GUID>
-): { value: Record<string, unknown>; dataType: string; resolvedDataType: string } {
- if (value && typeof value === 'object' && 'aliasId' in value) {
- const aliasGuid = varIdToGuid.get(value.aliasId) ?? stringToGuid(value.aliasId)
- return {
- value: { alias: { guid: aliasGuid } },
- dataType: 'ALIAS',
- resolvedDataType: { COLOR: 'COLOR', BOOLEAN: 'BOOLEAN', STRING: 'STRING' }[type] ?? 'FLOAT'
- }
- }
- if (type === 'COLOR' && typeof value === 'object' && 'r' in value) {
- return {
- value: { colorValue: safeColor(value) },
- dataType: 'COLOR',
- resolvedDataType: 'COLOR'
- }
- }
- if (type === 'BOOLEAN') {
- return { value: { boolValue: !!value }, dataType: 'BOOLEAN', resolvedDataType: 'BOOLEAN' }
- }
- if (type === 'STRING') {
- return {
- value: { textValue: typeof value === 'string' ? value : JSON.stringify(value) },
- dataType: 'STRING',
- resolvedDataType: 'STRING'
- }
- }
- return { value: { floatValue: Number(value) }, dataType: 'FLOAT', resolvedDataType: 'FLOAT' }
-}
-
function collectImageEntries(graph: SceneGraph): Array<{ name: string; data: Uint8Array }> {
const entries: Array<{ name: string; data: Uint8Array }> = []
for (const [hash, data] of graph.images) {
@@ -112,59 +85,6 @@ async function renderFigThumbnail(
)
}
-function assignVariableGuid(
- id: string,
- localIdCounter: { value: number },
- assignedGuidValues: Set<string>,
- nodeSourceGuidValues: Set<string>
-): GUID {
- if (/^\d+:\d+$/.test(id) && !assignedGuidValues.has(id) && !nodeSourceGuidValues.has(id)) {
- const guid = stringToGuid(id)
- assignedGuidValues.add(id)
- return guid
- }
- const guid = { sessionID: 0, localID: localIdCounter.value++ }
- assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)
- return guid
-}
-
-function assignVariableGuids(
- graph: SceneGraph,
- localIdCounter: { value: number },
- varIdToGuid: Map<string, GUID>,
- modeIdToGuid: Map<string, GUID>,
- assignedGuidValues: Set<string>,
- nodeSourceGuidValues: Set<string>
-): void {
- for (const [colId, col] of graph.variableCollections) {
- const colGuid = assignVariableGuid(
- colId,
- localIdCounter,
- assignedGuidValues,
- nodeSourceGuidValues
- )
- varIdToGuid.set(colId, colGuid)
- for (const mode of col.modes) {
- const modeGuid = assignVariableGuid(
- mode.modeId,
- localIdCounter,
- assignedGuidValues,
- nodeSourceGuidValues
- )
- modeIdToGuid.set(mode.modeId, modeGuid)
- }
- for (const varId of col.variableIds) {
- const varGuid = assignVariableGuid(
- varId,
- localIdCounter,
- assignedGuidValues,
- nodeSourceGuidValues
- )
- varIdToGuid.set(varId, varGuid)
- }
- }
-}
-
interface ComponentPropertyGuidState {
ids: string[]
maxLocalId0: number
@@ -210,90 +130,6 @@ function assignComponentPropertyGuids(
}
}
-function appendVariableNodeChanges(
- graph: SceneGraph,
- nodeChanges: KiwiNodeChange[],
- internalCanvasGuid: GUID,
- varIdToGuid: Map<string, GUID>,
- modeIdToGuid: Map<string, GUID>
-): void {
- let collIdx = 0
- for (const [colId, col] of graph.variableCollections) {
- const colGuid = varIdToGuid.get(colId) ?? stringToGuid(colId)
- nodeChanges.push({
- guid: colGuid,
- parentIndex: { guid: internalCanvasGuid, position: fractionalPosition(collIdx++) },
- type: 'VARIABLE_SET',
- name: col.name,
- phase: 'CREATED',
- strokeAlign: 'CENTER',
- strokeJoin: 'BEVEL',
- variableSetModes: col.modes.map((m, i) => {
- const mGuid = modeIdToGuid.get(m.modeId) ?? stringToGuid(m.modeId)
- return { id: mGuid, name: m.name, sortPosition: fractionalPosition(i) }
- })
- })
-
- appendVariablesForCollection(
- graph,
- nodeChanges,
- colGuid,
- internalCanvasGuid,
- col.variableIds,
- varIdToGuid,
- modeIdToGuid
- )
- }
-}
-
-function appendVariablesForCollection(
- graph: SceneGraph,
- nodeChanges: KiwiNodeChange[],
- colGuid: GUID,
- parentGuid: GUID,
- variableIds: string[],
- varIdToGuid: Map<string, GUID>,
- modeIdToGuid: Map<string, GUID>
-): void {
- let varIdx = 0
- for (const varId of variableIds) {
- const variable = graph.variables.get(varId)
- if (!variable) continue
-
- const varGuid = varIdToGuid.get(varId) ?? stringToGuid(varId)
- const typeMap: Record<string, string> = {
- COLOR: 'COLOR',
- BOOLEAN: 'BOOLEAN',
- STRING: 'STRING'
- }
- const resolvedType = typeMap[variable.type] ?? 'FLOAT'
-
- const entries = Object.entries(variable.valuesByMode).map(([modeId, value]) => ({
- modeID: modeIdToGuid.get(modeId) ?? stringToGuid(modeId),
- variableData: variableValueToKiwi(value, variable.type, varIdToGuid)
- }))
-
- const nc: KiwiNodeChange = {
- guid: varGuid,
- parentIndex: { guid: parentGuid, position: fractionalPosition(varIdx++) },
- type: 'VARIABLE',
- name: variable.name,
- phase: 'CREATED',
- strokeAlign: 'CENTER',
- strokeJoin: 'BEVEL',
- variableSetID: { guid: colGuid },
- variableResolvedType: resolvedType,
- variableDataValues: { entries },
- variableScopes: ['ALL_SCOPES']
- }
- // Preserve library key/version on VARIABLE NodeChanges so that
- // buildAssetRefMap can resolve assetRef to guid on reimport.
- if (variable.key) nc.key = variable.key
- if (variable.version) nc.version = variable.version
- nodeChanges.push(nc)
- }
-}
-
function applyImportedCanvasFields(page: FigExportPage, canvasNc: KiwiNodeChange): void {
if (!page.source.id) return
if (!('pageType' in page.source.fig.rawNodeFields)) delete canvasNc.pageType
@@ -407,6 +243,12 @@ function appendInternalResources(context: InternalResourceContext): void {
const { graph, internalCanvasGuid, nodeChanges } = context
if (!internalCanvasGuid) return
const sharedStyleNodes = [...graph.nodes.values()].filter((node) => node.sharedStyleType !== null)
+ assignSharedStyleGuids(
+ sharedStyleNodes,
+ context.localIdCounter,
+ context.nodeIdToGuid,
+ context.assignedGuidValues
+ )
for (let index = 0; index < sharedStyleNodes.length; index++) {
nodeChanges.push(
...sceneNodeToKiwi(
@@ -416,15 +258,17 @@ function appendInternalResources(context: InternalResourceContext): void {
context.localIdCounter,
graph,
context.blobs,
- context.nodeIdToGuid,
- context.fontDigestMap,
- context.varIdToGuid,
- context.glyphBlobMap,
- context.blobIndexByHex,
- context.assignedGuidValues,
- context.componentPropertyDefinitionsById,
- context.modeIdToGuid,
- context.propertyIdToGuid
+ {
+ nodeIdToGuid: context.nodeIdToGuid,
+ fontDigestMap: context.fontDigestMap,
+ varIdToGuid: context.varIdToGuid,
+ glyphBlobMap: context.glyphBlobMap,
+ blobIndexByHex: context.blobIndexByHex,
+ assignedGuidValues: context.assignedGuidValues,
+ componentPropertyDefinitionsById: context.componentPropertyDefinitionsById,
+ modeIdToGuid: context.modeIdToGuid,
+ propertyIdToGuid: context.propertyIdToGuid
+ }
)
)
}
@@ -449,7 +293,7 @@ export async function exportFigFile(
const originalArchive = await originalFigArchive(sourceGraph)
if (originalArchive) return originalArchive.slice()
const graph = cloneSceneGraphForFigExport(sourceGraph)
- populateAllLazyFigImportRoots(graph)
+ populateReaderExport(sourceGraph, graph)
await initCodec()
// When the document was imported from a .fig file, preserve the original
@@ -548,21 +392,34 @@ export async function exportFigFile(
for (const entry of canvasEntries) nodeChanges.push(entry.canvasNc)
+ appendInternalResources({
+ graph,
+ nodeChanges,
+ internalCanvasGuid,
+ localIdCounter,
+ blobs,
+ nodeIdToGuid,
+ fontDigestMap,
+ varIdToGuid,
+ modeIdToGuid,
+ glyphBlobMap,
+ blobIndexByHex,
+ assignedGuidValues,
+ componentPropertyDefinitionsById,
+ propertyIdToGuid
+ })
+
const orderedCanvasEntries = [
...canvasEntries.filter((entry) => entry.page.internalOnly),
...canvasEntries.filter((entry) => !entry.page.internalOnly)
]
for (const { page, canvasGuid } of orderedCanvasEntries) {
- const children = graph.getChildren(page.id).filter((child) => !child.internalOnly)
+ const children = graph
+ .getChildren(page.id)
+ .filter((child) => !child.internalOnly && child.sharedStyleType === null)
for (let i = 0; i < children.length; i++) {
nodeChanges.push(
- ...sceneNodeToKiwi(
- children[i],
- canvasGuid,
- i,
- localIdCounter,
- graph,
- blobs,
+ ...sceneNodeToKiwi(children[i], canvasGuid, i, localIdCounter, graph, blobs, {
nodeIdToGuid,
fontDigestMap,
varIdToGuid,
@@ -572,28 +429,11 @@ export async function exportFigFile(
componentPropertyDefinitionsById,
modeIdToGuid,
propertyIdToGuid
- )
+ })
)
}
}
- appendInternalResources({
- graph,
- nodeChanges,
- internalCanvasGuid,
- localIdCounter,
- blobs,
- nodeIdToGuid,
- fontDigestMap,
- varIdToGuid,
- modeIdToGuid,
- glyphBlobMap,
- blobIndexByHex,
- assignedGuidValues,
- componentPropertyDefinitionsById,
- propertyIdToGuid
- })
-
const msg: Record<string, unknown> = {
type: 'NODE_CHANGES',
sessionID: 0,
diff --git a/packages/core/src/io/formats/fig/index.ts b/packages/core/src/io/formats/fig/index.ts
index 1cc42e1ff..f7a44f674 100644
--- a/packages/core/src/io/formats/fig/index.ts
+++ b/packages/core/src/io/formats/fig/index.ts
@@ -1,3 +1,8 @@
export { readFigFile, parseFigFile, type ParseFigFileOptions } from './read'
export { exportFigFile, compressFigData, compressFigDataSync } from './write'
export { findFigThumbnailPageId } from './thumbnail-page'
+export {
+ populateFigPage,
+ populateAllFigPages,
+ readerDiagnostics
+} from '#core/kiwi/fig/session/document-state'
diff --git a/packages/core/src/io/formats/fig/read.ts b/packages/core/src/io/formats/fig/read.ts
index 3c7cde067..55dd3a221 100644
--- a/packages/core/src/io/formats/fig/read.ts
+++ b/packages/core/src/io/formats/fig/read.ts
@@ -1,16 +1,19 @@
-import { parseFigBuffer } from '@open-pencil/fig'
import type { FigPageManifestEntry } from '@open-pencil/kiwi/fig'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { IS_BROWSER } from '#core/constants'
-import { importNodeChanges } from '#core/kiwi/fig/import'
import { deserializeSceneGraph } from '#core/kiwi/fig/parse/transfer'
import {
registerFigPopulationWorker,
registerOriginalArchiveRequest
} from '#core/kiwi/fig/population/client'
import { createFigSessionWorker } from '#core/kiwi/fig/session/client'
+import {
+ registerReaderRecovery,
+ registerReaderSession
+} from '#core/kiwi/fig/session/document-state'
import type { FigSessionOpenRequest, FigSessionResponse } from '#core/kiwi/fig/session/protocol'
+import { openReaderSession } from '#core/kiwi/fig/session/reader'
import { randomHex } from '#core/random'
export interface ParseFigFileOptions {
@@ -19,18 +22,19 @@ export interface ParseFigFileOptions {
signal?: AbortSignal
}
+class ReaderSemanticError extends Error {
+ override name = 'ReaderSemanticError'
+}
+
function parseFigFileSync(buffer: ArrayBuffer, options: ParseFigFileOptions = {}): SceneGraph {
- const {
- nodeChanges,
- blobs,
- images: imageEntries,
- figKiwiVersion,
- figSchemaDeflated
- } = parseFigBuffer(buffer, options.onPages)
- const graph = importNodeChanges(nodeChanges, blobs, new Map(imageEntries), options)
- graph.figKiwiVersion = figKiwiVersion
- graph.figSchemaDeflated = figSchemaDeflated
- return graph
+ options.signal?.throwIfAborted()
+ const reader = openReaderSession(buffer, options.populate)
+ options.onPages?.(reader.pages)
+ options.signal?.throwIfAborted()
+ const bytes = buffer.slice(0)
+ registerReaderSession(bytes, reader.session, reader.diagnostics)
+ registerOriginalArchiveRequest(reader.graph, async () => new Uint8Array(bytes.slice(0)))
+ return reader.graph
}
function parseViaWorker(buffer: ArrayBuffer, options: ParseFigFileOptions): Promise<SceneGraph> {
@@ -65,13 +69,15 @@ function parseViaWorker(buffer: ArrayBuffer, options: ParseFigFileOptions): Prom
cleanupAbort()
channel.port1.close()
worker.terminate()
- reject(new Error(e.data.error ?? 'Worker failed to parse .fig file'))
+ reject(new ReaderSemanticError(e.data.error ?? 'Worker failed to parse .fig file'))
return
}
try {
const graph = deserializeSceneGraph(e.data.graph)
- if (options.populate === 'first-page') {
+ if (options.populate === 'first-page' || options.populate === 'none') {
cleanupAbort()
+ if (!e.data.checkpoint) throw new Error('Missing reader checkpoint')
+ registerReaderRecovery(graph, buffer.slice(0), e.data.checkpoint)
registerFigPopulationWorker(graph, worker, channel.port1)
registerOriginalArchiveRequest(
graph,
@@ -125,11 +131,9 @@ export async function parseFigFile(
try {
return await parseViaWorker(buffer, options)
} catch (error) {
- if (options.signal?.aborted) throw error
+ if (options.signal?.aborted || error instanceof ReaderSemanticError) throw error
console.warn('Worker parsing failed, falling back to main thread:', error)
- const graph = parseFigFileSync(copy, options)
- registerOriginalArchiveRequest(graph, async () => new Uint8Array(copy.slice(0)))
- return graph
+ return parseFigFileSync(copy, options)
}
}
options.signal?.throwIfAborted()
diff --git a/packages/core/src/io/formats/fig/variable-export.ts b/packages/core/src/io/formats/fig/variable-export.ts
new file mode 100644
index 000000000..fb482ef4d
--- /dev/null
+++ b/packages/core/src/io/formats/fig/variable-export.ts
@@ -0,0 +1,157 @@
+import type { GUID, NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'
+import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
+import type { SceneGraph, SceneNode, VariableValue } from '@open-pencil/scene-graph'
+
+import { fractionalPosition, safeColor } from '#core/kiwi/fig/node-change/serialize'
+
+/**
+ * Identity allocation shared by the two writers. The document exporter and the clipboard
+ * both emit variables, modes and shared styles ahead of the nodes that reference them; when
+ * each allocated its own way the two drifted.
+ */
+export function assignVariableGuid(
+ id: string,
+ localIdCounter: { value: number },
+ assignedGuidValues: Set<string>,
+ nodeSourceGuidValues: Set<string>
+): GUID {
+ if (/^\d+:\d+$/.test(id) && !assignedGuidValues.has(id) && !nodeSourceGuidValues.has(id)) {
+ const guid = stringToGuid(id)
+ assignedGuidValues.add(id)
+ return guid
+ }
+ const guid = { sessionID: 0, localID: localIdCounter.value++ }
+ assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)
+ return guid
+}
+
+export function assignVariableGuids(
+ graph: SceneGraph,
+ localIdCounter: { value: number },
+ varIdToGuid: Map<string, GUID>,
+ modeIdToGuid: Map<string, GUID>,
+ assignedGuidValues: Set<string>,
+ nodeSourceGuidValues: Set<string>
+): void {
+ for (const [colId, col] of graph.variableCollections) {
+ const colGuid = assignVariableGuid(
+ colId,
+ localIdCounter,
+ assignedGuidValues,
+ nodeSourceGuidValues
+ )
+ varIdToGuid.set(colId, colGuid)
+ for (const mode of col.modes) {
+ const modeGuid = assignVariableGuid(
+ mode.modeId,
+ localIdCounter,
+ assignedGuidValues,
+ nodeSourceGuidValues
+ )
+ modeIdToGuid.set(mode.modeId, modeGuid)
+ }
+ for (const varId of col.variableIds) {
+ const varGuid = assignVariableGuid(
+ varId,
+ localIdCounter,
+ assignedGuidValues,
+ nodeSourceGuidValues
+ )
+ varIdToGuid.set(varId, varGuid)
+ }
+ }
+}
+
+/** Shared styles live on the internal canvas and need a GUID before any node cites them. */
+export function assignSharedStyleGuids(
+ styles: readonly SceneNode[],
+ localIdCounter: { value: number },
+ nodeIdToGuid: Map<string, GUID>,
+ assignedGuidValues: Set<string>
+): void {
+ for (const style of styles) {
+ if (nodeIdToGuid.has(style.id)) continue
+ let guid: GUID
+ do {
+ guid = { sessionID: 1, localID: localIdCounter.value++ }
+ } while (assignedGuidValues.has(`${guid.sessionID}:${guid.localID}`))
+ nodeIdToGuid.set(style.id, guid)
+ assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)
+ }
+}
+
+function variableValueToKiwi(
+ value: VariableValue,
+ type: string,
+ ids: Map<string, GUID>
+): VariableDataEntry {
+ if (typeof value === 'object' && 'aliasId' in value)
+ return {
+ value: { alias: { guid: ids.get(value.aliasId) ?? stringToGuid(value.aliasId) } },
+ dataType: 'ALIAS',
+ resolvedDataType: type
+ }
+ if (type === 'COLOR' && typeof value === 'object' && 'r' in value)
+ return { value: { colorValue: safeColor(value) }, dataType: type, resolvedDataType: type }
+ if (type === 'BOOLEAN')
+ return { value: { boolValue: !!value }, dataType: type, resolvedDataType: type }
+ if (type === 'STRING')
+ return {
+ value: { textValue: typeof value === 'string' ? value : JSON.stringify(value) },
+ dataType: type,
+ resolvedDataType: type
+ }
+ return { value: { floatValue: Number(value) }, dataType: 'FLOAT', resolvedDataType: 'FLOAT' }
+}
+
+export function appendVariableNodeChanges(
+ graph: SceneGraph,
+ changes: NodeChange[],
+ parent: GUID,
+ ids: Map<string, GUID>,
+ modes: Map<string, GUID>
+): void {
+ let index = 0
+ for (const collection of graph.variableCollections.values()) {
+ const guid = ids.get(collection.id) ?? stringToGuid(collection.id)
+ changes.push({
+ guid,
+ parentIndex: { guid: parent, position: fractionalPosition(index++) },
+ type: 'VARIABLE_SET',
+ name: collection.name,
+ phase: 'CREATED',
+ strokeAlign: 'CENTER',
+ strokeJoin: 'BEVEL',
+ variableSetModes: collection.modes.map((mode, i) => ({
+ id: modes.get(mode.modeId) ?? stringToGuid(mode.modeId),
+ name: mode.name,
+ sortPosition: fractionalPosition(i)
+ }))
+ })
+ let variableIndex = 0
+ for (const id of collection.variableIds) {
+ const variable = graph.variables.get(id)
+ if (!variable) continue
+ changes.push({
+ guid: ids.get(id) ?? stringToGuid(id),
+ parentIndex: { guid: parent, position: fractionalPosition(variableIndex++) },
+ type: 'VARIABLE',
+ name: variable.name,
+ phase: 'CREATED',
+ strokeAlign: 'CENTER',
+ strokeJoin: 'BEVEL',
+ variableSetID: { guid },
+ variableResolvedType: variable.type,
+ variableDataValues: {
+ entries: Object.entries(variable.valuesByMode).map(([mode, value]) => ({
+ modeID: modes.get(mode) ?? stringToGuid(mode),
+ variableData: variableValueToKiwi(value, variable.type, ids)
+ }))
+ },
+ variableScopes: ['ALL_SCOPES'],
+ key: variable.key,
+ version: variable.version
+ })
+ }
+ }
+}
diff --git a/packages/core/src/kiwi/fig/import.ts b/packages/core/src/kiwi/fig/import.ts
deleted file mode 100644
index b8954aaea..000000000
--- a/packages/core/src/kiwi/fig/import.ts
+++ /dev/null
@@ -1,599 +0,0 @@
-import { isNotNil } from 'es-toolkit/predicate'
-
-import { populateAndApplyOverrides } from '@open-pencil/fig/instance-overrides'
-import type { InstanceNodeChange } from '@open-pencil/fig/instance-overrides'
-import {
- applyStyleRefsToFields,
- ENABLED_LIBRARIES_PLUGIN_KEY,
- getOpenPencilPluginValue,
- guidToString,
- importCanvasGuides,
- linkImportedInstanceChildren,
- nodeChangeToProps,
- shouldImportTextAsAutoSize,
- sortChildren,
- resolveVariableConsumptionEntry,
- setVariableColorResolver
-} from '@open-pencil/fig/node-change'
-import type { NodeChange, VariableDataValuesEntry, Color, GUID } from '@open-pencil/kiwi/fig/codec'
-import { SceneGraph } from '@open-pencil/scene-graph'
-import type {
- ComponentPropertyDefinition,
- VariableType,
- VariableValue
-} from '@open-pencil/scene-graph'
-
-import { BLACK } from '#core/constants'
-import { setLazyFigImportContext } from '#core/kiwi/fig/lazy-import'
-
-type AssetRef = { key: string; version?: string }
-type AliasRef = { guid?: GUID; assetRef?: AssetRef }
-
-function applyImportedCanvasMetadata(
- page: ReturnType<SceneGraph['addPage']>,
- canvasNc: NodeChange
-) {
- page.source.format = 'fig'
- page.source.orderKey = canvasNc.parentIndex?.position ?? null
- if (canvasNc.backgroundColor)
- page.source.fig.rawNodeFields.backgroundColor = structuredClone(canvasNc.backgroundColor)
- if (canvasNc.backgroundPaints)
- page.source.fig.rawNodeFields.backgroundPaints = structuredClone(canvasNc.backgroundPaints)
- if (canvasNc.guides) {
- page.guides = importCanvasGuides(canvasNc.guides)
- page.source.fig.rawNodeFields.guides = structuredClone(canvasNc.guides)
- }
- page.source.fig.rawNodeFields.strokeJoin = canvasNc.strokeJoin
- page.source.fig.rawNodeFields.strokeWeight = canvasNc.strokeWeight
- if (canvasNc.pageType) page.source.fig.rawNodeFields.pageType = canvasNc.pageType
-}
-
-function applyImportedDocumentMetadata(graph: SceneGraph, docNc: NodeChange | undefined) {
- const rootNode = graph.getNode(graph.rootId)
- if (!docNc || !rootNode) return
- rootNode.source.format = 'fig'
- rootNode.pluginData = docNc.pluginData
- ? docNc.pluginData.map((entry) => ({
- pluginId: entry.pluginID,
- key: entry.key,
- value: entry.value
- }))
- : []
- rootNode.source.fig.rawNodeFields.strokeJoin = docNc.strokeJoin
- rootNode.source.fig.rawNodeFields.strokeWeight = docNc.strokeWeight
- const bindings = getOpenPencilPluginValue(docNc, ENABLED_LIBRARIES_PLUGIN_KEY)
- if (!bindings) return
- try {
- const parsed = JSON.parse(bindings) as unknown
- if (!Array.isArray(parsed)) return
- for (const entry of parsed) {
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
- const value = entry as { libraryId?: unknown; revisionId?: unknown; enabled?: unknown }
- if (typeof value.libraryId !== 'string' || typeof value.revisionId !== 'string') continue
- graph.enabledLibraries.set(value.libraryId, {
- libraryId: value.libraryId,
- revisionId: value.revisionId,
- enabled: value.enabled === true
- })
- }
- } catch (error) {
- console.warn('Ignored malformed OpenPencil library metadata', error)
- }
-}
-
-function assetRefKey(assetRef: AssetRef): string {
- return assetRef.version ? `${assetRef.key}@${assetRef.version}` : assetRef.key
-}
-
-function buildAssetRefMap(changeMap: Map<string, NodeChange>): Map<string, string> {
- const refs = new Map<string, string>()
- for (const [id, nc] of changeMap) {
- if (typeof nc.key !== 'string') continue
- 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') {
- refs.set(assetRefKey({ key: nc.key, version: nc.userFacingVersion }), id)
- }
- }
- return refs
-}
-
-function resolveAliasId(alias: AliasRef, assetRefs: Map<string, string>): string | undefined {
- if (alias.guid) return guidToString(alias.guid)
- if (!alias.assetRef) return undefined
- return assetRefs.get(assetRefKey(alias.assetRef)) ?? assetRefs.get(alias.assetRef.key)
-}
-
-function buildVariableColorResolver(
- changeMap: Map<string, NodeChange>,
- assetRefs: Map<string, string>
-): (alias: AliasRef) => Color | null {
- // Collect variable data: GUID → entries
- const varEntries = new Map<string, VariableDataValuesEntry[]>()
- const varSetId = new Map<string, string>()
- for (const [id, nc] of changeMap) {
- if (nc.type !== 'VARIABLE') continue
- varEntries.set(id, nc.variableDataValues?.entries ?? [])
- const setGuid = nc.variableSetID?.guid ? guidToString(nc.variableSetID.guid) : undefined
- const parentGuid = nc.parentIndex?.guid ? guidToString(nc.parentIndex.guid) : undefined
- if (setGuid) varSetId.set(id, setGuid)
- else if (parentGuid) varSetId.set(id, parentGuid)
- }
-
- // Collection default modes
- const defaultModes = new Map<string, string>()
- for (const [id, nc] of changeMap) {
- if (nc.type !== 'VARIABLE_SET') continue
- const modes = nc.variableSetModes ?? []
- if (modes.length > 0) defaultModes.set(id, guidToString(modes[0].id))
- }
-
- function resolveById(
- id: string,
- preferredModeId: string | undefined,
- depth: number
- ): Color | null {
- if (depth > 10) return null
- const entries = varEntries.get(id)
- if (!entries?.length) return null
-
- const setId = varSetId.get(id)
- const defaultMode = setId ? defaultModes.get(setId) : undefined
- let entry = preferredModeId
- ? entries.find((e) => guidToString(e.modeID) === preferredModeId)
- : undefined
- if (!entry && defaultMode) entry = entries.find((e) => guidToString(e.modeID) === defaultMode)
- if (!entry) entry = entries[0]
-
- const val = entry.variableData.value
- if (!val) return null
- if (val.colorValue) return val.colorValue
- if (val.alias) {
- const aliasId = resolveAliasId(val.alias, assetRefs)
- if (aliasId) return resolveById(aliasId, guidToString(entry.modeID), depth + 1)
- }
- return null
- }
-
- return function resolve(alias: AliasRef): Color | null {
- const id = resolveAliasId(alias, assetRefs)
- return id ? resolveById(id, undefined, 0) : null
- }
-}
-
-interface ChangeMaps {
- changeMap: Map<string, NodeChange>
- parentMap: Map<string, string>
- childrenMap: Map<string, string[]>
-}
-
-function buildChangeMaps(nodeChanges: NodeChange[]): ChangeMaps {
- const changeMap = new Map<string, NodeChange>()
- const parentMap = new Map<string, string>()
- const childrenMap = new Map<string, string[]>()
-
- for (const nc of nodeChanges) {
- if (!nc.guid) continue
- if (nc.phase === 'REMOVED') continue
- const id = guidToString(nc.guid)
- changeMap.set(id, nc)
-
- if (nc.parentIndex?.guid) {
- const pid = guidToString(nc.parentIndex.guid)
- parentMap.set(id, pid)
- let siblings = childrenMap.get(pid)
- if (!siblings) {
- siblings = []
- childrenMap.set(pid, siblings)
- }
- siblings.push(id)
- }
- }
-
- for (const [parentId, children] of childrenMap) {
- const parentNc = changeMap.get(parentId)
- if (parentNc) sortChildren(children, parentNc, changeMap)
- }
-
- return { changeMap, parentMap, childrenMap }
-}
-
-function resolveVariableType(resolvedType: string | undefined): VariableType {
- if (resolvedType === 'COLOR') return 'COLOR'
- if (resolvedType === 'BOOLEAN') return 'BOOLEAN'
- if (resolvedType === 'STRING') return 'STRING'
- return 'FLOAT'
-}
-
-function resolveVariableValue(
- entry: VariableDataValuesEntry,
- assetRefs: Map<string, string>
-): VariableValue | undefined {
- const vd = entry.variableData
- if (!vd.value) return undefined
-
- const dt = vd.dataType ?? vd.resolvedDataType
- if (dt === 'COLOR' && vd.value.colorValue) {
- const c = vd.value.colorValue
- return { r: c.r, g: c.g, b: c.b, a: c.a }
- }
- if (dt === 'BOOLEAN') return vd.value.boolValue ?? false
- if (dt === 'STRING') return vd.value.textValue ?? ''
- if (dt === 'ALIAS' && vd.value.alias) {
- const aliasId = resolveAliasId(vd.value.alias, assetRefs)
- if (aliasId) return { aliasId }
- return undefined
- }
- return vd.value.floatValue ?? 0
-}
-
-function resolveDefaultValue(type: VariableType): VariableValue {
- if (type === 'BOOLEAN') return false
- if (type === 'STRING') return ''
- if (type === 'COLOR') return { ...BLACK }
- return 0
-}
-
-function importCollections(changeMap: Map<string, NodeChange>, graph: SceneGraph): void {
- for (const [id, nc] of changeMap) {
- if (nc.type !== 'VARIABLE_SET') continue
-
- const modes = (nc.variableSetModes ?? []).map((m) => {
- const modeId = guidToString(m.id)
- return { modeId, name: m.name }
- })
- if (modes.length === 0) modes.push({ modeId: 'default', name: 'Default' })
-
- graph.addCollection({
- id,
- name: nc.name ?? 'Variables',
- modes,
- defaultModeId: modes[0].modeId,
- variableIds: []
- })
- }
-}
-
-function resolveVariableCollectionId(
- nc: NodeChange,
- id: string,
- parentMap: Map<string, string>,
- assetRefs: Map<string, string>
-): string {
- if (nc.variableSetID?.guid) return guidToString(nc.variableSetID.guid)
- const assetRef = nc.variableSetID?.assetRef
- if (assetRef) return assetRefs.get(assetRefKey(assetRef)) ?? assetRefs.get(assetRef.key) ?? ''
- return parentMap.get(id) ?? ''
-}
-
-function addFallbackCollection(
- changeMap: Map<string, NodeChange>,
- graph: SceneGraph,
- collectionId: string
-): void {
- if (graph.variableCollections.has(collectionId)) return
- const parentNc = changeMap.get(collectionId)
- graph.addCollection({
- id: collectionId,
- name: parentNc?.name ?? 'Variables',
- modes: [{ modeId: 'default', name: 'Default' }],
- defaultModeId: 'default',
- variableIds: []
- })
-}
-
-function importVariableEntries(
- changeMap: Map<string, NodeChange>,
- parentMap: Map<string, string>,
- graph: SceneGraph,
- assetRefs: Map<string, string>
-): void {
- for (const [id, nc] of changeMap) {
- if (nc.type !== 'VARIABLE') continue
-
- const collectionId = resolveVariableCollectionId(nc, id, parentMap, assetRefs)
- addFallbackCollection(changeMap, graph, collectionId)
-
- const type = resolveVariableType(nc.variableResolvedType)
- const valuesByMode: Record<string, VariableValue> = {}
-
- if (nc.variableDataValues?.entries) {
- for (const entry of nc.variableDataValues.entries) {
- const val = resolveVariableValue(entry, assetRefs)
- if (val !== undefined) {
- valuesByMode[guidToString(entry.modeID)] = val
- }
- }
- }
-
- if (Object.keys(valuesByMode).length === 0) {
- const col = graph.variableCollections.get(collectionId)
- const defaultMode = col?.defaultModeId ?? 'default'
- valuesByMode[defaultMode] = resolveDefaultValue(type)
- }
-
- graph.addVariable({
- id,
- name: nc.name ?? 'Variable',
- type,
- collectionId,
- valuesByMode,
- description: '',
- hiddenFromPublishing: false,
- key: typeof nc.key === 'string' ? nc.key : undefined,
- version: typeof nc.version === 'string' ? nc.version : undefined
- })
- }
-}
-
-function importPages(
- graph: SceneGraph,
- changeMap: Map<string, NodeChange>,
- parentMap: Map<string, string>,
- childrenMap: Map<string, string[]>,
- created: Set<string>,
- canvasIdToPageId: Map<string, string>,
- createSceneNode: (ncId: string, graphParentId: string) => void
-): void {
- let docId: string | null = null
- for (const [id, nc] of changeMap) {
- if (nc.type === 'DOCUMENT' || id === '0:0') {
- docId = id
- break
- }
- }
-
- if (docId) {
- applyImportedDocumentMetadata(graph, changeMap.get(docId))
-
- for (const canvasId of childrenMap.get(docId) ?? []) {
- const canvasNc = changeMap.get(canvasId)
- if (!canvasNc) continue
- if (canvasNc.type === 'CANVAS') {
- const page = graph.addPage(canvasNc.name ?? 'Page')
- page.source.id = canvasId
- applyImportedCanvasMetadata(page, canvasNc)
- canvasIdToPageId.set(canvasId, page.id)
- if (canvasNc.internalOnly) page.internalOnly = true
- created.add(canvasId)
- for (const childId of childrenMap.get(canvasId) ?? []) {
- createSceneNode(childId, page.id)
- }
- } else {
- createSceneNode(canvasId, graph.getPages()[0]?.id ?? graph.rootId)
- }
- }
- } else {
- const roots: string[] = []
- for (const [id] of changeMap) {
- const pid = parentMap.get(id)
- if (!pid || !changeMap.has(pid)) roots.push(id)
- }
- const page = graph.getPages()[0] ?? graph.addPage('Page 1')
- for (const rootId of roots) {
- createSceneNode(rootId, page.id)
- }
- }
-}
-
-function importVariableBindings(
- changeMap: Map<string, NodeChange>,
- guidToNodeId: Map<string, string>,
- graph: SceneGraph
-): void {
- for (const [ncId, nc] of changeMap) {
- if (!nc.variableConsumptionMap?.entries?.length) continue
- const nodeId = guidToNodeId.get(ncId)
- if (!nodeId) continue
- for (const entry of nc.variableConsumptionMap.entries) {
- const binding = resolveVariableConsumptionEntry(entry)
- if (binding) graph.bindVariable(nodeId, binding.field, binding.variableId)
- }
- }
-}
-
-function remapComponentIds(graph: SceneGraph, guidToNodeId: Map<string, string>): void {
- graph.preserveSourceMetadataDuring(() => {
- for (const node of graph.getAllNodes()) {
- if (node.type !== 'INSTANCE' || !node.componentId) continue
- const remapped = guidToNodeId.get(node.componentId)
- if (remapped) graph.updateNode(node.id, { componentId: remapped })
- }
- })
-}
-
-/**
- * INSTANCE_SWAP definitions/assignments store a target node's GUID (matching
- * how it was exported), not this import's freshly-assigned node ID — remap
- * them the same way remapComponentIds fixes up instance.componentId.
- */
-function remapInstanceSwapPropertyValues(
- graph: SceneGraph,
- guidToNodeId: Map<string, string>
-): void {
- const defsById = new Map<string, ComponentPropertyDefinition>()
- for (const node of graph.getAllNodes()) {
- for (const def of node.componentPropertyDefinitions) {
- if (!defsById.has(def.id)) defsById.set(def.id, def)
- }
- }
-
- graph.preserveSourceMetadataDuring(() => {
- for (const node of graph.getAllNodes()) {
- if (node.componentPropertyDefinitions.length > 0) {
- const defs = node.componentPropertyDefinitions.map((def) => {
- if (def.type !== 'INSTANCE_SWAP') return def
- const remappedDefault = def.defaultValue ? guidToNodeId.get(def.defaultValue) : undefined
- if (!remappedDefault) return def
- return { ...def, defaultValue: remappedDefault }
- })
- const changed = defs.some((def, i) => def !== node.componentPropertyDefinitions[i])
- if (changed) graph.updateNode(node.id, { componentPropertyDefinitions: defs })
- }
-
- if (Object.keys(node.componentPropertyAssignments).length > 0) {
- let changed = false
- const assignments = { ...node.componentPropertyAssignments }
- for (const [propId, value] of Object.entries(assignments)) {
- if (defsById.get(propId)?.type !== 'INSTANCE_SWAP') continue
- const remapped = guidToNodeId.get(value)
- if (remapped) {
- assignments[propId] = remapped
- changed = true
- }
- }
- if (changed) graph.updateNode(node.id, { componentPropertyAssignments: assignments })
- }
- }
- })
-}
-
-function applyVariantPropSpecs(graph: SceneGraph): void {
- for (const node of graph.getAllNodes()) {
- if (node.type !== 'COMPONENT' || node.variantPropSpecs.length === 0 || !node.parentId) continue
- const parent = graph.getNode(node.parentId)
- if (parent?.type !== 'COMPONENT_SET') continue
- const defs = new Map(parent.componentPropertyDefinitions.map((def) => [def.id, def.name]))
- const values: Record<string, string> = {}
- for (const spec of node.variantPropSpecs)
- values[defs.get(spec.propDefId) ?? spec.propDefId] = spec.value
- graph.updateNode(node.id, { componentPropertyValues: values })
- }
-}
-
-function parseDocumentColorSpace(nodeChanges: NodeChange[]): 'srgb' | 'display-p3' {
- const documentNode = nodeChanges.find((nc) => nc.type === 'DOCUMENT')
- return documentNode?.documentColorProfile === 'DISPLAY_P3' ? 'display-p3' : 'srgb'
-}
-
-function applyStyleRefs(
- changeMap: Map<string, NodeChange>,
- assetRefs: ReadonlyMap<string, string>
-): void {
- for (const nc of changeMap.values()) applyStyleRefsToFields(changeMap, nc, assetRefs)
-}
-
-export interface FigImportOptions {
- populate?: 'all' | 'first-page' | 'none'
-}
-
-function rememberLazyFigImportContext(
- graph: SceneGraph,
- changeMap: Map<string, NodeChange>,
- guidToNodeId: Map<string, string>,
- blobs: Uint8Array[],
- populatedRootIds: string[]
-): void {
- setLazyFigImportContext(graph, {
- changeMap: changeMap as Map<string, InstanceNodeChange>,
- guidToNodeId,
- blobs,
- populatedRootIds: new Set(populatedRootIds)
- })
-}
-
-function componentPageIdsForLazyPopulation(graph: SceneGraph): Set<string> {
- const pageIds = new Set<string>()
- for (const node of graph.getAllNodes()) {
- if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') continue
- let current = node.parentId ? graph.getNode(node.parentId) : undefined
- while (current?.parentId && current.type !== 'CANVAS') {
- current = graph.getNode(current.parentId)
- }
- if (current?.type === 'CANVAS') pageIds.add(current.id)
- }
- return pageIds
-}
-
-export function importNodeChanges(
- nodeChanges: NodeChange[],
- blobs: Uint8Array[] = [],
- images?: Map<string, Uint8Array>,
- options: FigImportOptions = {}
-): SceneGraph {
- const graph = new SceneGraph()
- graph.documentColorSpace = parseDocumentColorSpace(nodeChanges)
-
- if (images) {
- for (const [hash, data] of images) {
- graph.images.set(hash, data)
- }
- }
-
- for (const page of graph.getPages(true)) {
- graph.deleteNode(page.id)
- }
-
- const { changeMap, parentMap, childrenMap } = buildChangeMaps(nodeChanges)
- const assetRefs = buildAssetRefMap(changeMap)
- applyStyleRefs(changeMap, assetRefs)
- setVariableColorResolver(buildVariableColorResolver(changeMap, assetRefs))
-
- const canvasIdToPageId = new Map<string, string>()
- const created = new Set<string>()
- const guidToNodeId = new Map<string, string>()
- const getChildren = (ncId: string): string[] => childrenMap.get(ncId) ?? []
-
- function createSceneNode(ncId: string, graphParentId: string) {
- if (created.has(ncId)) return
- created.add(ncId)
-
- const nc = changeMap.get(ncId)
- if (!nc) return
-
- const { nodeType, ...props } = nodeChangeToProps(nc, blobs)
- if (props.sharedStyleType) props.internalOnly = true
- if (nodeType === 'DOCUMENT' || nodeType === 'VARIABLE' || nc.type === 'VARIABLE_SET') return
- if (shouldImportTextAsAutoSize(nc, changeMap.get(parentMap.get(ncId) ?? ''))) {
- props.textAutoResize = 'WIDTH_AND_HEIGHT'
- }
-
- const parentId = canvasIdToPageId.get(graphParentId) ?? graphParentId
- const node = graph.createNode(nodeType, parentId, props)
- guidToNodeId.set(ncId, node.id)
-
- for (const childId of getChildren(ncId)) {
- createSceneNode(childId, node.id)
- }
- }
-
- importPages(graph, changeMap, parentMap, childrenMap, created, canvasIdToPageId, createSceneNode)
-
- importCollections(changeMap, graph)
- importVariableEntries(changeMap, parentMap, graph, assetRefs)
- importVariableBindings(changeMap, guidToNodeId, graph)
- remapComponentIds(graph, guidToNodeId)
- remapInstanceSwapPropertyValues(graph, guidToNodeId)
- applyVariantPropSpecs(graph)
-
- const firstPageId = graph.getPages().find((page) => !page.internalOnly)?.id
- const componentPageIds =
- options.populate === 'first-page' ? componentPageIdsForLazyPopulation(graph) : new Set<string>()
- const activeRootIds =
- options.populate === 'first-page'
- ? [firstPageId, ...componentPageIds].filter(isNotNil)
- : undefined
-
- if (options.populate !== 'none') {
- graph.preserveSourceMetadataDuring(() => {
- populateAndApplyOverrides(
- graph,
- changeMap as Map<string, InstanceNodeChange>,
- guidToNodeId,
- blobs,
- activeRootIds
- )
- })
- }
-
- // Link imported instance children after population so linkage operates on the final tree state.
- linkImportedInstanceChildren(graph)
-
- if (activeRootIds)
- rememberLazyFigImportContext(graph, changeMap, guidToNodeId, blobs, activeRootIds)
-
- setVariableColorResolver(null)
- if (graph.getPages(true).length === 0) graph.addPage('Page 1')
- return graph
-}
diff --git a/packages/core/src/kiwi/fig/lazy-import.ts b/packages/core/src/kiwi/fig/lazy-import.ts
deleted file mode 100644
index c4cdc6a79..000000000
--- a/packages/core/src/kiwi/fig/lazy-import.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { populateAndApplyOverrides } from '@open-pencil/fig/instance-overrides'
-import type { InstanceNodeChange } from '@open-pencil/fig/instance-overrides'
-import type { SceneGraph } from '@open-pencil/scene-graph'
-
-export interface LazyFigImportContext {
- changeMap: Map<string, InstanceNodeChange>
- guidToNodeId: Map<string, string>
- blobs: Uint8Array[]
- populatedRootIds: Set<string>
-}
-
-const lazyFigImportContexts = new WeakMap<SceneGraph, LazyFigImportContext>()
-
-export function setLazyFigImportContext(graph: SceneGraph, context: LazyFigImportContext): void {
- lazyFigImportContexts.set(graph, context)
-}
-
-export function getLazyFigImportContext(graph: SceneGraph): LazyFigImportContext | undefined {
- return lazyFigImportContexts.get(graph)
-}
-
-export function clearLazyFigImportContext(graph: SceneGraph): void {
- lazyFigImportContexts.delete(graph)
-}
-
-function applyPopulation(
- graph: SceneGraph,
- context: LazyFigImportContext,
- rootIds?: string[]
-): void {
- graph.preserveSourceMetadataDuring(() => {
- populateAndApplyOverrides(
- graph,
- context.changeMap,
- context.guidToNodeId,
- context.blobs,
- rootIds
- )
- })
- const populatedRootIds = rootIds ?? graph.getPages(true).map((page) => page.id)
- for (const id of populatedRootIds) context.populatedRootIds.add(id)
-}
-
-function populateRoots(
- graph: SceneGraph,
- context: LazyFigImportContext,
- rootIds: Iterable<string>
-): boolean {
- const pending = [...rootIds].filter((id) => id && !context.populatedRootIds.has(id))
- if (pending.length === 0) return false
- applyPopulation(graph, context, pending)
- return true
-}
-
-export function populateLazyFigImportRoots(graph: SceneGraph, rootIds: Iterable<string>): boolean {
- const context = getLazyFigImportContext(graph)
- return context ? populateRoots(graph, context, rootIds) : false
-}
-
-export function populateAllLazyFigImportRoots(graph: SceneGraph): boolean {
- const context = getLazyFigImportContext(graph)
- if (!context) return false
- const rootIds = graph.getPages(true).map((page) => page.id)
- if (rootIds.every((id) => context.populatedRootIds.has(id))) return false
-
- // Revisit the initially populated page without an active-root filter.
- // Cross-page component chains can only stabilize when global override
- // resolution can see every source and target in the same pass.
- applyPopulation(graph, context)
- return true
-}
diff --git a/packages/core/src/kiwi/fig/node-change/serialize.ts b/packages/core/src/kiwi/fig/node-change/serialize.ts
index 9cf8b3ad3..840395589 100644
--- a/packages/core/src/kiwi/fig/node-change/serialize.ts
+++ b/packages/core/src/kiwi/fig/node-change/serialize.ts
@@ -1,8 +1,9 @@
import {
sceneNodeToKiwi as sceneNodeToKiwiWithRuntime,
- type KiwiNodeChange
+ type KiwiNodeChange,
+ type SceneNodeToKiwiOptions
} from '@open-pencil/fig/node-change'
-import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { GUID } from '@open-pencil/scene-graph/primitives'
import { getGlyphOutlineMetricsSync } from '#core/text/opentype'
@@ -31,32 +32,10 @@ export function sceneNodeToKiwi(
localIdCounter: { value: number },
graph: SceneGraph,
blobs: Uint8Array[],
- nodeIdToGuid?: Map<string, GUID>,
- fontDigestMap?: Map<string, Uint8Array>,
- varIdToGuid?: Map<string, GUID>,
- glyphBlobMap = new Map<string, number>(),
- blobIndexByHex?: Map<string, number>,
- assignedGuidValues?: Set<string>,
- componentPropertyDefinitionsById?: ReadonlyMap<string, ComponentPropertyDefinition>,
- modeIdToGuid?: Map<string, GUID>,
- propertyIdToGuid?: Map<string, GUID>
+ options: SceneNodeToKiwiOptions = {}
): KiwiNodeChange[] {
- return sceneNodeToKiwiWithRuntime(
- node,
- parentGuid,
- childIndex,
- localIdCounter,
- graph,
- blobs,
- nodeIdToGuid,
- fontDigestMap,
- varIdToGuid,
- glyphBlobMap,
- blobIndexByHex,
- assignedGuidValues,
- coreFigExportRuntime,
- componentPropertyDefinitionsById,
- modeIdToGuid,
- propertyIdToGuid
- )
+ return sceneNodeToKiwiWithRuntime(node, parentGuid, childIndex, localIdCounter, graph, blobs, {
+ ...options,
+ runtime: options.runtime ?? coreFigExportRuntime
+ })
}
diff --git a/packages/core/src/kiwi/fig/parse/client.ts b/packages/core/src/kiwi/fig/parse/client.ts
deleted file mode 100644
index 899e85a1c..000000000
--- a/packages/core/src/kiwi/fig/parse/client.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export function createFigParseWorker(): Worker {
- return new Worker(new URL('./worker.ts', import.meta.url), {
- type: 'module'
- })
-}
diff --git a/packages/core/src/kiwi/fig/parse/transfer.ts b/packages/core/src/kiwi/fig/parse/transfer.ts
index 3a2718373..ffb8336ba 100644
--- a/packages/core/src/kiwi/fig/parse/transfer.ts
+++ b/packages/core/src/kiwi/fig/parse/transfer.ts
@@ -1,27 +1,16 @@
-import type { InstanceNodeChange } from '@open-pencil/fig/instance-overrides'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { EnabledLibraryBinding, SceneNode } from '@open-pencil/scene-graph'
-import { getLazyFigImportContext, setLazyFigImportContext } from '#core/kiwi/fig/lazy-import'
import type { PortableSceneGraphData } from '#core/kiwi/fig/parse/portable-data'
-export interface SerializedLazyFigImportContext {
- changeMap: Array<[string, InstanceNodeChange]>
- guidToNodeId: Array<[string, string]>
- blobs: Uint8Array[]
- populatedRootIds: string[]
-}
-
export interface SerializedSceneGraph extends PortableSceneGraphData {
instanceIndex: Array<[string, string[]]>
figKiwiVersion: number | null
figSchemaDeflated: Uint8Array | null
enabledLibraries?: Array<[string, EnabledLibraryBinding]>
- lazyFigImport?: SerializedLazyFigImportContext
}
export function serializeSceneGraph(graph: SceneGraph): SerializedSceneGraph {
- const lazyFigImport = getLazyFigImportContext(graph)
return {
rootId: graph.rootId,
nodes: [...graph.nodes],
@@ -33,15 +22,7 @@ export function serializeSceneGraph(graph: SceneGraph): SerializedSceneGraph {
figKiwiVersion: graph.figKiwiVersion,
figSchemaDeflated: graph.figSchemaDeflated,
documentColorSpace: graph.documentColorSpace,
- enabledLibraries: [...graph.enabledLibraries],
- lazyFigImport: lazyFigImport
- ? {
- changeMap: [...lazyFigImport.changeMap],
- guidToNodeId: [...lazyFigImport.guidToNodeId],
- blobs: lazyFigImport.blobs,
- populatedRootIds: [...lazyFigImport.populatedRootIds]
- }
- : undefined
+ enabledLibraries: [...graph.enabledLibraries]
}
}
@@ -56,15 +37,7 @@ export function serializedSceneGraphTransferList(data: SerializedSceneGraph): Tr
buffers.add(image.buffer)
}
}
- for (const blob of data.lazyFigImport?.blobs ?? []) {
- if (
- blob.buffer instanceof ArrayBuffer &&
- blob.byteOffset === 0 &&
- blob.byteLength === blob.buffer.byteLength
- ) {
- buffers.add(blob.buffer)
- }
- }
+
if (data.figSchemaDeflated) {
if (
data.figSchemaDeflated.buffer instanceof ArrayBuffer &&
@@ -78,7 +51,7 @@ export function serializedSceneGraphTransferList(data: SerializedSceneGraph): Tr
}
/**
- * Clone the graph state that lazy FIG population may mutate while retaining immutable imported
+ * Clone the graph state that page population may mutate while retaining immutable imported
* resources by reference. Population replaces node fields and mutates child ID arrays, but only
* reads image bytes, variables, source changes, GUID mappings, blobs, and schema bytes.
*/
@@ -100,26 +73,25 @@ export function cloneSceneGraphForFigExport(graph: SceneGraph): SceneGraph {
cloned.documentColorSpace = graph.documentColorSpace
cloned.enabledLibraries = new Map(graph.enabledLibraries)
- const lazyFigImport = getLazyFigImportContext(graph)
- if (lazyFigImport) {
- setLazyFigImportContext(cloned, {
- changeMap: lazyFigImport.changeMap,
- guidToNodeId: lazyFigImport.guidToNodeId,
- blobs: lazyFigImport.blobs,
- populatedRootIds: new Set(lazyFigImport.populatedRootIds)
- })
- }
return cloned
}
-function normalizeNodeGuides(node: SceneNode): SceneNode {
- return Array.isArray(node.guides) ? node : { ...node, guides: [] }
+function normalizeImportedNode(
+ node: Omit<SceneNode, 'componentScale'> & { componentScale?: number }
+): SceneNode {
+ return {
+ ...node,
+ guides: Array.isArray(node.guides) ? node.guides : [],
+ variableBindingScales: { ...node.variableBindingScales },
+ variableAssignmentScales: { ...node.variableAssignmentScales },
+ componentScale: node.componentScale ?? 1
+ }
}
export function deserializeSceneGraph(data: SerializedSceneGraph): SceneGraph {
const graph = new SceneGraph()
graph.rootId = data.rootId
- graph.nodes = new Map(data.nodes.map(([id, node]) => [id, normalizeNodeGuides(node)]))
+ graph.nodes = new Map(data.nodes.map(([id, node]) => [id, normalizeImportedNode(node)]))
graph.images = new Map(data.images)
graph.variables = new Map(data.variables)
graph.variableCollections = new Map(data.variableCollections)
@@ -129,13 +101,6 @@ export function deserializeSceneGraph(data: SerializedSceneGraph): SceneGraph {
graph.figSchemaDeflated = data.figSchemaDeflated
graph.documentColorSpace = data.documentColorSpace
graph.enabledLibraries = data.enabledLibraries ? new Map(data.enabledLibraries) : new Map()
- if (data.lazyFigImport) {
- setLazyFigImportContext(graph, {
- changeMap: new Map(data.lazyFigImport.changeMap),
- guidToNodeId: new Map(data.lazyFigImport.guidToNodeId),
- blobs: data.lazyFigImport.blobs,
- populatedRootIds: new Set(data.lazyFigImport.populatedRootIds)
- })
- }
+
return graph
}
diff --git a/packages/core/src/kiwi/fig/parse/worker.ts b/packages/core/src/kiwi/fig/parse/worker.ts
deleted file mode 100644
index 6e6593700..000000000
--- a/packages/core/src/kiwi/fig/parse/worker.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { parseFigBuffer } from '@open-pencil/fig'
-import type { SceneGraph } from '@open-pencil/scene-graph'
-
-import { importNodeChanges } from '#core/kiwi/fig/import'
-import { getLazyFigImportContext, populateLazyFigImportRoots } from '#core/kiwi/fig/lazy-import'
-import {
- serializeSceneGraph,
- serializedSceneGraphTransferList
-} from '#core/kiwi/fig/parse/transfer'
-import { buildFigPopulationDelta, installFigMutationJournal } from '#core/kiwi/fig/population/delta'
-import type { FigSessionPopulateRequest } from '#core/kiwi/fig/session/protocol'
-
-interface WorkerParseRequest {
- buffer: ArrayBuffer
- options?: { populate?: 'all' | 'first-page' }
-}
-type PopulateRequest = FigSessionPopulateRequest
-type WorkerRequest = ArrayBuffer | WorkerParseRequest | PopulateRequest
-type WorkerPostMessage = (message: unknown, transfer: Transferable[]) => void
-const postWorkerMessage: WorkerPostMessage = (message, transfer) => {
- globalThis.postMessage(message, { transfer })
-}
-let graph: SceneGraph | undefined
-
-function isPopulateRequest(request: WorkerRequest): request is PopulateRequest {
- return !(request instanceof ArrayBuffer) && 'type' in request
-}
-
-self.onmessage = (event: MessageEvent<WorkerRequest>) => {
- const request = event.data
- try {
- if (isPopulateRequest(request)) {
- if (!graph) throw new Error('FIG parse worker has no retained graph')
- const journal = installFigMutationJournal(graph)
- try {
- const populated = populateLazyFigImportRoots(graph, [request.pageId])
- const context = getLazyFigImportContext(graph)
- if (!context) throw new Error('FIG population worker has no lazy import context')
- postWorkerMessage(
- {
- type: 'population-result',
- requestId: request.requestId,
- baseRevision: request.baseRevision,
- populated,
- delta: buildFigPopulationDelta(graph, journal, context.populatedRootIds)
- },
- []
- )
- } finally {
- journal.stop()
- }
- return
- }
- const parseRequest: WorkerParseRequest =
- request instanceof ArrayBuffer ? { buffer: request } : request
- const { nodeChanges, blobs, images, figKiwiVersion, figSchemaDeflated } = parseFigBuffer(
- parseRequest.buffer,
- (pages) => postWorkerMessage({ type: 'page-manifest', pages }, [])
- )
- const parsedGraph = importNodeChanges(nodeChanges, blobs, new Map(images), parseRequest.options)
- parsedGraph.figKiwiVersion = figKiwiVersion
- parsedGraph.figSchemaDeflated = figSchemaDeflated
- graph = parseRequest.options?.populate === 'first-page' ? parsedGraph : undefined
- const serialized = serializeSceneGraph(parsedGraph)
- const transfer =
- parseRequest.options?.populate === 'first-page'
- ? []
- : serializedSceneGraphTransferList(serialized)
- postWorkerMessage({ type: 'graph', graph: serialized }, transfer)
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
- postWorkerMessage(
- isPopulateRequest(request)
- ? { type: 'population-error', error: errorMessage }
- : { type: 'graph', error: errorMessage },
- []
- )
- }
-}
diff --git a/packages/core/src/kiwi/fig/population/client.ts b/packages/core/src/kiwi/fig/population/client.ts
index 72027e7fe..eb07c4c2d 100644
--- a/packages/core/src/kiwi/fig/population/client.ts
+++ b/packages/core/src/kiwi/fig/population/client.ts
@@ -1,19 +1,13 @@
import type { SceneGraph } from '@open-pencil/scene-graph'
-import { getLazyFigImportContext } from '#core/kiwi/fig/lazy-import'
+import { updateReaderRecovery, releaseReaderRecovery } from '#core/kiwi/fig/session/document-state'
import type { FigSessionResponse } from '#core/kiwi/fig/session/protocol'
import { randomHex } from '#core/random'
-import { applyFigPopulationDelta, type FigPopulationDelta } from './delta'
+import { applyFigPopulationDelta } from './delta'
-interface PopulationResult {
- type: 'population-result'
- requestId: string
- baseRevision: number
- populated: boolean
- delta: FigPopulationDelta
-}
-type WorkerResult = PopulationResult | { type: 'population-error'; error: string }
+/** The two responses this client acts on, taken from the session protocol itself. */
+type WorkerResult = Extract<FigSessionResponse, { type: 'population-result' | 'population-error' }>
const MAX_FIG_POPULATION_WORKER_NODES = 200_000
const FIG_POPULATION_WORKER_TIMEOUT_MS = 30_000
@@ -59,16 +53,8 @@ export function registerFigPopulationWorker(
emitTelemetry({ event: 'registered' })
}
-function isDevelopmentBuild(env?: { DEV?: boolean }): boolean {
- return env?.DEV ?? false
-}
-
export function canUseFigPopulationWorker(graph: SceneGraph): boolean {
- return (
- isDevelopmentBuild(import.meta.env) &&
- populationWorkers.has(graph) &&
- getLazyFigImportContext(graph) !== undefined
- )
+ return populationWorkers.has(graph)
}
export function registerOriginalArchiveRequest(
@@ -100,6 +86,7 @@ export async function requestOriginalArchive(graph: SceneGraph): Promise<Uint8Ar
}
export function releaseFigPopulationWorker(graph: SceneGraph): void {
+ releaseReaderRecovery(graph)
populationWorkers.get(graph)?.terminate()
populationWorkers.delete(graph)
originalArchiveRequests.get(graph)?.unbind()
@@ -131,10 +118,10 @@ export function createFigPopulationWorker(graph: SceneGraph): FigPopulationWorke
return populationWorkers.get(graph) ?? null
}
-function createPopulationWorkerClient(
+export function createPopulationWorkerClient(
graph: SceneGraph,
- worker: Worker,
- port?: MessagePort
+ worker: Pick<Worker, 'postMessage' | 'terminate' | 'onerror' | 'onmessage'>,
+ port?: Pick<MessagePort, 'postMessage' | 'start' | 'close' | 'onmessage'>
): FigPopulationWorker {
const pending = new Map<
string,
@@ -199,8 +186,7 @@ function createPopulationWorkerClient(
const applyStartedAt = performance.now()
try {
applyFigPopulationDelta(graph, result.delta)
- const context = getLazyFigImportContext(graph)
- if (context) context.populatedRootIds = new Set(result.delta.populatedRootIds)
+ if (result.checkpoint) updateReaderRecovery(graph, result.checkpoint)
} catch {
applyingDelta = false
fail()
@@ -219,8 +205,7 @@ function createPopulationWorkerClient(
})
}
if (port) {
- port.onmessage = (event: MessageEvent<FigSessionResponse>) =>
- receive(event.data as WorkerResult)
+ port.onmessage = (event: MessageEvent<WorkerResult>) => receive(event.data)
port.start()
} else {
worker.onmessage = (event: MessageEvent<WorkerResult>) => receive(event.data)
diff --git a/packages/core/src/kiwi/fig/population/delta.ts b/packages/core/src/kiwi/fig/population/delta.ts
index 9d39bb7a4..a64feabd5 100644
--- a/packages/core/src/kiwi/fig/population/delta.ts
+++ b/packages/core/src/kiwi/fig/population/delta.ts
@@ -129,5 +129,11 @@ export function applyFigPopulationDelta(graph: SceneGraph, delta: FigPopulationD
for (const [id, changes] of delta.updated) graph.updateNode(id, changes)
for (const id of delta.deleted) graph.deleteNode(id)
})
- graph.instanceIndex = new Map(delta.instanceIndex.map(([id, ids]) => [id, new Set(ids)]))
+ graph.instanceIndex.clear()
+ for (const node of graph.getAllNodes()) {
+ if (node.type !== 'INSTANCE' || !node.componentId) continue
+ const ids = graph.instanceIndex.get(node.componentId) ?? new Set<string>()
+ ids.add(node.id)
+ graph.instanceIndex.set(node.componentId, ids)
+ }
}
diff --git a/packages/core/src/kiwi/fig/session/document-state.ts b/packages/core/src/kiwi/fig/session/document-state.ts
new file mode 100644
index 000000000..bac9969f4
--- /dev/null
+++ b/packages/core/src/kiwi/fig/session/document-state.ts
@@ -0,0 +1,107 @@
+import { createFigDocumentSession, type FigSessionCheckpoint } from '@open-pencil/fig'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { readerSessionOptions, type FigReaderDiagnostic } from '#core/kiwi/fig/session/options'
+
+/**
+ * Per-graph reader state: the archive bytes, the live session or its checkpoint, and the
+ * records that session skipped. Page population, diagnostics and recovery all read it.
+ */
+interface ReaderState {
+ bytes: ArrayBuffer
+ checkpoint?: FigSessionCheckpoint
+ session?: ReturnType<typeof createFigDocumentSession>
+ /** Records skipped by sessions this recovery state has opened. */
+ diagnostics: FigReaderDiagnostic[]
+}
+const states = new WeakMap<SceneGraph, ReaderState>()
+
+export function registerReaderRecovery(
+ graph: SceneGraph,
+ bytes: ArrayBuffer,
+ checkpoint: FigSessionCheckpoint
+): void {
+ states.set(graph, { bytes, checkpoint, diagnostics: [] })
+}
+
+export function registerReaderSession(
+ bytes: ArrayBuffer,
+ session: ReturnType<typeof createFigDocumentSession>,
+ diagnostics: FigReaderDiagnostic[] = []
+): void {
+ states.set(session.graph, { bytes, session, diagnostics })
+}
+
+/** Records skipped while opening, recovering, or exporting this graph's document. */
+export function readerDiagnostics(graph: SceneGraph): readonly FigReaderDiagnostic[] {
+ return states.get(graph)?.diagnostics ?? []
+}
+
+export function isReaderPagePending(graph: SceneGraph, pageId: string): boolean {
+ const state = states.get(graph)
+ if (!state) return false
+ const checkpoint = state.session?.checkpoint() ?? state.checkpoint
+ const sourceId = checkpoint?.sources.find(([, graphId]) => graphId === pageId)?.[0]
+ if (!sourceId) return false
+ const session = state.session
+ return session
+ ? session.pages.some((page) => page.id === sourceId) && !session.loadedPageIds.has(sourceId)
+ : !checkpoint.loadedPageIds.includes(sourceId)
+}
+
+export function hasReaderSession(graph: SceneGraph): boolean {
+ return states.has(graph)
+}
+
+export function populateFigPage(graph: SceneGraph, pageId: string): boolean {
+ return isReaderPagePending(graph, pageId) ? recoverReaderPage(graph, pageId) : false
+}
+
+export function populateAllFigPages(graph: SceneGraph): boolean {
+ let changed = false
+ for (const page of graph.getPages()) {
+ if (populateFigPage(graph, page.id)) changed = true
+ }
+ return changed
+}
+
+export function populateReaderExport(source: SceneGraph, target: SceneGraph): boolean {
+ const state = states.get(source)
+ if (!state) return false
+ const checkpoint = state.session?.checkpoint() ?? state.checkpoint
+ if (!checkpoint) throw new Error('Missing reader checkpoint')
+ const session = createFigDocumentSession(state.bytes, readerSessionOptions(state.diagnostics), {
+ graph: target,
+ checkpoint
+ })
+ // Export must include internal content too, not just the dependency closure needed
+ // for visible pages. Loading happens on the isolated target, never the live graph.
+ for (const page of session.pages) session.loadPage(page.id)
+ return true
+}
+
+export function updateReaderRecovery(graph: SceneGraph, checkpoint: FigSessionCheckpoint): void {
+ const state = states.get(graph)
+ if (state && !state.session) state.checkpoint = checkpoint
+}
+
+export function releaseReaderRecovery(graph: SceneGraph): void {
+ states.delete(graph)
+}
+
+export function recoverReaderPage(graph: SceneGraph, pageId: string): boolean {
+ const state = states.get(graph)
+ if (!state) throw new Error('No reader recovery state')
+ if (!state.session) {
+ if (!state.checkpoint) throw new Error('Missing reader checkpoint')
+ state.session = createFigDocumentSession(state.bytes, readerSessionOptions(state.diagnostics), {
+ graph,
+ checkpoint: state.checkpoint
+ })
+ }
+ const page = state.session.pages.find((page) => state.session?.graphPageId(page.id) === pageId)
+ if (!page) throw new Error(`Unknown graph page ${pageId}`)
+ const populated = !state.session.loadedPageIds.has(page.id)
+ state.session.loadPage(page.id)
+ return populated
+}
diff --git a/packages/core/src/kiwi/fig/session/options.ts b/packages/core/src/kiwi/fig/session/options.ts
new file mode 100644
index 000000000..4c50411c4
--- /dev/null
+++ b/packages/core/src/kiwi/fig/session/options.ts
@@ -0,0 +1,27 @@
+import type { DocumentAssemblyOptions } from '@open-pencil/fig'
+
+type Handler<K extends keyof DocumentAssemblyOptions> = NonNullable<DocumentAssemblyOptions[K]>
+
+/** A saved record the reader could not apply and skipped instead of refusing the file. */
+export type FigReaderDiagnostic =
+ | { kind: 'property'; diagnostic: Parameters<Handler<'onUnresolvedProperty'>>[0] }
+ | { kind: 'assignment'; diagnostic: Parameters<Handler<'onUnresolvedAssignment'>>[0] }
+ | { kind: 'binding'; diagnostic: Parameters<Handler<'onUnresolvedBinding'>>[0] }
+ | { kind: 'component'; diagnostic: Parameters<Handler<'onMissingComponent'>>[0] }
+
+/**
+ * Figma retains override and binding records that address nodes it later deleted, and
+ * instances of deleted components, and the reader has no replacement to guess at. Opening
+ * a file skips those records, keeps such instances childless, and reports both, including a
+ * swap whose target layer is gone. An ambiguous address means the path is wrong, not stale,
+ * and still fails.
+ */
+export function readerSessionOptions(sink: FigReaderDiagnostic[]): DocumentAssemblyOptions {
+ return {
+ derivedBounds: true,
+ onUnresolvedProperty: (diagnostic) => sink.push({ kind: 'property', diagnostic }),
+ onUnresolvedAssignment: (diagnostic) => sink.push({ kind: 'assignment', diagnostic }),
+ onUnresolvedBinding: (diagnostic) => sink.push({ kind: 'binding', diagnostic }),
+ onMissingComponent: (diagnostic) => sink.push({ kind: 'component', diagnostic })
+ }
+}
diff --git a/packages/core/src/kiwi/fig/session/protocol.ts b/packages/core/src/kiwi/fig/session/protocol.ts
index ed5ccb717..5da107e02 100644
--- a/packages/core/src/kiwi/fig/session/protocol.ts
+++ b/packages/core/src/kiwi/fig/session/protocol.ts
@@ -1,6 +1,7 @@
+import type { FigSessionCheckpoint } from '@open-pencil/fig'
import type { FigPageManifestEntry } from '@open-pencil/kiwi/fig'
-import type { FigImportOptions } from '#core/kiwi/fig/import'
+import type { ParseFigFileOptions } from '#core/io/formats/fig/read'
import type { SerializedSceneGraph } from '#core/kiwi/fig/parse/transfer'
import type { FigPopulationDelta } from '#core/kiwi/fig/population/delta'
@@ -8,7 +9,7 @@ export interface FigSessionOpenRequest {
type: 'open'
originalBuffer: ArrayBuffer
archiveBuffer: ArrayBuffer
- options?: FigImportOptions
+ options?: Pick<ParseFigFileOptions, 'populate'>
port: MessagePort
}
@@ -41,12 +42,18 @@ export type FigSessionRequest =
export type FigSessionResponse =
| { type: 'page-manifest'; pages: FigPageManifestEntry[] }
- | { type: 'graph'; graph?: SerializedSceneGraph; error?: string }
+ | {
+ type: 'graph'
+ graph?: SerializedSceneGraph
+ checkpoint?: FigSessionCheckpoint
+ error?: string
+ }
| {
type: 'population-result'
requestId: string
baseRevision: number
populated: boolean
+ checkpoint?: FigSessionCheckpoint
delta: FigPopulationDelta
}
| { type: 'population-error'; requestId?: string; error: string }
diff --git a/packages/core/src/kiwi/fig/session/reader.ts b/packages/core/src/kiwi/fig/session/reader.ts
new file mode 100644
index 000000000..e8a8ddde6
--- /dev/null
+++ b/packages/core/src/kiwi/fig/session/reader.ts
@@ -0,0 +1,60 @@
+import { createFigDocumentSession } from '@open-pencil/fig'
+import type { FigPageManifestEntry } from '@open-pencil/kiwi/fig'
+
+import { buildFigPopulationDelta, installFigMutationJournal } from '#core/kiwi/fig/population/delta'
+import { readerSessionOptions, type FigReaderDiagnostic } from '#core/kiwi/fig/session/options'
+
+/** Worker and main-thread transport for the .fig reader session for the FIG reader session. */
+export function openReaderSession(
+ bytes: ArrayBuffer,
+ populate: 'all' | 'first-page' | 'none' = 'all'
+) {
+ const diagnostics: FigReaderDiagnostic[] = []
+ const session = createFigDocumentSession(bytes, readerSessionOptions(diagnostics))
+ const pages: FigPageManifestEntry[] = session.pages.map((page) => ({
+ sourceId: page.id,
+ name: page.name,
+ position: page.position,
+ internalOnly: page.internalOnly
+ }))
+ const sourceByGraph = new Map<string, string>()
+ for (const page of session.pages) {
+ const id = session.graphPageId(page.id)
+ if (id) sourceByGraph.set(id, page.id)
+ }
+ const loadedGraphIds = () =>
+ [...session.loadedPageIds].flatMap((id) => {
+ const graphId = session.graphPageId(id)
+ return graphId ? [graphId] : []
+ })
+ if (populate === 'all') {
+ for (const page of pages) if (!page.internalOnly) session.loadPage(page.sourceId)
+ } else if (populate === 'first-page') {
+ const page = pages.find((page) => !page.internalOnly)
+ if (page) session.loadPage(page.sourceId)
+ }
+ return {
+ session,
+ /** Records skipped so far, including those of pages loaded later. */
+ diagnostics,
+ checkpoint: () => session.checkpoint(),
+ graph: session.graph,
+ pages,
+ populate(pageId: string) {
+ const sourceId = sourceByGraph.get(pageId)
+ if (!sourceId) throw new Error(`Unknown graph page ${pageId}`)
+ const populated = !session.loadedPageIds.has(sourceId)
+ const journal = installFigMutationJournal(session.graph)
+ try {
+ session.loadPage(sourceId)
+ return {
+ checkpoint: session.checkpoint(),
+ populated,
+ delta: buildFigPopulationDelta(session.graph, journal, loadedGraphIds())
+ }
+ } finally {
+ journal.stop()
+ }
+ }
+ }
+}
diff --git a/packages/core/src/kiwi/fig/session/worker.ts b/packages/core/src/kiwi/fig/session/worker.ts
index a1701e890..9252ad218 100644
--- a/packages/core/src/kiwi/fig/session/worker.ts
+++ b/packages/core/src/kiwi/fig/session/worker.ts
@@ -1,17 +1,12 @@
-import { parseFigBuffer } from '@open-pencil/fig'
-import type { SceneGraph } from '@open-pencil/scene-graph'
-
-import { importNodeChanges } from '#core/kiwi/fig/import'
-import { getLazyFigImportContext, populateLazyFigImportRoots } from '#core/kiwi/fig/lazy-import'
import { serializeSceneGraph } from '#core/kiwi/fig/parse/transfer'
-import { buildFigPopulationDelta, installFigMutationJournal } from '#core/kiwi/fig/population/delta'
import type {
FigSessionOpenRequest,
FigSessionRequest,
FigSessionResponse
} from '#core/kiwi/fig/session/protocol'
+import { openReaderSession } from '#core/kiwi/fig/session/reader'
-let graph: SceneGraph | undefined
+let session: ReturnType<typeof openReaderSession> | undefined
let originalArchive: Uint8Array | undefined
let port: MessagePort | undefined
@@ -20,22 +15,14 @@ function respond(message: FigSessionResponse): void {
}
function populate(request: Extract<FigSessionRequest, { type: 'populate' }>): void {
- if (!graph) throw new Error('FIG session has no retained graph')
- const journal = installFigMutationJournal(graph)
- try {
- const populated = populateLazyFigImportRoots(graph, [request.pageId])
- const context = getLazyFigImportContext(graph)
- if (!context) throw new Error('FIG session has no lazy import context')
- respond({
- type: 'population-result',
- requestId: request.requestId,
- baseRevision: request.baseRevision,
- populated,
- delta: buildFigPopulationDelta(graph, journal, context.populatedRootIds)
- })
- } finally {
- journal.stop()
- }
+ if (!session) throw new Error('FIG session has no retained reader')
+ const result = session.populate(request.pageId)
+ respond({
+ type: 'population-result',
+ requestId: request.requestId,
+ baseRevision: request.baseRevision,
+ ...result
+ })
}
function handleRequest(request: FigSessionRequest): void {
@@ -49,7 +36,7 @@ function handleRequest(request: FigSessionRequest): void {
return
}
if (request.type === 'dispose') {
- graph = undefined
+ session = undefined
originalArchive = undefined
respond({ type: 'disposed' })
port?.close()
@@ -75,15 +62,17 @@ self.onmessage = (event: MessageEvent<FigSessionOpenRequest>) => {
port.start()
originalArchive = new Uint8Array(request.archiveBuffer)
try {
- const { nodeChanges, blobs, images, figKiwiVersion, figSchemaDeflated } = parseFigBuffer(
- request.originalBuffer,
- (pages) => respond({ type: 'page-manifest', pages })
- )
- const parsedGraph = importNodeChanges(nodeChanges, blobs, new Map(images), request.options)
- parsedGraph.figKiwiVersion = figKiwiVersion
- parsedGraph.figSchemaDeflated = figSchemaDeflated
- graph = request.options?.populate === 'first-page' ? parsedGraph : undefined
- respond({ type: 'graph', graph: serializeSceneGraph(parsedGraph) })
+ const opened = openReaderSession(request.originalBuffer, request.options?.populate)
+ respond({ type: 'page-manifest', pages: opened.pages })
+ session =
+ request.options?.populate === 'first-page' || request.options?.populate === 'none'
+ ? opened
+ : undefined
+ respond({
+ type: 'graph',
+ graph: serializeSceneGraph(opened.graph),
+ checkpoint: opened.checkpoint()
+ })
} catch (error) {
respond({ type: 'graph', error: error instanceof Error ? error.message : String(error) })
}
diff --git a/packages/core/src/kiwi/index.ts b/packages/core/src/kiwi/index.ts
index c8cd0ec0a..6ee6acf2f 100644
--- a/packages/core/src/kiwi/index.ts
+++ b/packages/core/src/kiwi/index.ts
@@ -1,7 +1,5 @@
export { prefetchFigmaSchema } from '#core/clipboard'
export { readFigFile, parseFigFile } from './fig/file'
-export { importNodeChanges } from './fig/import'
-export { populateAllLazyFigImportRoots, populateLazyFigImportRoots } from './fig/lazy-import'
export { deduplicateNodeChangePluginData } from '@open-pencil/kiwi/fig/parse'
export {
initCodec,
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index e116c0177..e1155d653 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -515,6 +515,9 @@ function configureTextLeaf(
const cached = cache.get(cacheKey)
if (cached) return cached
+ if (constraintW === child.width && (child.derivedTextGlyphs?.length ?? 0) > 0) {
+ return { width: constraintW, height: child.height }
+ }
const measured = getTextMeasurer()?.(child, constraintW)
const result = {
width: constraintW,
diff --git a/packages/core/src/editor/layout-runner.ts b/packages/core/src/layout/mutations.ts
similarity index 100%
rename from packages/core/src/editor/layout-runner.ts
rename to packages/core/src/layout/mutations.ts
diff --git a/packages/core/src/layout/variables.ts b/packages/core/src/layout/variables.ts
new file mode 100644
index 000000000..7a31b17d1
--- /dev/null
+++ b/packages/core/src/layout/variables.ts
@@ -0,0 +1,15 @@
+import { reconcileNumericVariableBindings, type SceneGraph } from '@open-pencil/scene-graph'
+
+import { computeLayout } from '#core/layout'
+
+import { createLayoutRunner } from './mutations'
+
+/** Binding evaluation is derived work, not an additional history entry. */
+export function reconcileVariableLayouts(graph: SceneGraph): void {
+ const { runLayoutForNode } = createLayoutRunner(() => graph)
+ for (const id of reconcileNumericVariableBindings(graph)) {
+ // A deliberate binding change also invalidates a placed instance's saved Hug size.
+ computeLayout(graph, id)
+ runLayoutForNode(id)
+ }
+}
diff --git a/packages/core/tests/canvas/constraint-resize.test.ts b/packages/core/tests/canvas/constraint-resize.test.ts
new file mode 100644
index 000000000..5473cf941
--- /dev/null
+++ b/packages/core/tests/canvas/constraint-resize.test.ts
@@ -0,0 +1,49 @@
+import { resolve } from 'node:path'
+import { expect, test } from 'bun:test'
+
+import { SkiaRenderer } from '@open-pencil/core'
+import { initCanvasKit, renderNodesToImage } from '@open-pencil/core/io'
+import { materializeDocument } from '@open-pencil/fig'
+
+import { expectDefined } from '../helpers/assert'
+import { FIXTURES } from '../helpers/fig/fixtures'
+import { absoluteConstraintRecords } from '../helpers/fig/absolute-constraints'
+
+test('absolute resize constraints match native Figma pixels', async () => {
+ const { graph, sources } = materializeDocument(absoluteConstraintRecords())
+ const ck = await initCanvasKit()
+ const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))
+ const root = expectDefined(sources.get('1:4'))
+ const decode = (bytes: Uint8Array) => {
+ const image = expectDefined(ck.MakeImageFromEncoded(bytes))
+ try {
+ expect([image.width(), image.height()]).toEqual([200, 120])
+ return image.readPixels(0, 0, {
+ width: 200,
+ height: 120,
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB
+ })
+ } finally {
+ image.delete()
+ }
+ }
+ try {
+ const png = expectDefined(
+ renderNodesToImage(ck, renderer, graph, graph.getPages()[0].id, [root], {
+ scale: 1,
+ format: 'PNG',
+ trimTransparent: false
+ })
+ )
+ const native = new Uint8Array(
+ await Bun.file(
+ resolve(FIXTURES, 'absolute-constraint-figma.png')
+ ).arrayBuffer()
+ )
+ expect(decode(png)).toEqual(decode(native))
+ } finally {
+ renderer.destroy()
+ }
+})
diff --git a/packages/core/tests/canvas/instance-scale.test.ts b/packages/core/tests/canvas/instance-scale.test.ts
new file mode 100644
index 000000000..9d07bfdb7
--- /dev/null
+++ b/packages/core/tests/canvas/instance-scale.test.ts
@@ -0,0 +1,160 @@
+import { resolve } from 'node:path'
+import { expect, test } from 'bun:test'
+
+import { SkiaRenderer } from '@open-pencil/core'
+import { createEditor } from '@open-pencil/core/editor'
+import { initCanvasKit, renderNodesToImage } from '@open-pencil/core/io'
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { rescaleNodeTree } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../helpers/assert'
+import { inheritedNestedBindingRecords } from '../helpers/fig/nested-binding'
+import { FIXTURES, readFixtureJSON } from '../helpers/fig/fixtures'
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-layout-scale.json')
+
+const declared = readFixtureJSON<Record<string, unknown>[]>('nested-binding-ownership-records.json')
+
+for (const edit of [
+ 'direct',
+ 'variable',
+ 'declared',
+ 'authored',
+ 'component',
+ 'expression',
+ 'rescale',
+ 'definition'
+] as const) {
+ test(`${edit} nested scale edit matches the independent Figma raster`, async () => {
+ const captured = edit !== 'direct' && edit !== 'variable'
+ const records = captured
+ ? declared.nodeChanges
+ : [{ guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT' }, ...fixture.before]
+ const { graph, sources } = materializeDocument(
+ ['expression', 'definition'].includes(edit)
+ ? inheritedNestedBindingRecords()
+ : (records as NodeChange[]),
+ (captured ? declared : fixture).blobs.map((value) => Uint8Array.fromBase64(value)),
+ { derivedBounds: true }
+ )
+ const rootId = expectDefined(
+ sources.get(captured ? '293733:8' : fixture.ids.instance),
+ 'instance'
+ )
+ const width = {
+ direct: 300,
+ variable: 300,
+ declared: 268,
+ authored: 264,
+ component: 264,
+ expression: 300,
+ rescale: 132,
+ definition: 180
+ }[edit]
+ const height = {
+ direct: 56,
+ variable: 56,
+ declared: 56,
+ authored: 56,
+ component: 64,
+ expression: 56,
+ rescale: 28,
+ definition: 56
+ }[edit]
+ const nested = expectDefined(graph.getChildren(rootId)[0], 'nested instance')
+ const editor = createEditor({ graph })
+ if (!captured) editor.updateNodeWithUndo(rootId, { paddingLeft: 13 })
+ if (edit === 'definition') {
+ rescaleNodeTree(graph, rootId, 0.5)
+ const outer = expectDefined(sources.get('1:4'), 'outer component')
+ rescaleNodeTree(graph, graph.getChildren(outer)[0].id, 2)
+ await Promise.resolve()
+ expect(nested.paddingLeft).toBe(5)
+ } else if (['authored', 'component', 'rescale'].includes(edit)) {
+ editor.bindVariable(rootId, 'paddingRight', '293742:7')
+ editor.bindVariable(nested.id, 'paddingRight', '293742:7')
+ expect(nested.paddingRight).toBe(6)
+ if (edit === 'rescale') rescaleNodeTree(graph, rootId, 0.5)
+ if (edit === 'component') {
+ editor.updateNodeWithUndo(expectDefined(sources.get('1:2'), 'component'), { paddingTop: 8 })
+ await Promise.resolve()
+ expect(nested.paddingTop).toBe(2)
+ }
+ } else if (edit === 'declared' || edit === 'expression') {
+ const values =
+ edit === 'expression'
+ ? { first: 60, second: 40, afterFirst: 15, afterSecond: 10 }
+ : { first: 16, second: 12, afterFirst: 8, afterSecond: 6 }
+ const variable = expectDefined(
+ graph.variables.get(nested.boundVariables.paddingLeft),
+ 'declared variable'
+ )
+ const mode = graph.getNodeVariableModeId(nested.id, variable.collectionId)
+ editor.updateVariableValue(variable.id, mode, values.first)
+ expect(nested.paddingLeft).toBe(values.afterFirst)
+ editor.updateVariableValue(variable.id, mode, values.second)
+ expect(nested.paddingLeft).toBe(values.afterSecond)
+ } else if (edit === 'direct') editor.updateNodeWithUndo(nested.id, { paddingLeft: 7 })
+ else {
+ const collection = graph.createCollection('Spacing')
+ const variable = graph.createVariable('Padding', 'FLOAT', collection.id, 10)
+ graph.updateNode(nested.id, {
+ boundVariables: { paddingLeft: variable.id },
+ variableBindingScales: { paddingLeft: 0.25 }
+ })
+ editor.updateVariableValue(variable.id, collection.defaultModeId, 28)
+ }
+
+ const ck = await initCanvasKit()
+ const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1), 'surface'))
+ try {
+ const png = expectDefined(
+ renderNodesToImage(ck, renderer, graph, graph.getPages()[0].id, [rootId], {
+ scale: 8,
+ format: 'PNG',
+ trimTransparent: false
+ }),
+ 'rendered PNG'
+ )
+ const expectedBytes = new Uint8Array(
+ await Bun.file(
+ resolve(
+ FIXTURES,
+ {
+ direct: 'nested-layout-scale-figma.png',
+ variable: 'nested-layout-scale-figma.png',
+ declared: 'nested-binding-ownership-figma.png',
+ authored: 'nested-binding-authoring-figma.png',
+ component: 'nested-component-scale-figma.png',
+ expression: 'nested-binding-expression-figma.png',
+ rescale: 'nested-owner-rescale-figma.png',
+ definition: 'nested-definition-rescale-figma.png'
+ }[edit]
+ )
+ ).arrayBuffer()
+ )
+ const pixels = (bytes: Uint8Array) => {
+ const image = expectDefined(ck.MakeImageFromEncoded(bytes), 'decoded PNG')
+ try {
+ expect([image.width(), image.height()]).toEqual([width, height])
+ return expectDefined(
+ image.readPixels(0, 0, {
+ width,
+ height,
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB
+ }),
+ 'decoded pixels'
+ )
+ } finally {
+ image.delete()
+ }
+ }
+ expect(pixels(png)).toEqual(pixels(expectedBytes))
+ } finally {
+ renderer.destroy()
+ }
+ })
+}
diff --git a/packages/core/tests/clipboard/figma/replacement-import.test.ts b/packages/core/tests/clipboard/figma/replacement-import.test.ts
new file mode 100644
index 000000000..775067389
--- /dev/null
+++ b/packages/core/tests/clipboard/figma/replacement-import.test.ts
@@ -0,0 +1,40 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { prepareClipboardImport } from '#core/clipboard/fig-import'
+import { readFixtureJSON } from '../../helpers/fig/fixtures'
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-binding-ownership-records.json')
+
+
+test('replacement clipboard preparation imports real nested component bindings', () => {
+ const graph = new SceneGraph()
+ const operation = prepareClipboardImport(
+ fixture.nodeChanges,
+ graph,
+ graph.getPages()[0].id,
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
+ 20,
+ 30
+ )
+ expect(graph.getChildren(graph.getPages()[0].id)).toHaveLength(0)
+ operation.commit()
+ const roots = operation.plan.rootIds.map((id) => graph.getNode(id))
+ expect(roots.length).toBeGreaterThan(0)
+ const sourceId = operation.sourceIds.get('293733:8')
+ const placed = graph.getNode(operation.plan.nodeIds.get(sourceId ?? '') ?? '')
+ expect(placed).toBeDefined()
+ if (!placed) throw new Error('Missing instance')
+ const nested = graph.getChildren(placed.id)[0]
+ expect(nested.paddingLeft).toBe(6)
+ expect(graph.variables.has(nested.boundVariables.paddingLeft)).toBe(true)
+ expect(graph.getNode(placed.componentId ?? '')).toBeDefined()
+ operation.capture()
+ operation.undo()
+ expect(graph.getChildren(graph.getPages()[0].id)).toHaveLength(0)
+ expect(graph.variables.size).toBe(0)
+ operation.redo()
+ expect(graph.getNode(placed.id)).toBeDefined()
+ expect(graph.getNode(placed.componentId ?? '')).toBeDefined()
+})
diff --git a/packages/core/tests/editor/clipboard/fig-transfer-history.test.ts b/packages/core/tests/editor/clipboard/fig-transfer-history.test.ts
new file mode 100644
index 000000000..f7dcce0b5
--- /dev/null
+++ b/packages/core/tests/editor/clipboard/fig-transfer-history.test.ts
@@ -0,0 +1,71 @@
+import { expect, test } from 'bun:test'
+
+import { buildFigmaClipboardHTML } from '@open-pencil/core/clipboard'
+import { createEditor } from '@open-pencil/core/editor'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeFigFragment } from '@open-pencil/fig'
+import { CommittedGraphEventError } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../../helpers/assert'
+import { readFixtureJSON } from '../../helpers/fig/fixtures'
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-binding-ownership-records.json')
+
+for (const failObserver of [false, true]) {
+ for (const replaceSelection of [false, true]) {
+ test(`FIG paste owns nested definitions and variables through history (replace=${replaceSelection}, observer=${failObserver})`, async () => {
+ await initCodec()
+ const fragment = materializeFigFragment(
+ fixture.nodeChanges,
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value))
+ )
+ const root = expectDefined(
+ fragment.graph.getNode(expectDefined(fragment.sources.get('293733:8')))
+ )
+ const html = expectDefined(await buildFigmaClipboardHTML([root], fragment.graph))
+ const editor = createEditor()
+ const target = editor.graph.createNode('RECTANGLE', editor.state.currentPageId, {
+ x: 100,
+ y: 100,
+ width: 40,
+ height: 40
+ })
+ editor.select([target.id])
+ const before = [...editor.graph.nodes.keys()]
+ let unsubscribe: (() => void) | undefined
+ if (failObserver)
+ unsubscribe = editor.graph.onNodeEvents({
+ created: () => {
+ throw new Error('Observer failure')
+ }
+ })
+ const paste = editor.pasteFromHTML(html, undefined, { replaceSelection })
+ if (failObserver) await expect(paste).rejects.toBeInstanceOf(CommittedGraphEventError)
+ else await paste
+ unsubscribe?.()
+ const ids = [...editor.state.selectedIds]
+ expect(ids).toHaveLength(1)
+ const placed = expectDefined(editor.graph.getNode(ids[0]))
+ const nested = editor.graph.getChildren(placed.id)[0]
+ expect(nested.paddingLeft).toBe(6)
+ expect(editor.graph.getNode(placed.componentId ?? '')).toBeDefined()
+ expect(editor.graph.variables.has(nested.boundVariables.paddingLeft)).toBe(true)
+ expect(editor.graph.getNode(target.id) === undefined).toBe(replaceSelection)
+ const position = { x: placed.x, y: placed.y }
+ editor.undo.undo()
+ expect(new Set(editor.graph.nodes.keys())).toEqual(new Set(before))
+ expect(editor.graph.variables.size).toBe(0)
+ expect(editor.graph.variableCollections.size).toBe(0)
+ editor.undo.redo()
+ expect(editor.graph.getNode(placed.id)).toMatchObject(position)
+ expect(editor.graph.getNode(placed.componentId ?? '')).toBeDefined()
+ expect(editor.graph.variables.has(nested.boundVariables.paddingLeft)).toBe(true)
+ if (replaceSelection && !failObserver) {
+ editor.undo.undo()
+ editor.graph.createNodeWithId(placed.id, 'RECTANGLE', editor.state.currentPageId)
+ expect(() => editor.undo.redo()).toThrow('Transfer identity collision')
+ expect(editor.graph.getNode(target.id)).toBeDefined()
+ }
+ })
+ }
+}
diff --git a/packages/core/tests/editor/clipboard/import-nodes/components.test.ts b/packages/core/tests/editor/clipboard/import-nodes/components.test.ts
index aebd84d10..310e67bc4 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/components.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/components.test.ts
@@ -185,12 +185,13 @@ describe('importClipboardNodes: components', () => {
expect(children[0].name).toBe('Path')
expect(children[0].type).toBe('VECTOR')
- // Component should NOT exist as a visible node
- for (const node of graph.getAllNodes()) {
- if (node.type === 'COMPONENT' && node.name === 'Icon') {
- throw new Error('Internal component should not be pasted as visible node')
- }
- }
+ // Retain definitions on hidden dependency pages; never select them as pasted roots.
+ const definition = [...graph.getAllNodes()].find(
+ (node) => node.type === 'COMPONENT' && node.name === 'Icon'
+ )
+ expect(definition).toBeDefined()
+ expect(graph.getNode(definition?.parentId ?? '')?.internalOnly).toBe(true)
+ expect(created).not.toContain(definition?.id)
})
it('detaches orphaned instances to FRAME when component is missing', () => {
@@ -238,7 +239,7 @@ describe('importClipboardNodes: components', () => {
const button = children[0]
expect(button.type).toBe('FRAME')
expect(button.name).toBe('Button')
- expect(button.componentId).toBe('')
+ expect(button.componentId).toBeNull()
expect(button.fills).toHaveLength(1)
expect(button.fills[0].color.b).toBe(1)
expect(button.cornerRadius).toBe(8)
diff --git a/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts b/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts
index 9b257228d..19d750d09 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts
@@ -22,13 +22,27 @@ describe('importClipboardNodes: filtering', () => {
guid: { sessionID: 0, localID: 2 },
parentIndex: { guid: { sessionID: 0, localID: 1 }, position: '!' },
type: 'VARIABLE_SET',
- name: 'Primitives'
+ name: 'Primitives',
+ variableSetModes: [{ id: { sessionID: 0, localID: 4 }, name: 'Default' }]
},
{
guid: { sessionID: 0, localID: 3 },
parentIndex: { guid: { sessionID: 0, localID: 2 }, position: '!' },
type: 'VARIABLE',
- name: 'Colors/Brand/500'
+ name: 'Colors/Brand/500',
+ variableResolvedType: 'COLOR',
+ variableDataValues: {
+ entries: [
+ {
+ modeID: { sessionID: 0, localID: 4 },
+ variableData: {
+ dataType: 'COLOR',
+ resolvedDataType: 'COLOR',
+ value: { colorValue: { r: 0, g: 0, b: 1, a: 1 } }
+ }
+ }
+ ]
+ }
},
{
guid: { sessionID: 0, localID: 10 },
diff --git a/packages/core/tests/editor/clipboard/import-nodes/instance-linkage.test.ts b/packages/core/tests/editor/clipboard/import-nodes/instance-linkage.test.ts
index ee6e09472..21df941fb 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/instance-linkage.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/instance-linkage.test.ts
@@ -13,10 +13,10 @@ describe('importClipboardNodes: instance child linkage', () => {
const page = graph.addPage('Test')
const pageId = page.id
- // Component with one FRAME child, plus an INSTANCE referencing it that carries a
- // SERIALIZED child (as Figma exports instances with their instantiated subtree).
- // The instance child is renamed ('Header v2') — exactly the case the sync-time
- // name+type fallback cannot match, so paste-time linkage is required.
+ // Component with one FRAME child, plus an INSTANCE referencing it whose child is
+ // renamed through a saved name override, the way Figma records it. The reader
+ // expands the child from the component and links it, so the rename cannot defeat
+ // a later sync.
const nodeChanges = [
{ guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT', name: 'Doc' },
{
@@ -48,15 +48,12 @@ describe('importClipboardNodes: instance child linkage', () => {
name: 'Card',
size: { x: 200, y: 60 },
transform: { m00: 1, m01: 0, m02: 300, m10: 0, m11: 1, m12: 0 },
- symbolData: { symbolID: { sessionID: 1, localID: 10 } }
- },
- {
- guid: { sessionID: 2, localID: 21 },
- parentIndex: { guid: { sessionID: 2, localID: 20 }, position: '!' },
- type: 'FRAME',
- name: 'Header v2',
- size: { x: 200, y: 40 },
- transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ symbolData: {
+ symbolID: { sessionID: 1, localID: 10 },
+ symbolOverrides: [
+ { guidPath: { guids: [{ sessionID: 1, localID: 11 }] }, name: 'Header v2' }
+ ]
+ }
}
] as NodeChange[]
@@ -73,8 +70,7 @@ describe('importClipboardNodes: instance child linkage', () => {
expect(instance.componentId).toBe(component.id)
expect(instance.childIds).toHaveLength(1)
- // Paste-time linkage: the serialized instance child is stamped with its component
- // child's id — name-independent (positional + type), so renames do not defeat it.
+ // The expanded child carries the override and its component child's id.
const instChild = getNodeOrThrow(graph, instance.childIds[0])
expect(instChild.name).toBe('Header v2')
expect(instChild.componentId).toBe(compChild.id)
diff --git a/packages/core/tests/editor/clipboard/import-nodes/paste-scope.test.ts b/packages/core/tests/editor/clipboard/import-nodes/paste-scope.test.ts
index 3f5a6b14c..3eddb1067 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/paste-scope.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/paste-scope.test.ts
@@ -115,8 +115,8 @@ describe('importClipboardNodes: paste linkage scoping', () => {
componentId: null
})
- // Paste a component 'Card' (FRAME child 'Header') plus an INSTANCE of it with a
- // serialized renamed child 'Header v2' — the pasted instance MUST be linked.
+ // Paste a component 'Card' (FRAME child 'Header') plus an INSTANCE of it whose child
+ // is renamed through a saved override — the pasted instance MUST be linked.
const nodeChanges = [
{ guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT', name: 'Doc' },
{
@@ -148,22 +148,19 @@ describe('importClipboardNodes: paste linkage scoping', () => {
name: 'Card',
size: { x: 200, y: 60 },
transform: { m00: 1, m01: 0, m02: 300, m10: 0, m11: 1, m12: 0 },
- symbolData: { symbolID: { sessionID: 4, localID: 40 } }
- },
- {
- guid: { sessionID: 4, localID: 43 },
- parentIndex: { guid: { sessionID: 4, localID: 42 }, position: '!' },
- type: 'FRAME',
- name: 'Header v2',
- size: { x: 200, y: 40 },
- transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ symbolData: {
+ symbolID: { sessionID: 4, localID: 40 },
+ symbolOverrides: [
+ { guidPath: { guids: [{ sessionID: 4, localID: 41 }] }, name: 'Header v2' }
+ ]
+ }
}
] as NodeChange[]
const created = importClipboardNodes(nodeChanges, graph, page.id)
expect(created).toHaveLength(2)
- // Pasted instance IS linked (positional + type, name-independent).
+ // Pasted instance IS linked, and the override keeps the child's name.
const pastedInst = getNodeByType(graph, created, 'INSTANCE')
const pastedComp = getNodeByType(graph, created, 'COMPONENT')
if (!pastedInst || !pastedComp) throw new Error('pasted instance/component missing')
diff --git a/packages/core/tests/editor/components/properties.test.ts b/packages/core/tests/editor/components/properties.test.ts
index 98d82aa59..446dd464d 100644
--- a/packages/core/tests/editor/components/properties.test.ts
+++ b/packages/core/tests/editor/components/properties.test.ts
@@ -65,6 +65,10 @@ describe('component property actions', () => {
editor.undo.undo()
const restored = childByName(editor, instance.id, 'Icon A')
expect(restored?.componentId).toBe(iconA.id)
+ editor.undo.redo()
+ expect(childByName(editor, instance.id, 'Icon B')?.componentId).toBe(iconB.id)
+ editor.undo.undo()
+ expect(childByName(editor, instance.id, 'Icon A')?.componentId).toBe(iconA.id)
expect(restored?.childIds.map((id) => editor.graph.getNode(id)?.name)).toEqual(['A shape'])
})
diff --git a/packages/core/tests/editor/components/transitive-sync.test.ts b/packages/core/tests/editor/components/transitive-sync.test.ts
new file mode 100644
index 000000000..040bc9622
--- /dev/null
+++ b/packages/core/tests/editor/components/transitive-sync.test.ts
@@ -0,0 +1,34 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../../helpers/assert'
+
+test('component edits propagate across definition dependencies and undo/redo', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const inner = graph.createNode('COMPONENT', page, { paddingLeft: 4 })
+ const middle = graph.createNode('COMPONENT', page)
+ const innerTemplate = expectDefined(graph.createInstance(inner.id, middle.id))
+ const outer = graph.createNode('COMPONENT', page)
+ const middleTemplate = expectDefined(graph.createInstance(middle.id, outer.id))
+ const placed = expectDefined(graph.createInstance(outer.id, page))
+ const placedMiddle = graph.getChildren(placed.id)[0]
+ const placedInner = graph.getChildren(placedMiddle.id)[0]
+ const editor = createEditor({ graph })
+ editor.updateNodeWithUndo(middle.id, { paddingRight: 9 })
+ editor.updateNodeWithUndo(inner.id, { paddingLeft: 12 })
+ await Promise.resolve()
+ expect(innerTemplate.paddingLeft).toBe(12)
+ expect(graph.getChildren(middleTemplate.id)[0].paddingLeft).toBe(12)
+ expect(placedInner.paddingLeft).toBe(12)
+ expect(placedMiddle.paddingRight).toBe(9)
+ expect(graph.getChildren(placedMiddle.id)).toHaveLength(1)
+ editor.undo.undo()
+ await Promise.resolve()
+ expect(placedInner.paddingLeft).toBe(4)
+ editor.undo.redo()
+ await Promise.resolve()
+ expect(placedInner.paddingLeft).toBe(12)
+})
diff --git a/packages/core/tests/editor/layout/mutation-impact.test.ts b/packages/core/tests/editor/layout/mutation-impact.test.ts
index a88fdd1e8..0f3f379b9 100644
--- a/packages/core/tests/editor/layout/mutation-impact.test.ts
+++ b/packages/core/tests/editor/layout/mutation-impact.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { createLayoutRunner } from '../../../src/editor/layout-runner'
+import { createLayoutRunner } from '#core/layout/mutations'
function pageId(graph: SceneGraph): string {
return graph.getPages()[0].id
diff --git a/packages/core/tests/editor/variables/scaled-bindings.test.ts b/packages/core/tests/editor/variables/scaled-bindings.test.ts
new file mode 100644
index 000000000..6b9c09705
--- /dev/null
+++ b/packages/core/tests/editor/variables/scaled-bindings.test.ts
@@ -0,0 +1,102 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { serializeSceneGraph, deserializeSceneGraph } from '#core/kiwi/fig/parse/transfer'
+
+function setup(importedInstance = false) {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Spacing')
+ const variable = graph.createVariable('Padding', 'FLOAT', collection.id, 10)
+ const alias = graph.createVariable('Alias', 'FLOAT', collection.id, { aliasId: variable.id })
+ const frame = graph.createNode(importedInstance ? 'INSTANCE' : 'FRAME', graph.getPages()[0].id, {
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ paddingLeft: 2.5,
+ boundVariables: { paddingLeft: alias.id },
+ variableBindingScales: { paddingLeft: 0.25 }
+ })
+ if (importedInstance) frame.source.format = 'fig'
+ const child = graph.createNode('RECTANGLE', frame.id, { width: 5, height: 5 })
+ return { graph, collection, variable, alias, frame, child, editor: createEditor({ graph }) }
+}
+
+test('token edits through aliases reflow scaled layout and undo without changing binding units', () => {
+ const { editor, collection, variable, frame, child } = setup()
+ editor.updateVariableValue(variable.id, collection.defaultModeId, 20)
+ expect(frame.paddingLeft).toBe(5)
+ expect(child.x).toBe(5)
+ expect(frame.width).toBe(10)
+ editor.undo.undo()
+ expect(frame.paddingLeft).toBe(2.5)
+ expect(child.x).toBe(2.5)
+ editor.undo.redo()
+ expect(frame.paddingLeft).toBe(5)
+ expect(frame.variableBindingScales).toEqual({ paddingLeft: 0.25 })
+})
+
+test('a binding edit recomputes the saved Hug size of a placed instance root', () => {
+ const { editor, variable, collection, frame, child } = setup(true)
+ editor.updateVariableValue(variable.id, collection.defaultModeId, 20)
+ expect(frame.width).toBe(10)
+ expect(child.x).toBe(5)
+ editor.undo.undo()
+ expect(frame.width).toBe(7.5)
+ expect(child.x).toBe(2.5)
+})
+
+test('active and inherited explicit modes use the same numeric conversion', () => {
+ const { graph, editor, collection, variable, frame, child } = setup()
+ graph.addMode(collection.id, 'alternate', 'Alternate')
+ editor.updateVariableValue(variable.id, 'alternate', 40)
+ expect(frame.paddingLeft).toBe(2.5)
+ editor.setActiveMode(collection.id, 'alternate')
+ expect(frame.paddingLeft).toBe(10)
+ editor.updateNodeWithUndo(graph.getPages()[0].id, {
+ variableModes: { [collection.id]: collection.defaultModeId }
+ })
+ expect(frame.paddingLeft).toBe(2.5)
+ expect(child.x).toBe(2.5)
+ editor.undo.undo()
+ expect(frame.paddingLeft).toBe(10)
+})
+
+test('portable graph transfer retains conversions and accepts older snapshots', () => {
+ const { graph, frame, variable, collection } = setup()
+ graph.updateNode(frame.id, { variableAssignmentScales: { paddingLeft: 0.5 } })
+ const data = structuredClone(serializeSceneGraph(graph))
+ const restored = deserializeSceneGraph(data)
+ createEditor({ graph: restored }).updateVariableValue(variable.id, collection.defaultModeId, 20)
+ expect(restored.getNode(frame.id)?.paddingLeft).toBe(5)
+ expect(graph.getNode(frame.id)?.paddingLeft).toBe(2.5)
+ createEditor({ graph: restored }).bindVariable(frame.id, 'paddingLeft', variable.id)
+ expect(restored.getNode(frame.id)?.paddingLeft).toBe(10)
+ for (const [, node] of data.nodes) {
+ Reflect.deleteProperty(node, 'variableBindingScales')
+ Reflect.deleteProperty(node, 'variableAssignmentScales')
+ }
+ const legacy = deserializeSceneGraph(data)
+ expect(legacy.getNode(frame.id)?.variableBindingScales).toEqual({})
+ expect(legacy.getNode(frame.id)?.variableAssignmentScales).toEqual({})
+})
+
+test('clones isolate conversion metadata and unbinding undo restores it', () => {
+ const { graph, editor, frame, alias, collection, variable } = setup()
+ frame.variableAssignmentScales = { paddingLeft: 0.5 }
+ const clone = graph.cloneTree(frame.id, graph.getPages()[0].id)
+ if (!clone) throw new Error('Missing clone')
+ clone.variableAssignmentScales.paddingLeft = 0.75
+ expect(frame.variableAssignmentScales.paddingLeft).toBe(0.5)
+ clone.variableBindingScales.paddingLeft = 0.5
+ expect(frame.variableBindingScales.paddingLeft).toBe(0.25)
+ editor.unbindVariable(frame.id, 'paddingLeft')
+ expect(frame.variableBindingScales).toEqual({})
+ editor.undo.undo()
+ expect(frame.boundVariables.paddingLeft).toBe(alias.id)
+ expect(frame.variableBindingScales.paddingLeft).toBe(0.25)
+ editor.updateVariableValue(variable.id, collection.defaultModeId, 20)
+ expect(frame.paddingLeft).toBe(5)
+ expect(clone.paddingLeft).toBe(10)
+})
diff --git a/packages/core/tests/figma-api/variables/scaled-bindings.test.ts b/packages/core/tests/figma-api/variables/scaled-bindings.test.ts
new file mode 100644
index 000000000..6cbd9cb62
--- /dev/null
+++ b/packages/core/tests/figma-api/variables/scaled-bindings.test.ts
@@ -0,0 +1,39 @@
+import { expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('Figma API edits reconcile existing scaled bindings without an editor', () => {
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const collection = api.createVariableCollection('Spacing')
+ const first = api.createVariable('First', 'FLOAT', collection.id, 10)
+ const frame = graph.createNode('INSTANCE', graph.getPages()[0].id, {
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ paddingLeft: 2.5,
+ boundVariables: { paddingLeft: first.id },
+ variableBindingScales: { paddingLeft: 0.25 }
+ })
+ frame.source.format = 'fig'
+ const child = graph.createNode('RECTANGLE', frame.id, { width: 5, height: 5 })
+ api.setVariableValue(first.id, collection.defaultModeId, 20)
+ expect(frame.paddingLeft).toBe(5)
+ expect(frame.width).toBe(10)
+ expect(child.x).toBe(5)
+ api.unbindVariable(frame.id, 'paddingLeft')
+ api.setVariableValue(first.id, collection.defaultModeId, 80)
+ expect(frame.paddingLeft).toBe(5)
+})
+
+test('Figma API copies assigned variable values rather than retaining caller aliases', () => {
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const collection = api.createVariableCollection('Colors')
+ const variable = api.createVariable('Color', 'COLOR', collection.id)
+ const value = { r: 1, g: 0, b: 0, a: 1 }
+ api.setVariableValue(variable.id, collection.defaultModeId, value)
+ value.r = 0
+ expect(variable.valuesByMode[collection.defaultModeId]).toEqual({ r: 1, g: 0, b: 0, a: 1 })
+})
diff --git a/packages/core/tests/helpers/fig/absolute-constraints.ts b/packages/core/tests/helpers/fig/absolute-constraints.ts
new file mode 100644
index 000000000..e565ee1b5
--- /dev/null
+++ b/packages/core/tests/helpers/fig/absolute-constraints.ts
@@ -0,0 +1,41 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+export function absoluteConstraintRecords(): NodeChange[] {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ return [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 100, y: 80 },
+ stackMode: 'HORIZONTAL'
+ },
+ {
+ guid: guid(3),
+ type: 'RECTANGLE',
+ parentIndex: { guid: guid(2), position: '!' },
+ size: { x: 10, y: 60 },
+ transform: { m00: 1, m01: 0, m02: 80, m10: 0, m11: 1, m12: 10 },
+ stackPositioning: 'ABSOLUTE',
+ horizontalConstraint: 'MAX',
+ verticalConstraint: 'STRETCH',
+ fillPaints: [
+ {
+ type: 'SOLID',
+ color: { r: 217 / 255, g: 217 / 255, b: 217 / 255, a: 1 },
+ opacity: 1,
+ visible: true
+ }
+ ]
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ size: { x: 200, y: 120 },
+ symbolData: { symbolID: guid(2) }
+ }
+ ]
+}
diff --git a/packages/core/tests/helpers/fig/fixtures.ts b/packages/core/tests/helpers/fig/fixtures.ts
new file mode 100644
index 000000000..d5b9bcbb8
--- /dev/null
+++ b/packages/core/tests/helpers/fig/fixtures.ts
@@ -0,0 +1,117 @@
+import { existsSync, readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+import {
+ parseFigFile,
+ type ParseFigFileOptions,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/core'
+
+import { collectAllNodes } from './traversal'
+
+export const FIXTURES = resolve(import.meta.dir, '../../../../../tests/fixtures')
+
+export const VALID_NODE_TYPES = new Set<string>([
+ 'CANVAS',
+ 'FRAME',
+ 'RECTANGLE',
+ 'ROUNDED_RECTANGLE',
+ 'ELLIPSE',
+ 'TEXT',
+ 'LINE',
+ 'STAR',
+ 'POLYGON',
+ 'VECTOR',
+ 'GROUP',
+ 'SECTION',
+ 'COMPONENT',
+ 'COMPONENT_SET',
+ 'INSTANCE',
+ 'BOOLEAN_OPERATION',
+ 'CONNECTOR',
+ 'SHAPE_WITH_TEXT'
+])
+
+/** Read a shared JSON fixture as data; a module import would escape the package root. */
+export function readFixtureJSON<T>(name: string): T {
+ return JSON.parse(readFileSync(resolve(FIXTURES, name), 'utf8')) as T
+}
+
+export function readFixtureBytes(name: string): Uint8Array {
+ return readFileSync(resolve(FIXTURES, name))
+}
+
+export function uint8ArrayToArrayBuffer(bytes: Uint8Array): ArrayBuffer {
+ const buffer = bytes.buffer
+ if (buffer instanceof ArrayBuffer) {
+ return buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
+ }
+
+ const copy = new Uint8Array(bytes.byteLength)
+ copy.set(bytes)
+ return copy.buffer
+}
+
+export function readFixtureArrayBuffer(name: string): ArrayBuffer {
+ return uint8ArrayToArrayBuffer(readFixtureBytes(name))
+}
+
+export async function parseFixture(
+ name: string,
+ options?: ParseFigFileOptions
+): Promise<SceneGraph> {
+ return parseFigFile(readFixtureArrayBuffer(name), options)
+}
+
+export async function parseGoldPreviewFixture(): Promise<{
+ graph: SceneGraph
+ allNodes: SceneNode[]
+}> {
+ const graph = await parseFixture('gold-preview.fig')
+ return { graph, allNodes: collectAllNodes(graph) }
+}
+
+let sharedGoldPreview: ReturnType<typeof parseGoldPreviewFixture> | null = null
+
+/**
+ * The fully populated `gold-preview.fig` graph, parsed once per process.
+ *
+ * Populating its ~38k instance children costs about 3 s and 700 MB, and a
+ * shard runs every file in one Bun process, so read-only suites share the
+ * result instead of paying that per file. Treat the graph as immutable: a
+ * test that creates, updates, deletes or lays out nodes must call
+ * `parseGoldPreviewFixture()` for its own copy.
+ */
+export function sharedGoldPreviewFixture(): ReturnType<typeof parseGoldPreviewFixture> {
+ sharedGoldPreview ??= parseGoldPreviewFixture()
+ return sharedGoldPreview
+}
+
+const LFS_POINTER_PREFIX = 'version https://git-lfs'
+
+/**
+ * Read a `.fig` fixture by absolute path, or `null` when it is absent OR an
+ * un-fetched Git LFS pointer. `tests/fixtures/*.fig` are LFS-tracked, so on a
+ * shallow/LFS-less checkout `existsSync` passes but the bytes are a tiny ASCII
+ * pointer stub — parsing it would throw. Optional-local tests skip on `null`.
+ * (Contrast `readFixtureBytes`/`parseFixture`, which take a name and assume the
+ * fixture is present.)
+ */
+export function readFigFixture(path: string): ArrayBuffer | null {
+ if (!existsSync(path)) return null
+ const bytes = readFileSync(path)
+ if (
+ bytes.length < 1024 &&
+ bytes.toString('utf8', 0, LFS_POINTER_PREFIX.length) === LFS_POINTER_PREFIX
+ ) {
+ return null
+ }
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
+}
+
+/** Parse a `.fig` fixture by path into a SceneGraph, or `null` when unavailable (see readFigFixture). */
+export async function loadFigFixture(path: string): Promise<SceneGraph | null> {
+ const ab = readFigFixture(path)
+ return ab ? parseFigFile(ab) : null
+}
diff --git a/packages/core/tests/helpers/fig/guid.ts b/packages/core/tests/helpers/fig/guid.ts
new file mode 100644
index 000000000..559f72914
--- /dev/null
+++ b/packages/core/tests/helpers/fig/guid.ts
@@ -0,0 +1,5 @@
+import type { GUID } from '@open-pencil/kiwi/fig/codec'
+
+export function guid(localID: number, sessionID = 1): GUID {
+ return { sessionID, localID }
+}
diff --git a/packages/core/tests/helpers/fig/nested-binding.ts b/packages/core/tests/helpers/fig/nested-binding.ts
new file mode 100644
index 000000000..b25b9ce90
--- /dev/null
+++ b/packages/core/tests/helpers/fig/nested-binding.ts
@@ -0,0 +1,20 @@
+import type { SymbolData } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import { expectDefined } from '../assert'
+import { readFixtureJSON } from './fixtures'
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-binding-ownership-records.json')
+
+/** Remove only the placed owner's declaration, retaining the saved inherited expression. */
+export function inheritedNestedBindingRecords(): NodeChange[] {
+ const changes = structuredClone(fixture.nodeChanges) as NodeChange[]
+ const owner = expectDefined(
+ changes.find((node) => node.guid?.sessionID === 293733 && node.guid.localID === 8),
+ 'captured owner'
+ )
+ for (const override of (owner.symbolData as SymbolData).symbolOverrides ?? []) {
+ Reflect.deleteProperty(override, 'parameterConsumptionMap')
+ }
+ return changes
+}
diff --git a/tests/helpers/fig-traversal.ts b/packages/core/tests/helpers/fig/traversal.ts
similarity index 100%
rename from tests/helpers/fig-traversal.ts
rename to packages/core/tests/helpers/fig/traversal.ts
diff --git a/packages/core/tests/helpers/test-utils.ts b/packages/core/tests/helpers/test-utils.ts
new file mode 100644
index 000000000..5c1e57754
--- /dev/null
+++ b/packages/core/tests/helpers/test-utils.ts
@@ -0,0 +1,14 @@
+import { describe } from 'bun:test'
+
+// Tests that don't run are not useful, but it may be desirable to run only a short subset of tests.
+// Set BUN_HEAVY_TESTS to false to skip tests marked as heavy, and set it to true to run them.
+// By default, all tests are run.
+export const runsHeavyTests = process.env.BUN_HEAVY_TESTS
+ ? ['1', 't', 'true'].includes(process.env.BUN_HEAVY_TESTS.trim().toLowerCase())
+ : true
+
+export const heavy = describe.if(runsHeavyTests)
+
+// Default per-test timeout in CI is often too short for fixture I/O tests that parse/export
+// real .fig files. Use this timeout for tests that are bounded by fixture parsing speed.
+export const HEAVY_TEST_TIMEOUT_MS = 30_000
diff --git a/packages/core/tests/io/formats/fig/export/README.md b/packages/core/tests/io/formats/fig/export/README.md
new file mode 100644
index 000000000..58cc5e2b7
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/README.md
@@ -0,0 +1,17 @@
+# `export-contract.json`
+
+Reduced from Figma's Save local copy canvas payload for a controlled document containing:
+
+- A local Inter Medium text style at 14 px with 20 px line height.
+- A component with a Boolean visibility property bound to its text child.
+- A custom-named instance resized to 240×80 with the label hidden.
+- A second instance scaled to 75%, producing 150×45 bounds.
+
+The fixture retains eight records and eleven referenced glyph blobs (base64 encoded).
+`ids` identifies the source nodes; `expected` records observations from the Figma plugin API.
+Blob indexes were remapped to this fixture's blob table. Font digests are JSON byte arrays,
+not numeric-key objects. Temporary oracle page/style objects were removed after capture.
+
+The capture demonstrates modern typed `varValue` defaults and `PROP_REF` parameter bindings.
+See [the contract tests](./export-contract.test.ts). It is not a complete document compatibility
+fixture and does not prove every export claim in the expected data is currently implemented.
diff --git a/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts b/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts
new file mode 100644
index 000000000..a1f01299c
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts
@@ -0,0 +1,139 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { cloneInstanceOverrideState } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../../../../../helpers/assert'
+import { inheritedNestedBindingRecords } from '../../../../../helpers/fig/nested-binding'
+import { readFixtureJSON } from '../../../../../helpers/fig/fixtures'
+
+const oracle = readFixtureJSON<Record<string, unknown>[]>('nested-binding-authoring.json')
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-binding-ownership-records.json')
+
+function document(inherited = false) {
+ const changes = inherited
+ ? inheritedNestedBindingRecords()
+ : (structuredClone(fixture.nodeChanges) as NodeChange[])
+ const result = materializeDocument(
+ changes,
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
+ { derivedBounds: true }
+ )
+ const root = expectDefined(
+ result.graph.getNode(expectDefined(result.sources.get('293733:8'), 'source')),
+ 'root'
+ )
+ const nested = expectDefined(result.graph.getChildren(root.id)[0], 'nested')
+ return { ...result, root, nested }
+}
+
+for (const caller of ['editor', 'api'] as const) {
+ test(`${caller} authors new root and nested aliases in occurrence-owner units`, async () => {
+ const { graph, root, nested } = document()
+ const writer = caller === 'editor' ? createEditor({ graph }) : new FigmaAPI(graph)
+ writer.bindVariable(nested.id, 'paddingRight', '293742:7')
+ writer.bindVariable(root.id, 'paddingRight', '293742:7')
+ expect(nested.paddingRight).toBe(6)
+ expect(root.paddingRight).toBe(6)
+ expect(nested.width).toBe(17)
+ expect(root.width).toBe(33)
+ graph.updateNode(root.id, { name: 'Authored binding' })
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const reopened = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ derivedBounds: true
+ }).graph
+ const restored = expectDefined(
+ reopened.getAllNodes().find((node) => node.name === 'Authored binding'),
+ 'reopened root'
+ )
+ const child = expectDefined(reopened.getChildren(restored.id)[0], 'reopened child')
+ expect(restored.paddingRight).toBe(6)
+ expect(child.paddingRight).toBe(6)
+ expect(child.boundVariables.paddingRight).toBeDefined()
+ expect(child.variableBindingScales.paddingRight).toBe(0.5)
+ })
+}
+
+test('component edits preserve authored aliases and subsequent declaration units', async () => {
+ const { graph, sources, root, nested } = document()
+ const editor = createEditor({ graph })
+ editor.bindVariable(nested.id, 'paddingRight', '293742:7')
+ const component = expectDefined(sources.get('1:2'), 'component')
+ editor.updateNodeWithUndo(component, { paddingTop: oracle.componentEdit.sourcePaddingTop })
+ await Promise.resolve()
+ expect(nested.paddingTop).toBe(oracle.componentEdit.paddingTop)
+ expect(nested.height).toBe(oracle.componentEdit.height)
+ expect(nested.componentScale).toBe(0.25)
+ expect(nested.boundVariables.paddingRight).toBe('293742:7')
+ expect(nested.paddingRight).toBe(6)
+ expect(root.variableAssignmentScales.paddingRight).toBe(0.5)
+ editor.bindVariable(nested.id, 'itemSpacing', '293742:7')
+ expect(nested.itemSpacing).toBe(6)
+ editor.undo.undo()
+ editor.undo.undo()
+ await Promise.resolve()
+ expect(nested.paddingTop).toBe(1)
+ expect(nested.paddingRight).toBe(6)
+ editor.undo.redo()
+ await Promise.resolve()
+ expect(nested.paddingTop).toBe(2)
+})
+
+test('saved inherited multiplication stays live through token edits and edited export', async () => {
+ const { graph, root, nested } = document(true)
+ const editor = createEditor({ graph })
+ const variable = expectDefined(graph.variables.get('293733:7'), 'inherited variable')
+ const mode = graph.getNodeVariableModeId(nested.id, variable.collectionId)
+ expect(nested.paddingLeft).toBe(5)
+ editor.updateVariableValue(variable.id, mode, 40)
+ expect(nested.paddingLeft).toBe(10)
+ editor.undo.undo()
+ expect(nested.paddingLeft).toBe(5)
+ editor.undo.redo()
+ expect(nested.paddingLeft).toBe(10)
+ graph.updateNode(root.id, { name: 'Expression round-trip' })
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const reopened = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ derivedBounds: true
+ }).graph
+ const restored = expectDefined(
+ reopened.getAllNodes().find((node) => node.name === 'Expression round-trip'),
+ 'root'
+ )
+ const child = expectDefined(reopened.getChildren(restored.id)[0], 'nested')
+ expect(child.paddingLeft).toBe(10)
+ expect(child.variableBindingScales.paddingLeft).toBe(0.25)
+ expect(child.boundVariables.paddingLeft).toBeDefined()
+})
+
+test('rebinding the same inherited alias declares new units; undo restores inherited units and claims', () => {
+ const { graph, root, nested } = document(true)
+ const editor = createEditor({ graph })
+ const previous = cloneInstanceOverrideState(root.instanceOverrides)
+ expect(nested.paddingLeft).toBe(5)
+ expect(nested.variableBindingScales.paddingLeft).toBe(0.25)
+ editor.bindVariable(nested.id, 'paddingLeft', '293733:7')
+ expect(nested.paddingLeft).toBe(10)
+ expect(nested.variableBindingScales.paddingLeft).toBe(0.5)
+ editor.undo.undo()
+ expect(nested.variableBindingScales.paddingLeft).toBe(0.25)
+ expect(nested.paddingLeft).toBe(5)
+ expect(nested.variableBindingScales.paddingLeft).toBe(0.25)
+ expect(root.instanceOverrides).toEqual(previous)
+ editor.undo.redo()
+ expect(nested.paddingLeft).toBe(10)
+ editor.unbindVariable(nested.id, 'paddingLeft')
+ editor.undo.undo()
+ expect(nested.variableBindingScales.paddingLeft).toBe(0.5)
+ expect(nested.paddingLeft).toBe(10)
+})
diff --git a/packages/core/tests/io/formats/fig/export/binding/import.test.ts b/packages/core/tests/io/formats/fig/export/binding/import.test.ts
new file mode 100644
index 000000000..42184c6da
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/binding/import.test.ts
@@ -0,0 +1,88 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { readFixtureJSON } from '../../../../../helpers/fig/fixtures'
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-binding-ownership-records.json')
+
+
+test('binding patches keep unrelated inherited fields in their original units', () => {
+ const changes = structuredClone(fixture.nodeChanges) as NodeChange[]
+ const inner = changes.find((node) => node.guid?.sessionID === 1 && node.guid.localID === 2)
+ if (!inner) throw new Error('Missing component')
+ inner.variableConsumptionMap = {
+ entries: [
+ {
+ variableField: 'STACK_SPACING',
+ variableData: {
+ dataType: 'ALIAS',
+ value: { alias: { guid: { sessionID: 293742, localID: 7 } } }
+ }
+ }
+ ]
+ }
+ const { graph, sources } = materializeDocument(
+ changes,
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
+ { derivedBounds: true }
+ )
+ const rootId = sources.get('293733:8')
+ if (!rootId) throw new Error('Missing owner')
+ const nested = graph.getChildren(rootId)[0]
+ expect(nested.boundVariables.itemSpacing).toBe(nested.boundVariables.paddingLeft)
+ expect(nested.itemSpacing).toBe(3)
+ expect(nested.paddingLeft).toBe(6)
+ expect(nested.variableBindingScales).toMatchObject({ itemSpacing: 0.25, paddingLeft: 0.5 })
+})
+
+test('a direct nested binding retains its alias and declaring-owner units', async () => {
+ const { graph, sources } = materializeDocument(
+ fixture.nodeChanges as NodeChange[],
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
+ { derivedBounds: true }
+ )
+ const rootId = sources.get('293733:8')
+ const sourceId = sources.get('1:4')
+ if (!rootId || !sourceId) throw new Error('Missing captured sources')
+ const children = graph.getChildren(rootId)
+ expect(children).toHaveLength(1)
+ const nested = children[0]
+ expect(nested.boundVariables.paddingLeft).toBe('293742:7')
+ expect(nested.variableBindingScales.paddingLeft).toBe(0.5)
+ expect(nested.paddingLeft).toBe(6)
+ expect(nested.width).toBe(13.5)
+ const canonicalChildren = graph.getChildren(sourceId)
+ expect(canonicalChildren).toHaveLength(1)
+ const inherited = canonicalChildren[0]
+ expect(inherited?.paddingLeft).toBe(10)
+ const variable = graph.variables.get('293742:7')
+ if (!variable) throw new Error('Missing explicit binding')
+ const mode = graph.getNodeVariableModeId(nested.id, variable.collectionId)
+ const editor = createEditor({ graph })
+ editor.updateVariableValue(variable.id, mode, 16)
+ expect(nested.paddingLeft).toBe(8)
+ expect(nested.width).toBe(15.5)
+ expect(graph.getNode(rootId)?.width).toBe(35.5)
+ expect(inherited?.paddingLeft).toBe(10)
+ editor.undo.undo()
+ expect(nested.paddingLeft).toBe(6)
+ editor.updateNodeWithUndo(rootId, { name: 'Direct binding round-trip target' })
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const { graph: reopened } = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ derivedBounds: true
+ })
+ const roots = [...reopened.getAllNodes()].filter(
+ (node) => node.name === 'Direct binding round-trip target'
+ )
+ expect(roots).toHaveLength(1)
+ const restored = reopened.getChildren(roots[0].id)[0]
+ expect(restored.paddingLeft).toBe(6)
+ expect(restored.boundVariables.paddingLeft).toBeDefined()
+ expect(restored.variableBindingScales.paddingLeft).toBe(0.5)
+})
diff --git a/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts b/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts
new file mode 100644
index 000000000..134e0b7f8
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts
@@ -0,0 +1,155 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+
+import { expectDefined } from '../../../../helpers/assert'
+import { inheritedNestedBindingRecords } from '../../../../helpers/fig/nested-binding'
+import { readFixtureJSON } from '../../../../helpers/fig/fixtures'
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-binding-ownership-records.json')
+
+test('a placed binding does not freeze an unrelated inherited binding', async () => {
+ const { graph, sources } = materializeDocument(
+ inheritedNestedBindingRecords(),
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
+ { derivedBounds: true }
+ )
+ const root = expectDefined(sources.get('293733:8'))
+ const template = graph.getChildren(expectDefined(sources.get('1:4')))[0]
+ const nested = graph.getChildren(root)[0]
+ const api = new FigmaAPI(graph)
+ createEditor({ graph })
+ api.bindVariable(nested.id, 'paddingLeft', '293742:7')
+ api.bindVariable(template.id, 'paddingRight', '293733:7')
+ await Promise.resolve()
+ expect(nested.boundVariables.paddingLeft).toBe('293742:7')
+ expect(nested.boundVariables.paddingRight).toBe('293733:7')
+ expect(nested.variableBindingScales.paddingRight).toBe(0.25)
+ expect(nested.paddingRight).toBe(5)
+ api.unbindVariable(nested.id, 'paddingRight')
+ api.bindVariable(template.id, 'paddingTop', '293733:7')
+ await Promise.resolve()
+ expect(nested.boundVariables.paddingRight).toBeUndefined()
+ expect(nested.boundVariables.paddingTop).toBe('293733:7')
+ expect(nested.boundVariables.paddingLeft).toBe('293742:7')
+})
+
+test('definition rescale preserves an explicit placed binding in its declaring units', async () => {
+ const { graph, sources } = materializeDocument(
+ inheritedNestedBindingRecords(),
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
+ { derivedBounds: true }
+ )
+ const root = expectDefined(graph.getNode(expectDefined(sources.get('293733:8'))))
+ const template = graph.getChildren(expectDefined(sources.get('1:4')))[0]
+ const nested = graph.getChildren(root.id)[0]
+ const api = new FigmaAPI(graph)
+ createEditor({ graph })
+ api.getNodeById(root.id).rescale(0.5)
+ api.getNodeById(template.id).rescale(2)
+ await Promise.resolve()
+ api.bindVariable(nested.id, 'paddingLeft', '293742:7')
+ expect([root.width, nested.width, nested.paddingLeft]).toEqual([20.5, 10.5, 3])
+ api.getNodeById(template.id).rescale(2)
+ await Promise.resolve()
+ expect([
+ root.width,
+ root.height,
+ nested.width,
+ nested.height,
+ nested.paddingLeft,
+ nested.paddingRight
+ ]).toEqual([28, 14, 18, 14, 3, 5])
+ expect(nested.variableBindingScales.paddingLeft).toBe(0.25)
+ const variable = expectDefined(graph.variables.get('293742:7'))
+ const mode = graph.getNodeVariableModeId(nested.id, variable.collectionId)
+ api.setVariableValue(variable.id, mode, 16)
+ expect([root.width, nested.width, nested.paddingLeft]).toEqual([29, 19, 4])
+ api.setVariableValue(variable.id, mode, 12)
+ graph.updateNode(root.id, { name: 'Protected rescale acceptance' })
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const reopened = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ derivedBounds: true
+ }).graph
+ const restored = expectDefined(
+ reopened.getAllNodes().find((node) => node.name === 'Protected rescale acceptance')
+ )
+ const child = reopened.getChildren(restored.id)[0]
+ expect([
+ restored.width,
+ restored.height,
+ child.width,
+ child.height,
+ child.paddingLeft,
+ child.paddingRight
+ ]).toEqual([28, 14, 18, 14, 3, 5])
+})
+
+test('definition rescale propagates occurrence units through editor sync and export', async () => {
+ const { graph, sources } = materializeDocument(
+ inheritedNestedBindingRecords(),
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
+ { derivedBounds: true }
+ )
+ const root = expectDefined(graph.getNode(expectDefined(sources.get('293733:8'))))
+ const outer = expectDefined(graph.getNode(expectDefined(sources.get('1:4'))))
+ const template = graph.getChildren(outer.id)[0]
+ const nested = graph.getChildren(root.id)[0]
+ const api = new FigmaAPI(graph)
+ createEditor({ graph })
+ api.getNodeById(root.id).rescale(0.5)
+ await Promise.resolve()
+ api.getNodeById(template.id).rescale(2)
+ await Promise.resolve()
+ expect([
+ root.width,
+ root.height,
+ nested.width,
+ nested.height,
+ nested.paddingLeft,
+ nested.paddingRight
+ ]).toEqual([22.5, 7, 12.5, 7, 5, 2.5])
+ expect(nested.variableBindingScales.paddingLeft).toBe(0.25)
+ api.setVariableValue(
+ '293733:7',
+ graph.getNodeVariableModeId(
+ nested.id,
+ expectDefined(graph.variables.get('293733:7')).collectionId
+ ),
+ 40
+ )
+ expect([root.width, nested.width, nested.paddingLeft]).toEqual([27.5, 17.5, 10])
+ api.setVariableValue(
+ '293733:7',
+ graph.getNodeVariableModeId(
+ nested.id,
+ expectDefined(graph.variables.get('293733:7')).collectionId
+ ),
+ 20
+ )
+ graph.updateNode(root.id, { name: 'Definition rescale acceptance' })
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const reopened = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ derivedBounds: true
+ }).graph
+ const restored = expectDefined(
+ reopened.getAllNodes().find((node) => node.name === 'Definition rescale acceptance')
+ )
+ const child = reopened.getChildren(restored.id)[0]
+ expect([
+ restored.width,
+ restored.height,
+ child.width,
+ child.height,
+ child.paddingLeft,
+ child.paddingRight
+ ]).toEqual([22.5, 7, 12.5, 7, 5, 2.5])
+})
diff --git a/packages/core/tests/io/formats/fig/export/export-contract.json b/packages/core/tests/io/formats/fig/export/export-contract.json
new file mode 100644
index 000000000..54b94146d
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/export-contract.json
@@ -0,0 +1,1018 @@
+{
+ "expected": {
+ "name": "Custom card",
+ "width": 240,
+ "height": 80,
+ "visible": false,
+ "scaledWidth": 150,
+ "scaledHeight": 45
+ },
+ "ids": {
+ "page": "292486:1721",
+ "component": "292486:1723",
+ "text": "292486:1724",
+ "instance": "292486:1725",
+ "scaled": "292486:1727"
+ },
+ "records": [
+ {
+ "guid": {
+ "sessionID": 0,
+ "localID": 0
+ },
+ "phase": "CREATED",
+ "type": "DOCUMENT",
+ "name": "Document",
+ "visible": true,
+ "opacity": 1,
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "CENTER",
+ "strokeJoin": "MITER",
+ "pluginData": [],
+ "documentColorProfile": "DISPLAY_P3"
+ },
+ {
+ "guid": {
+ "sessionID": 0,
+ "localID": 3513
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 0,
+ "localID": 0
+ },
+ "position": "#"
+ },
+ "type": "CANVAS",
+ "name": "Internal Only Canvas",
+ "visible": true,
+ "opacity": 1,
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "CENTER",
+ "strokeJoin": "MITER",
+ "internalOnly": true
+ },
+ {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1721
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 0,
+ "localID": 0
+ },
+ "position": "~!"
+ },
+ "type": "CANVAS",
+ "name": "Export contract oracle",
+ "visible": true,
+ "opacity": 1,
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "backgroundOpacity": 1,
+ "backgroundColor": {
+ "r": 0.11764705926179886,
+ "g": 0.11764705926179886,
+ "b": 0.11764705926179886,
+ "a": 1
+ },
+ "isPageDivider": false,
+ "backgroundEnabled": true
+ },
+ {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1722
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 0,
+ "localID": 3513
+ },
+ "position": "~m"
+ },
+ "type": "TEXT",
+ "name": "Oracle/Medium14",
+ "isPublishable": true,
+ "styleType": "TEXT",
+ "version": "292486:5",
+ "sortPosition": "\"",
+ "fontSize": 14,
+ "textAlignVertical": "TOP",
+ "lineHeight": {
+ "value": 20,
+ "units": "PIXELS"
+ },
+ "fontName": {
+ "family": "Inter",
+ "style": "Medium",
+ "postscript": ""
+ },
+ "textData": {
+ "characters": "Ag",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ },
+ "derivedTextData": {
+ "layoutSize": {
+ "x": 19,
+ "y": 20
+ },
+ "baselines": [
+ {
+ "position": {
+ "x": 0,
+ "y": 15.090909004211426
+ },
+ "width": 18.3203125,
+ "lineY": -8.669766771163268e-8,
+ "lineHeight": 20,
+ "lineAscent": 13,
+ "firstCharacter": 0,
+ "endCharacter": 2
+ }
+ ],
+ "glyphs": [
+ {
+ "commandsBlob": 0,
+ "position": {
+ "x": 0,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 0,
+ "advance": 0.6999289989471436,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 1,
+ "position": {
+ "x": 9.6796875,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 1,
+ "advance": 0.6171875,
+ "rotation": 0
+ }
+ ],
+ "fontMetaData": [
+ {
+ "key": {
+ "family": "Inter",
+ "style": "Medium",
+ "postscript": ""
+ },
+ "fontLineHeight": 1.2102272510528564,
+ "fontDigest": [
+ 212, 131, 226, 199, 248, 3, 44, 102, 56, 208, 71, 22, 126, 251, 235, 160, 3, 15, 6, 73
+ ],
+ "fontStyle": "NORMAL",
+ "fontWeight": 500
+ }
+ ],
+ "truncationStartIndex": -1,
+ "truncatedHeight": -1,
+ "logicalIndexToCharacterOffsetMap": [0, 9.6796875],
+ "derivedLines": [
+ {
+ "directionality": "LTR"
+ }
+ ]
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "textUserLayoutVersion": 5,
+ "textExplicitLayoutVersion": 1,
+ "fontVariations": [],
+ "textBidiVersion": 1,
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 19,
+ "y": 20
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 0,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0,
+ "g": 0,
+ "b": 0,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 0,
+ "c1": 0,
+ "c2": 0,
+ "c3": 1
+ }
+ }
+ ],
+ "textDecorationSkipInk": true,
+ "autoRename": false,
+ "textTracking": 0,
+ "textAutoResize": "WIDTH_AND_HEIGHT"
+ },
+ {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1723
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1721
+ },
+ "position": "!"
+ },
+ "type": "SYMBOL",
+ "name": "Oracle Card",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "292486:7",
+ "componentPropDefs": [
+ {
+ "id": {
+ "sessionID": 292486,
+ "localID": 0
+ },
+ "name": "Show label",
+ "sortPosition": "\"",
+ "type": "BOOL",
+ "preferredValues": {},
+ "varValue": {
+ "value": {
+ "boolValue": true
+ },
+ "dataType": "BOOLEAN",
+ "resolvedDataType": "BOOLEAN"
+ }
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 200,
+ "y": 60
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "frameMaskDisabled": true
+ },
+ {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1724
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1723
+ },
+ "position": "!"
+ },
+ "type": "TEXT",
+ "name": "Styled label",
+ "styleIdForText": {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1722
+ }
+ },
+ "fontSize": 12,
+ "textAlignVertical": "TOP",
+ "lineHeight": {
+ "value": 100,
+ "units": "PERCENT"
+ },
+ "fontName": {
+ "family": "Inter",
+ "style": "Regular",
+ "postscript": ""
+ },
+ "textData": {
+ "characters": "Styled label",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ },
+ "derivedTextData": {
+ "layoutSize": {
+ "x": 79,
+ "y": 20
+ },
+ "baselines": [
+ {
+ "position": {
+ "x": 0,
+ "y": 15.090909004211426
+ },
+ "width": 78.244140625,
+ "lineY": -8.669766771163268e-8,
+ "lineHeight": 20,
+ "lineAscent": 13,
+ "firstCharacter": 0,
+ "endCharacter": 12
+ }
+ ],
+ "glyphs": [
+ {
+ "commandsBlob": 2,
+ "position": {
+ "x": 0,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 0,
+ "advance": 0.6434659361839294,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 3,
+ "position": {
+ "x": 9.009765625,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 1,
+ "advance": 0.37180399894714355,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 4,
+ "position": {
+ "x": 14.21875,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 2,
+ "advance": 0.56640625,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 5,
+ "position": {
+ "x": 22.1484375,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 3,
+ "advance": 0.24893467128276825,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 6,
+ "position": {
+ "x": 25.634765625,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 4,
+ "advance": 0.5873579978942871,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 7,
+ "position": {
+ "x": 33.8515625,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 5,
+ "advance": 0.6257102489471436,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 8,
+ "position": {
+ "x": 42.615234375,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 6,
+ "advance": 0.26491478085517883,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 5,
+ "position": {
+ "x": 46.3203125,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 7,
+ "advance": 0.24893467128276825,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 9,
+ "position": {
+ "x": 49.806640625,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 8,
+ "advance": 0.5692471861839294,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 10,
+ "position": {
+ "x": 57.77734375,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 9,
+ "advance": 0.6257102489471436,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 6,
+ "position": {
+ "x": 66.541015625,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 10,
+ "advance": 0.5873579978942871,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 5,
+ "position": {
+ "x": 74.7578125,
+ "y": 15.090909004211426
+ },
+ "fontSize": 14,
+ "firstCharacter": 11,
+ "advance": 0.24893467128276825,
+ "rotation": 0
+ }
+ ],
+ "fontMetaData": [
+ {
+ "key": {
+ "family": "Inter",
+ "style": "Medium",
+ "postscript": ""
+ },
+ "fontLineHeight": 1.2102272510528564,
+ "fontDigest": [
+ 212, 131, 226, 199, 248, 3, 44, 102, 56, 208, 71, 22, 126, 251, 235, 160, 3, 15, 6, 73
+ ],
+ "fontStyle": "NORMAL",
+ "fontWeight": 500
+ }
+ ],
+ "truncationStartIndex": -1,
+ "truncatedHeight": -1,
+ "logicalIndexToCharacterOffsetMap": [
+ 0, 9.009765625, 14.21875, 22.1484375, 25.634765625, 33.8515625, 42.615234375, 46.3203125,
+ 49.806640625, 57.77734375, 66.541015625, 74.7578125
+ ],
+ "derivedLines": [
+ {
+ "directionality": "LTR"
+ }
+ ]
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "textUserLayoutVersion": 5,
+ "textExplicitLayoutVersion": 1,
+ "fontVariations": [],
+ "textBidiVersion": 1,
+ "emojiImageSet": "APPLE",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 79,
+ "y": 20
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "OUTSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0,
+ "g": 0,
+ "b": 0,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 0,
+ "c1": 0,
+ "c2": 0,
+ "c3": 1
+ }
+ }
+ ],
+ "textDecorationSkipInk": true,
+ "autoRename": true,
+ "textTracking": 0,
+ "textAutoResize": "WIDTH_AND_HEIGHT",
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "propRefValue": {
+ "defId": {
+ "sessionID": 292486,
+ "localID": 0
+ }
+ }
+ },
+ "dataType": "PROP_REF",
+ "resolvedDataType": "BOOLEAN"
+ },
+ "variableField": "VISIBLE"
+ }
+ ]
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1725
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1721
+ },
+ "position": "\""
+ },
+ "type": "INSTANCE",
+ "name": "Custom card",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 292486,
+ "localID": 1723
+ },
+ "symbolOverrides": [
+ {
+ "name": "Custom card",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 292486,
+ "localID": 1723
+ }
+ ]
+ },
+ "size": {
+ "x": 240,
+ "y": 80
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ },
+ "derivedSymbolData": [],
+ "componentPropAssignments": [
+ {
+ "defID": {
+ "sessionID": 292486,
+ "localID": 0
+ },
+ "varValue": {
+ "value": {
+ "boolValue": false
+ },
+ "dataType": "BOOLEAN",
+ "resolvedDataType": "BOOLEAN"
+ }
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 240,
+ "y": 80
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 250,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 3
+ },
+ {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1727
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 292486,
+ "localID": 1721
+ },
+ "position": "#"
+ },
+ "type": "INSTANCE",
+ "name": "Oracle Card",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 292486,
+ "localID": 1723
+ },
+ "symbolOverrides": [],
+ "uniformScaleFactor": 0.75
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 292486,
+ "localID": 1724
+ }
+ ]
+ },
+ "derivedTextData": {
+ "layoutSize": {
+ "x": 59,
+ "y": 15
+ },
+ "baselines": [
+ {
+ "position": {
+ "x": 0,
+ "y": 11.318181991577148
+ },
+ "width": 58.68310546875,
+ "lineY": 1.7339533542326535e-7,
+ "lineHeight": 15,
+ "lineAscent": 10,
+ "firstCharacter": 0,
+ "endCharacter": 12
+ }
+ ],
+ "glyphs": [
+ {
+ "commandsBlob": 2,
+ "position": {
+ "x": 0,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 0,
+ "advance": 0.6434659361839294,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 3,
+ "position": {
+ "x": 6.75732421875,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 1,
+ "advance": 0.37180399894714355,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 4,
+ "position": {
+ "x": 10.6640625,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 2,
+ "advance": 0.56640625,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 5,
+ "position": {
+ "x": 16.611328125,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 3,
+ "advance": 0.24893467128276825,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 6,
+ "position": {
+ "x": 19.22607421875,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 4,
+ "advance": 0.5873579978942871,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 7,
+ "position": {
+ "x": 25.388671875,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 5,
+ "advance": 0.6257102489471436,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 8,
+ "position": {
+ "x": 31.96142578125,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 6,
+ "advance": 0.26491478085517883,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 5,
+ "position": {
+ "x": 34.740234375,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 7,
+ "advance": 0.24893467128276825,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 9,
+ "position": {
+ "x": 37.35498046875,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 8,
+ "advance": 0.5692471861839294,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 10,
+ "position": {
+ "x": 43.3330078125,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 9,
+ "advance": 0.6257102489471436,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 6,
+ "position": {
+ "x": 49.90576171875,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 10,
+ "advance": 0.5873579978942871,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 5,
+ "position": {
+ "x": 56.068359375,
+ "y": 11.318181991577148
+ },
+ "fontSize": 10.5,
+ "firstCharacter": 11,
+ "advance": 0.24893467128276825,
+ "rotation": 0
+ }
+ ],
+ "fontMetaData": [
+ {
+ "key": {
+ "family": "Inter",
+ "style": "Medium",
+ "postscript": ""
+ },
+ "fontLineHeight": 1.2102272510528564,
+ "fontDigest": [
+ 212, 131, 226, 199, 248, 3, 44, 102, 56, 208, 71, 22, 126, 251, 235, 160, 3, 15,
+ 6, 73
+ ],
+ "fontStyle": "NORMAL",
+ "fontWeight": 500
+ }
+ ],
+ "truncationStartIndex": -1,
+ "truncatedHeight": -1,
+ "logicalIndexToCharacterOffsetMap": [
+ 0, 6.75732421875, 10.6640625, 16.611328125, 19.22607421875, 25.388671875,
+ 31.96142578125, 34.740234375, 37.35498046875, 43.3330078125, 49.90576171875,
+ 56.068359375
+ ],
+ "derivedLines": [
+ {
+ "directionality": "LTR"
+ }
+ ]
+ },
+ "size": {
+ "x": 59,
+ "y": 15
+ }
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 150,
+ "y": 45
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 150
+ },
+ "strokeWeight": 0.75,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 3
+ }
+ ],
+ "blobs": [
+ "AAEvuhA+AAAAAALposs8AAAAAAIvupI+jC46PwLpotM+jC46PwJ10Sw/AAAAAAIAAA8/AAAAAAIvurQ+GF0YPwJ10bE+GF0YPwIvuhA+AAAAAAABL7okPnXRkT4CuugJP3XRkT4CuugJP0YXRT4CL7okPkYXRT4CL7okPnXRkT4A",
+ "AAHpopk+RhddvgMvunA+Rhddvi+6QD7poku+A0YXET6MLjq+ddHlPV10Hb4DXXSpPS+6AL7poos9Rhe9vQLSRSM+AABgvQNGFy0+AACQvV10PT7porO9A4wuTj4AANi9o4tqPl508b0D6aKDPl10Bb6MLpo+XXQFvgNGF7k+XXQFvtJFzT6ji869A1504T666JK9XnThPgAAALwCXnThPumiyz0CAADePumiyz0DRhfZPgAAqD110c8+L7p4PQMvusY+XXQhPS+6tj676MI8Ay+6pj510QU8RheNPnXRBTwDAABYPnXRBTy66CI+RhcdPQMYXdw9RheNPaOLnj3SRQM+A7voQj0YXUA+u+hCPS+6jD4Du+hCPdJFuT510Z09RhfZPgO76No9u+j4PqOLIj666AQ/A+miVz5ddA0/XXSNPl10DT8DXXSnPl10DT9ddLc+RhcJPwNddMc+ddEEPxhd0D6MLv4+A1502T4vuvI+GF3ePgAA6j4CGF3iPgAA6j4CGF3iPumiCz8CddELP+miCz8CddELP3XRRbwDddELPy+6qL1ddAM/o4sCvgOMLvY+L7owvumi2T676Ea+A9JFvT5GF12+6aKZPkYXXb4AAUYXmT5GF8U9A6OLsD5GF8U9L7rAPi+68D0DRhfRPqOLDj5edNk+6aI3PgMAAOI+RhdhPgAA4j5ddI0+AwAA4j7poqk+6aLZPkYXvz4D0kXRPqOL1D5GF8E+o4vgPgO76LA+L7rsPkYXmT4vuuw+A6OLgD4vuuw+GF1gPgAA4D4D6aI/Pl500z676C4+ddG9PgOjix4+jC6oPqOLHj5ddI0+A6OLHj4AAGQ+0kUvPqOLOj4DAABAPkYXET4vumA+6aLzPQO66IA+RhfFPUYXmT5GF8U9AA==",
+ "AAEAAPQ+0kUJPwNGF/E+jC4WPwAA3D7SRR0/A7voxj5ddCQ/u+imPl10JD8DAACQPl10JD+ji34+ddEgPwNGF10+0kUdP6OLSj4AABc/AxhdOD510RA/GF04PrroCD8DGF04PtJFAj8vukQ+u+j6PgNedFE+0kXxPnXRZT4vuuo+A6OLej4YXeQ+RheJPgAA4D4DuuiUPnXR2z510Z8+RhfZPgKMLsQ+6aLPPgMAANY+0kXLPi+66D510cM+A150+z4YXbw+L7oFP4wusD4DL7oNPwAApD7pohI/AACSPgPpohc/AACAPumiFz910U0+A+miFz+jiw4+XXQPP7vouj0DGF0HP110MT110e8+AACAPANGF9E+ddFFvF10pT510UW8A9JFdz510UW8jC46PrvoYjwDjC76PbroIj1GF7U9u+iyPQMAAGA9o4sKPl50UT110U0+AkYXJT510U0+AxhdKD5ddCU+0kU/PqOLCj4Do4tWPgAA4D2ji3o+ddHFPQNddI8+GF2sPUYXpT4YXaw9A7vovD4YXaw9XXTPPowuyj0DjC7iPi+66D276Ow+0kUPPgPpovc+o4sqPumi9z676E4+A+mi9z4AAHA+jC7uPqOLgj4Du+jkPkYXjT676NQ+AACUPgNGF8U+uuiaPkYXsT6MLqA+AkYXhT6MLqw+Ay+6MD4YXbg+L7r4PQAA0D4DL7qQPemi5z4vupA90kUHPwMvupA9GF0XP6OL1j0YXSM/A4wuDj4YXS8/ddFJPgAANj8DL7qCPi+6PD+MLqg+L7o8PwMAAM4+L7o8P7vo6j5GFzY/AwAABD9ddC8/GF0MP3XRIz8DL7oUP9JFGD9GFxU/0kUJPwIAAPQ+0kUJPwA=",
+ "AAG76KY+6aILPwK76KY+6aLrPgJ10eU86aLrPgJ10eU86aILPwK76KY+6aILPwABRhfdPUYXLT8C0kVbPkYXLT8C0kVbPgAAJD4D0kVbPhhdBD4vumQ+L7roPQOMLm4+XXTJPUYXfT510b09A4wuhj676LI9RhePPrvosj0D6aKVPrvosj2ji5o+o4u2PQNddJ8+jC66PYwuoj4YXbw9AgAArD7poos7A9JFpz6MLjo6o4uePowuOrsDddGVPkYX3bsvuog+L7rouwOji2Y+AAAAvF10QT4AAAA8AxhdHD4AAMA8XXQFPnXRZT0DRhfdPXXRtT1GF909XXQNPgJGF909RhctPwA=",
+ "AAF10Q0+XnRRvgO76Oo9XnRRvrvowj1ddE2+A7romj110Um+0kWHPV10Rb4C6aK7PS+62L0D0kX3PS+66L266BI+o4vmvQOMLio+GF3kvQAAPD7posO9A4wuTj666KK9AABcPl10Mb0CXnRpPi+66LsCL7roPOmiCz8CXXQRPumiCz8CXXSPPowu+j0CGF2SPowu+j0CRhfZPumiCz8CL7oJP+miCz8CGF2gPkYXlb0DGF2YPhhd7L0AAIw+GF0UvgPSRX8+u+gyvkYXXT6MLkK+A7voOj5edFG+ddENPl50Ub4A",
+ "AAF10TU+jC46PwJ10TU+AAAAAAKMLpI9AAAAAAKMLpI9jC46PwJ10TU+jC46PwA=",
+ "AAG66Jw+GF00vAPSRWc+GF00vOmiKz4AAMA8Ay+64D2ji249AACgPQAA+D0DAABAPS+6PD4AAEA9ddGJPgMAAEA9L7q0PgAAoD1edNU+Ay+64D2MLvY+jC4qPtJFBD8DGF1kPl10DT9GF5k+XXQNPwMvurA+XXQNP7voxj6jiwk/A0YX3T7pogU/L7ruPqOL+j4DjC4AP3XR6T7SRQU/RhfPPgMYXQo/o4u0PhhdCj+ji44+AhhdCj+ji3Y+Arvo2j2ji3Y+Arvo2j0AAKQ+Al503z4AAKQ+A1503z5ddLk+L7rWPgAAyj4DAADOPi+62j6MLr4+GF3kPgOji64+AADuPl10mT4AAO4+A6OLgj4AAO4+u+hiPi+64j4DRhdBPumi1z6jiy4+6aLFPgMYXRw+ddGzPhhdHD666J4+AhhdHD6MLn4+AxhdHD6MLkY+AAAwPrroHj4DAABEPtJF7z3pomc+ddHFPQPpooU+RhedPV10nT5GF509A7vorD5GF5096aK5PqOLrj0DGF3GPi+6wD3pos8+GF3kPQO76Ng+AAAEPnXR3T6MLh4+AumiCD/pogs+A6OLBT8YXbw9Rhf7PgAAcD0D0kXrPl500TzSRdM+L7roOwNddLs+GF00vLronD4YXTS8AA==",
+ "AAFGF40+o4suvAOji1Y+o4suvF10IT5GF708A1502T2MLmo9RhedPXXR9T0Du+hCPemiOz676EI9RheLPgO76EI9GF24PnXRnT2ji9g+A7vo2j0vuvg+o4siPrroBD8D6aJXPl10DT9ddI0+XXQNPwNddKc+XXQNP9JFtz5GFwk/A9JFxz510QQ/AADQPowu/j4Du+jYPi+68j510d0+AADqPgJGF+E+AADqPgJGF+E+jC46PwIvugs/jC46PwIvugs/AAAAAAIYXeI+AAAAAAIYXeI+ddGtPQJ10d0+ddGtPQO76Ng+jC6KPemizz4vujg9A6OLxj6MLro8o4u2PnXRxTsDo4umPqOLLrxGF40+o4suvAABRheZPumioz0Do4uwPumioz0vusA+RhfVPQNGF9E+6aIDPl502T4AADA+AwAA4j4YXVw+AADiPumiiz4DAADiPi+6qD7potk+o4u+PgPSRdE+GF3UPkYXwT6ji+A+A7vosD4vuuw+RheZPi+67D4Do4uAPi+67D4YXWA+AADgPgPpoj8+0kXTPrvoLj7SRb0+A6OLHj7SRac+o4sePumiiz4Do4sePtJFXz7SRS8+o4syPgMAAEA+ddEFPi+6YD7SRdc9A7rogD7poqM9RheZPumioz0A",
+ "AA==",
+ "AAHpoms+ddFFvAOjizY+ddFFvOmiCz4vuug7A110wT2MLto80kWPPYwugj0D6aI7PXXRzT3pojs9ddEdPgPpojs9RhdNPowugj3poms+A6OLpj1GF4U+GF3kPQAAjj4DRhcRPrrolj7SRTc+XXSbPgNedF0+AACgPqOLgj4YXaI+A+mimz7SRaU+0kWrPkYXpz4Du+i6PkYXqT4AAMI+XXStPgNGF8k+ddGxPkYXyT7pors+AkYXyT676Lw+A0YXyT4vutQ+6aK7PnXR4T4DGF2uPrvo7j4AAJQ+u+juPgNGF3E+u+juPl50UT4vuuI+A4wuMj4vutY+jC4mPgAAyD4CAACAPemi0z4DGF2kPUYX7T6MLuo9L7r8PgMYXRg+0kUGP4wuRj510Qk/AwAAdD5ddA0/0kWTPl10DT8DAACkPl10DT8vurY+XXQLPwPposk+o4sJPwAA2j4YXQQ/A6OL6j4YXf4+Rhf1PkYX6z4D6aL/PgAA2D7pov8+XXS5PgLpov8+AAAAAAKji8o+AAAAAAKji8o+L7qYPQIYXcg+L7qYPQNGF8M+RhddPaOLuD7pogs9AwAArj4vumg8XXSdPumiizoDuuiMPnXRRbzpoms+ddFFvAAB6aKBPnXRlT0DjC6YPnXRlT2MLqg+XXS5PQMYXbg+RhfdPS+6wD7SRQs+A9JFyT4YXSg+0kXJPl10ST4C0kXJPi+6iD4DGF3GPnXRhT4AAL4+0kWDPgN10bU+uuiAPtJFqz6MLn4+Ay+6oD676Ho+L7qWPgAAeD4DL7qMPl50dT4AAIY+6aJzPgMYXWw+6aJvPowuUj6MLmY+AxhdOD4vulw+L7ooPrvoSj4DXXQZPl10OT5ddBk+GF0cPgNddBk+AADoPdJFNz6ji749A0YXVT510ZU96aKBPnXRlT0A",
+ "AAHpoqM9AAAAAALpoqM9jC46PwKjiz4+jC46PwKjiz4+AADqPgJGF0U+AADqPgOji04+L7ryPhhdYD6MLv4+A4wucj510QQ/uuiIPkYXCT8DL7qYPl10DT8vurI+XXQNPwOji9Q+XXQNP0YX7z666AQ/A3XRBD8vuvg+GF0MP6OL2D4DAAAUPxhduD4AABQ/RheLPgMAABQ/6aI7Pl10DD910fU9A7roBD+MLmo9XnTvPkYXvTwDRhfVPqOLLrzSRbM+o4suvAN10Zk+o4suvOmiiT510cU7A9JFcz6MLro8RhdhPi+6OD0Du+hOPowuij1GF0U+ddGtPQIAADw+ddGtPQIAADw+AAAAAALpoqM9AAAAAAABGF08Pumiiz4DGF08PhhdXD5ddE0+AAAwPgOji14+6aIDPrvofj5GF9U9A+mijz7poqM9RhenPumioz0DXXS/Pumioz110c8+0kXXPQOMLuA+ddEFPqOL6D6jizI+A0YX8T7SRV8+RhfxPumiiz4DRhfxPtJFpz4vuug+0kW9PgOji+A+0kXTPgAA0D4AAOA+A+mivz4vuuw+RhenPi+67D4DXXSPPi+67D6MLn4+o4vgPgN10V0+GF3UPkYXTT6ji74+AxhdPD4vuqg+GF08Pumiiz4A"
+ ]
+}
diff --git a/packages/core/tests/io/formats/fig/export/export-contract.test.ts b/packages/core/tests/io/formats/fig/export/export-contract.test.ts
new file mode 100644
index 000000000..ab75f137a
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/export-contract.test.ts
@@ -0,0 +1,51 @@
+import { expect, test } from 'bun:test'
+
+import { toUint8Array } from 'js-base64'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import fixture from './export-contract.json'
+
+test('Figma-authored minimal contract exports a decodable node stream', async () => {
+ await initCodec()
+ const { graph } = materializeDocument(
+ fixture.records as NodeChange[],
+ fixture.blobs.map((value) => toUint8Array(value))
+ )
+ const bytes = await exportFigFile(graph)
+ const { nodeChanges } = parseFigBuffer(bytes.buffer as ArrayBuffer)
+ expect(nodeChanges.length).toBeGreaterThan(0)
+ const text = nodeChanges.find((node) => node.type === 'TEXT' && node.name === 'Styled label')
+ expect(text?.parameterConsumptionMap).toEqual({
+ entries: [
+ {
+ variableField: 'VISIBLE',
+ variableData: {
+ value: { propRefValue: { defId: { sessionID: 292486, localID: 0 } } },
+ dataType: 'PROP_REF',
+ resolvedDataType: 'BOOLEAN'
+ }
+ }
+ ]
+ })
+})
+
+test('reads Figma-authored modern property defaults and references', () => {
+ const { graph, sources } = materializeDocument(
+ fixture.records as NodeChange[],
+ fixture.blobs.map((value) => toUint8Array(value))
+ )
+ const componentId = sources.get(fixture.ids.component)
+ const textId = sources.get(fixture.ids.text)
+ if (!componentId || !textId) throw new Error('Missing fixture nodes')
+ const component = graph.getNode(componentId)
+ const text = graph.getNode(textId)
+ expect(component?.componentPropertyDefinitions[0]?.defaultValue).toBe('true')
+ expect(text?.componentPropertyReferences).toEqual([{ propertyId: '292486:0', field: 'VISIBLE' }])
+ const instanceId = sources.get(fixture.ids.instance)
+ if (!instanceId) throw new Error('Missing instance')
+ expect(graph.getChildren(instanceId)[0]?.visible).toBe(false)
+})
diff --git a/packages/core/tests/io/formats/fig/export/geometry-winding.test.ts b/packages/core/tests/io/formats/fig/export/geometry-winding.test.ts
new file mode 100644
index 000000000..35a1fea3c
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/geometry-winding.test.ts
@@ -0,0 +1,28 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { resolveGeometryPaths } from '@open-pencil/fig/node-change'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('decodes Kiwi ODD geometry as scene even-odd', () => {
+ const paths = resolveGeometryPaths(
+ [{ windingRule: 'ODD', commandsBlob: 0 }],
+ [new Uint8Array([0])]
+ )
+ expect(paths[0].windingRule).toBe('EVENODD')
+})
+
+test('encodes scene even-odd geometry using the Kiwi enum', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ graph.createNode('VECTOR', graph.getPages()[0].id, {
+ fillGeometry: [{ windingRule: 'EVENODD', commandsBlob: new Uint8Array([0]) }],
+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: new Uint8Array([0]) }]
+ })
+ const bytes = await exportFigFile(graph)
+ const restored = await parseFigFile(bytes.buffer as ArrayBuffer)
+ const vector = [...restored.getAllNodes()].find((node) => node.type === 'VECTOR')
+ expect(vector?.fillGeometry[0]?.windingRule).toBe('EVENODD')
+ expect(vector?.strokeGeometry[0]?.windingRule).toBe('NONZERO')
+})
diff --git a/packages/core/tests/io/formats/fig/export/gold-edit.test.ts b/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
new file mode 100644
index 000000000..5b2ad1359
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
@@ -0,0 +1,126 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import { readFixtureArrayBuffer } from '../../../../helpers/fig/fixtures'
+
+test('Gold document exposes effective Boolean assignments and supports editor undo/redo', async () => {
+ const parsed = parseFigBuffer(readFixtureArrayBuffer('gold-preview.fig'))
+ const diagnostics: unknown[] = []
+ const { graph, sources } = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ images: new Map(parsed.images),
+ derivedBounds: true,
+ onUnresolvedProperty: (d) => diagnostics.push(d)
+ })
+ const inputId = sources.get('1:3503')
+ if (!inputId) throw new Error('Missing input')
+ const contents: SceneNode[] = []
+ const visit = (id: string): void => {
+ for (const child of graph.getChildren(id)) {
+ if (child.type === 'INSTANCE' && child.name === '_badge-and-tag') contents.push(child)
+ visit(child.id)
+ }
+ }
+ visit(inputId)
+ expect(contents).toHaveLength(3)
+ const first = contents[0]
+ expect(first.componentPropertyAssignments['4270:0']).toBe('true')
+ expect(first.componentPropertyAssignments['4270:3']).toBe('true')
+ const avatar = graph.getChildren(first.id).find((n) => n.name === 'Avatar')
+ if (!avatar) throw new Error('Missing avatar')
+ const originalComponents = contents.map((node) => {
+ const avatar = graph.getChildren(node.id).find((child) => child.name === 'Avatar')
+ return avatar?.componentId ? graph.getNode(avatar.componentId)?.name : undefined
+ })
+ expect(originalComponents).toEqual(['avatar04', 'avatar05', 'avatar06'])
+ const originalSizes = contents.map((node) => {
+ const avatar = graph.getChildren(node.id).find((child) => child.name === 'Avatar')
+ if (!avatar) throw new Error('Missing original avatar')
+ return { width: avatar.width, height: avatar.height }
+ })
+ const originalInput = graph.getNode(inputId)
+ if (!originalInput) throw new Error('Missing original input')
+ const originalInputSize = { width: originalInput.width, height: originalInput.height }
+ const editor = createEditor({ graph })
+ editor.setInstanceComponentProperty(first.id, '4270:0', 'false')
+ expect(avatar.visible).toBe(false)
+ editor.undo.undo()
+ expect(avatar.visible).toBe(true)
+ editor.undo.redo()
+ expect(avatar.visible).toBe(false)
+ graph.updateNode(inputId, { name: 'Gold edited input' })
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const saved = parseFigBuffer(bytes.buffer as ArrayBuffer)
+ const { graph: restored } = materializeDocument(saved.nodeChanges, saved.blobs, {
+ images: new Map(saved.images),
+ derivedBounds: true
+ })
+ const input = [...restored.getAllNodes()].find((node) => node.name === 'Gold edited input')
+ if (!input) throw new Error('Missing edited input after reload')
+ const restoredContents: SceneNode[] = []
+ const collect = (id: string): void => {
+ for (const child of restored.getChildren(id)) {
+ if (child.type === 'INSTANCE' && child.name === '_badge-and-tag') restoredContents.push(child)
+ collect(child.id)
+ }
+ }
+ collect(input.id)
+ expect(restoredContents).toHaveLength(3)
+ expect(
+ restoredContents.map(
+ (node) =>
+ restored
+ .getChildren(node.id)
+ .find((child) =>
+ child.componentPropertyReferences.some(
+ (ref) => ref.propertyId === '4270:0' && ref.field === 'VISIBLE'
+ )
+ )?.visible
+ )
+ ).toEqual([false, true, true])
+ expect(
+ restoredContents.map((node) => {
+ const avatar = restored
+ .getChildren(node.id)
+ .find((child) =>
+ child.componentPropertyReferences.some(
+ (ref) => ref.propertyId === '4270:0' && ref.field === 'VISIBLE'
+ )
+ )
+ return avatar?.componentId ? restored.getNode(avatar.componentId)?.name : undefined
+ })
+ ).toEqual(originalComponents)
+ expect({ width: input.width, height: input.height }).toEqual(originalInputSize)
+ expect(
+ restoredContents.map((node) => {
+ const avatar = restored
+ .getChildren(node.id)
+ .find((child) =>
+ child.componentPropertyReferences.some(
+ (ref) => ref.propertyId === '4270:0' && ref.field === 'VISIBLE'
+ )
+ )
+ if (!avatar) throw new Error('Missing restored avatar')
+ return { width: avatar.width, height: avatar.height }
+ })
+ ).toEqual(originalSizes)
+ const reopenedEditor = createEditor({ graph: restored })
+ reopenedEditor.setInstanceComponentProperty(restoredContents[1].id, '4270:0', 'false')
+ const secondAvatar = restored
+ .getChildren(restoredContents[1].id)
+ .find((child) =>
+ child.componentPropertyReferences.some(
+ (ref) => ref.propertyId === '4270:0' && ref.field === 'VISIBLE'
+ )
+ )
+ if (!secondAvatar) throw new Error('Missing reopened avatar target')
+ expect(secondAvatar.visible).toBe(false)
+ reopenedEditor.undo.undo()
+ expect(secondAvatar.visible).toBe(true)
+ expect(graph.getChildren(contents[1].id).find((n) => n.name === 'Avatar')?.visible).toBe(true)
+})
diff --git a/packages/core/tests/io/formats/fig/export/layout-edit-export.test.ts b/packages/core/tests/io/formats/fig/export/layout-edit-export.test.ts
new file mode 100644
index 000000000..eecbf7f15
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/layout-edit-export.test.ts
@@ -0,0 +1,60 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import { guid } from '../../../../helpers/fig/guid'
+
+test('retained implicit layout survives import but does not override an explicit sizing edit', async () => {
+ await initCodec()
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'DOCUMENT' },
+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'FRAME',
+ name: 'Layout',
+ parentIndex: { guid: guid(2), position: '!' },
+ stackMode: 'HORIZONTAL',
+ stackPrimarySizing: 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE',
+ stackCounterSizing: 'FIXED',
+ size: { x: 100, y: 28 }
+ }
+ ]
+ const { graph, sources } = materializeDocument(changes)
+ const id = sources.get('1:3')
+ if (!id) throw new Error('Missing layout')
+ const readSizing = async () => {
+ const bytes = await exportFigFile(graph)
+ return parseFigBuffer(bytes.buffer as ArrayBuffer).nodeChanges.find((n) => n.name === 'Layout')
+ ?.stackPrimarySizing
+ }
+ expect(await readSizing()).toBe('RESIZE_TO_FIT_WITH_IMPLICIT_SIZE')
+ graph.updateNode(id, {
+ itemSpacing: 0,
+ paddingLeft: 7,
+ paddingRight: 9,
+ layoutGrow: 0,
+ counterAxisAlign: 'MAX',
+ layoutDirection: 'RTL'
+ })
+ const bytes = await exportFigFile(graph)
+ const exported = parseFigBuffer(bytes.buffer as ArrayBuffer).nodeChanges.find(
+ (node) => node.name === 'Layout'
+ )
+ expect(exported?.stackSpacing).toBe(0)
+ expect(exported?.stackHorizontalPadding).toBe(7)
+ expect(exported?.stackPaddingRight).toBe(9)
+ expect(exported?.stackChildPrimaryGrow).toBe(0)
+ expect(exported?.stackCounterAlignItems).toBe('MAX')
+ expect(exported?.stackCounterSizing).toBe('FIXED')
+ expect(exported?.pluginData).toContainEqual({
+ pluginID: 'open-pencil',
+ key: 'layoutDirection',
+ value: 'RTL'
+ })
+ graph.updateNode(id, { primaryAxisSizing: 'FIXED' })
+ expect(await readSizing()).toBe('FIXED')
+})
diff --git a/packages/core/tests/io/formats/fig/export/layout-scale.test.ts b/packages/core/tests/io/formats/fig/export/layout-scale.test.ts
new file mode 100644
index 000000000..ade945bcb
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/layout-scale.test.ts
@@ -0,0 +1,76 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { computeAllLayouts } from '@open-pencil/core/layout'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { SymbolData } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { hasInstanceOverride } from '@open-pencil/scene-graph'
+import { readFixtureJSON } from '../../../../helpers/fig/fixtures'
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-layout-scale.json')
+
+
+function assembly(phase: 'before' | 'edited') {
+ return materializeDocument(
+ [{ guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT' }, ...fixture[phase]] as NodeChange[],
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
+ { derivedBounds: true }
+ )
+}
+
+for (const phase of ['before', 'edited'] as const) {
+ test(`nested Figma scale composes once and preserves ${phase} layout`, () => {
+ const { graph, sources } = assembly(phase)
+ const id = sources.get(fixture.ids.instance)
+ if (!id) throw new Error('Missing placed instance')
+ const root = graph.getNode(id)
+ const nested = graph.getChildren(id)[0]
+ const rectangle = graph.getChildren(nested.id)[0]
+ expect(root?.paddingLeft).toBe(phase === 'before' ? 10 : 13)
+ expect(nested.paddingLeft).toBe(phase === 'before' ? 2.5 : 7)
+ expect(nested.itemSpacing).toBe(1.5)
+ expect(rectangle.width).toBe(5)
+ computeAllLayouts(graph)
+ expect(root?.width).toBe(phase === 'before' ? 30 : 37.5)
+ expect(nested.width).toBe(phase === 'before' ? 10 : 14.5)
+ expect(rectangle.x).toBe(phase === 'before' ? 2.5 : 7)
+ expect(rectangle.width).toBe(5)
+ })
+}
+
+test('scaled padding edits undo and export in the declaring owner space', async () => {
+ await initCodec()
+ const { graph, sources } = assembly('before')
+ const id = sources.get(fixture.ids.instance)
+ if (!id) throw new Error('Missing placed instance')
+ const nested = graph.getChildren(id)[0]
+ const editor = createEditor({ graph })
+ expect(hasInstanceOverride(graph, nested.id, 'paddingLeft')).toBe(false)
+ editor.updateNodeWithUndo(nested.id, { paddingLeft: 7 })
+ expect(nested.paddingLeft).toBe(7)
+ expect(hasInstanceOverride(graph, nested.id, 'paddingLeft')).toBe(true)
+ editor.undo.undo()
+ expect(nested.paddingLeft).toBe(2.5)
+ expect(hasInstanceOverride(graph, nested.id, 'paddingLeft')).toBe(false)
+ editor.undo.redo()
+ expect(nested.paddingLeft).toBe(7)
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const saved = parsed.nodeChanges.find(
+ (node) => node.type === 'INSTANCE' && node.name === 'Scaled outer'
+ )
+ expect(saved).toBeDefined()
+ const overrides = (saved?.symbolData as SymbolData | undefined)?.symbolOverrides ?? []
+ expect(overrides.some((override) => override.stackHorizontalPadding === 14)).toBe(true)
+ const { graph: reopened } = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ derivedBounds: true
+ })
+ const placed = reopened
+ .getAllNodes()
+ .find((node) => node.type === 'INSTANCE' && node.name === 'Scaled outer')
+ if (!placed) throw new Error('Missing reopened instance')
+ expect(reopened.getChildren(placed.id)[0].paddingLeft).toBe(7)
+})
diff --git a/packages/core/tests/io/formats/fig/export/live-variable-scale.test.ts b/packages/core/tests/io/formats/fig/export/live-variable-scale.test.ts
new file mode 100644
index 000000000..190d83ffd
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/live-variable-scale.test.ts
@@ -0,0 +1,64 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import { readFixtureArrayBuffer } from '../../../../helpers/fig/fixtures'
+
+function tagsInInput(graph: SceneGraph, rootId: string): SceneNode {
+ const found: SceneNode[] = []
+ const visit = (id: string) => {
+ for (const node of graph.getChildren(id)) {
+ if (node.name === 'Tags' && node.boundVariables.paddingLeft) found.push(node)
+ visit(node.id)
+ }
+ }
+ visit(rootId)
+ expect(found).toHaveLength(1)
+ return found[0]
+}
+
+test('Gold imported binding units survive token edits and undo/redo', async () => {
+ const parsed = parseFigBuffer(readFixtureArrayBuffer('gold-preview.fig'))
+ const { graph, sources } = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ derivedBounds: true
+ })
+ const inputId = sources.get('1:3503')
+ if (!inputId) throw new Error('Missing input')
+ const tags = tagsInInput(graph, inputId)
+ const variableId = tags.boundVariables.paddingLeft
+ const variable = graph.variables.get(variableId)
+ if (!variable) throw new Error('Missing padding binding')
+ const mode = graph.getNodeVariableModeId(tags.id, variable.collectionId)
+ const editor = createEditor({ graph })
+ expect(graph.resolveVariable(variableId, mode)).toBe(8)
+ expect(tags.paddingLeft).toBeCloseTo(7.126753330230713, 6)
+ expect(tags.variableBindingScales.paddingLeft).toBeCloseTo(0.8908441662788391, 6)
+ editor.updateVariableValue(variableId, mode, 16)
+ expect(tags.paddingLeft).toBeCloseTo(14.253506660461426, 6)
+ expect(graph.getChildren(tags.id)[0].x).toBeCloseTo(tags.paddingLeft, 6)
+ editor.undo.undo()
+ expect(tags.paddingLeft).toBeCloseTo(7.126753330230713, 6)
+ editor.undo.redo()
+ expect(tags.paddingLeft).toBeCloseTo(14.253506660461426, 6)
+ editor.updateNodeWithUndo(inputId, { name: 'Live variable scale round-trip target' })
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const reopened = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const restored = materializeDocument(reopened.nodeChanges, reopened.blobs, {
+ derivedBounds: true
+ })
+ const roots = [...restored.graph.getAllNodes()].filter(
+ (node) => node.name === 'Live variable scale round-trip target'
+ )
+ expect(roots).toHaveLength(1)
+ const reopenedTags = tagsInInput(restored.graph, roots[0].id)
+ expect(reopenedTags.paddingLeft).toBeCloseTo(14.253506660461426, 6)
+ expect(reopenedTags.variableBindingScales.paddingLeft).toBeCloseTo(
+ tags.variableBindingScales.paddingLeft ?? 1,
+ 6
+ )
+})
diff --git a/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts b/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts
new file mode 100644
index 000000000..788acb6f4
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts
@@ -0,0 +1,105 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile, FigmaAPI, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { parseFigBuffer } from '@open-pencil/fig'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import { expectDefined } from '../../../../helpers/assert'
+
+// Captured from Figma's own clipboard encoding of the same edit: a text override inside a
+// nested instance is addressed as [nested instance, the nested component's child], never as
+// the enclosing component's copy of that child, which is not a record in the archive.
+test('an override inside a nested instance addresses the definition child', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const page = graph.getPages()[0]
+ const badge = graph.createNode('COMPONENT', page.id, { name: 'Badge', width: 40, height: 20 })
+ graph.createNode('TEXT', badge.id, { name: 'count', text: '1', width: 20, height: 16 })
+ const card = graph.createNode('COMPONENT', page.id, { name: 'Card', width: 200, height: 80 })
+ graph.createInstance(badge.id, card.id)
+ const instance = graph.createInstance(card.id, page.id)
+ const nestedBadge = expectDefined(graph.getChildren(instance.id)[0], 'nested badge')
+ const count = expectDefined(graph.getChildren(nestedBadge.id)[0], 'nested count')
+ api.wrapNode(count.id).characters = '42'
+
+ const bytes = await exportFigFile(graph)
+ const { nodeChanges } = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const ids = new Set(nodeChanges.flatMap((node) => (node.guid ? [guidToString(node.guid)] : [])))
+ const exported = expectDefined(
+ nodeChanges.find(
+ (node) => node.type === 'INSTANCE' && node.symbolData?.symbolOverrides?.length
+ ),
+ 'exported instance'
+ )
+ const claim = expectDefined(
+ exported.symbolData?.symbolOverrides?.find((override) => override.textData),
+ 'text claim'
+ )
+ const path = (claim.guidPath?.guids ?? []).map(guidToString)
+ expect(path).toHaveLength(2)
+ for (const segment of path) expect(ids.has(segment)).toBe(true)
+ const definitionCount = nodeChanges.find((node) => node.type === 'TEXT' && node.name === 'count')
+ expect(path[1]).toBe(guidToString(expectDefined(definitionCount?.guid, 'count guid')))
+
+ const reopened = await parseFigFile(bytes.slice().buffer as ArrayBuffer)
+ const reopenedInstance = expectDefined(
+ [...reopened.getAllNodes()].find(
+ (node) => node.type === 'INSTANCE' && node.parentId === reopened.getPages()[0].id
+ ),
+ 'reopened instance'
+ )
+ const reopenedCount = reopened.getChildren(reopened.getChildren(reopenedInstance.id)[0].id)[0]
+ expect(reopenedCount?.text).toBe('42')
+})
+
+test('a swap of a nested instance is addressed by the nested instance record', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const dot = graph.createNode('COMPONENT', page.id, { name: 'Dot', width: 16, height: 16 })
+ const star = graph.createNode('COMPONENT', page.id, { name: 'Star', width: 16, height: 16 })
+ const panel = graph.createNode('COMPONENT', page.id, { name: 'Panel', width: 200, height: 80 })
+ const marker = graph.createInstance(dot.id, panel.id)
+ graph.updateNode(marker.id, { name: 'marker' })
+ const instance = graph.createInstance(panel.id, page.id)
+ const nestedMarker = expectDefined(graph.getChildren(instance.id)[0], 'nested marker')
+ graph.swapInstanceComponent(nestedMarker.id, star.id)
+
+ const bytes = await exportFigFile(graph)
+ const { nodeChanges } = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const exported = expectDefined(
+ nodeChanges.find(
+ (node) => node.type === 'INSTANCE' && node.symbolData?.symbolOverrides?.length
+ ),
+ 'exported instance'
+ )
+ const swap = expectDefined(
+ exported.symbolData?.symbolOverrides?.find((override) => override.overriddenSymbolID),
+ 'swap claim'
+ )
+ const markerRecord = expectDefined(
+ nodeChanges.find((node) => node.type === 'INSTANCE' && node.name === 'marker'),
+ 'marker record'
+ )
+ const starRecord = expectDefined(
+ nodeChanges.find((node) => node.name === 'Star'),
+ 'star record'
+ )
+ expect((swap.guidPath?.guids ?? []).map(guidToString)).toEqual([
+ guidToString(expectDefined(markerRecord.guid, 'marker guid'))
+ ])
+ expect(guidToString(expectDefined(swap.overriddenSymbolID, 'replacement'))).toBe(
+ guidToString(expectDefined(starRecord.guid, 'star guid'))
+ )
+
+ const reopened = await parseFigFile(bytes.slice().buffer as ArrayBuffer)
+ const reopenedInstance = expectDefined(
+ [...reopened.getAllNodes()].find(
+ (node) => node.type === 'INSTANCE' && node.parentId === reopened.getPages()[0].id
+ ),
+ 'reopened instance'
+ )
+ const reopenedMarker = reopened.getChildren(reopenedInstance.id)[0]
+ expect(reopened.getNode(reopenedMarker?.componentId ?? '')?.name).toBe('Star')
+})
diff --git a/packages/core/tests/io/formats/fig/export/rescale-export.test.ts b/packages/core/tests/io/formats/fig/export/rescale-export.test.ts
new file mode 100644
index 000000000..1ce858dd7
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/rescale-export.test.ts
@@ -0,0 +1,96 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { SymbolData } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { setInstanceOverride } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../../../../helpers/assert'
+import { readFixtureJSON } from '../../../../helpers/fig/fixtures'
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-binding-ownership-records.json')
+
+for (const scale of [0.5, 2]) {
+ for (const literalClaim of [false, true]) {
+ test(`rescaling an imported owner by ${scale} exports current coordinates (literal claim: ${literalClaim})`, async () => {
+ const { graph, sources } = materializeDocument(
+ fixture.nodeChanges as NodeChange[],
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
+ { derivedBounds: true }
+ )
+ const root = expectDefined(graph.getNode(expectDefined(sources.get('293733:8'))))
+ const nested = expectDefined(graph.getChildren(root.id)[0])
+ const api = new FigmaAPI(graph)
+ api.bindVariable(root.id, 'paddingRight', '293742:7')
+ api.bindVariable(nested.id, 'paddingRight', '293742:7')
+ if (literalClaim) {
+ createEditor({ graph }).updateNodeWithUndo(root.id, { paddingLeft: 12 })
+ setInstanceOverride(root.instanceOverrides, root.id, root.id, 'paddingLeft', 12)
+ }
+ api.getNodeById(root.id).rescale(scale)
+ expect([
+ root.width,
+ root.height,
+ root.paddingRight,
+ nested.width,
+ nested.paddingLeft,
+ nested.paddingRight
+ ]).toEqual([
+ (literalClaim ? 35 : 33) * scale,
+ 7 * scale,
+ 6 * scale,
+ 17 * scale,
+ 6 * scale,
+ 6 * scale
+ ])
+ graph.updateNode(root.id, { name: 'Rescaled owner' })
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const exported = expectDefined(
+ parsed.nodeChanges.find((node) => node.name === 'Rescaled owner')
+ )
+ const symbol = exported.symbolData as SymbolData
+ expect(
+ symbol.symbolOverrides?.filter((entry) => entry.size).map((entry) => entry.guidPath?.guids)
+ ).toEqual([[symbol.symbolID]])
+ const reopened = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ derivedBounds: true
+ }).graph
+ const restored = expectDefined(
+ reopened.getAllNodes().find((node) => node.name === 'Rescaled owner')
+ )
+ const child = expectDefined(reopened.getChildren(restored.id)[0])
+ expect([
+ restored.width,
+ restored.height,
+ restored.paddingRight,
+ child.width,
+ child.paddingLeft,
+ child.paddingRight
+ ]).toEqual([
+ (literalClaim ? 35 : 33) * scale,
+ 7 * scale,
+ 6 * scale,
+ 17 * scale,
+ 6 * scale,
+ 6 * scale
+ ])
+ expect(restored.paddingLeft).toBe((literalClaim ? 12 : 10) * scale)
+ expect(restored.componentScale).toBe(scale * 0.5)
+ expect(child.variableBindingScales.paddingLeft).toBe(scale * 0.5)
+ const variable = expectDefined(reopened.variables.get(child.boundVariables.paddingLeft))
+ new FigmaAPI(reopened).setVariableValue(
+ variable.id,
+ reopened.getNodeVariableModeId(child.id, variable.collectionId),
+ 16
+ )
+ expect(child.paddingLeft).toBe(8 * scale)
+ expect(restored.width).toBe((literalClaim ? 41 : 39) * scale)
+ })
+ }
+}
diff --git a/packages/core/tests/io/formats/fig/export/scalar-override-lifecycle.test.ts b/packages/core/tests/io/formats/fig/export/scalar-override-lifecycle.test.ts
new file mode 100644
index 000000000..f5f2116f8
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/scalar-override-lifecycle.test.ts
@@ -0,0 +1,52 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+
+const guid = (localID: number) => ({ sessionID: 1, localID })
+const records = () => [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ { guid: guid(2), type: 'SYMBOL', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ name: 'Label',
+ fontSize: 12,
+ opacity: 1,
+ textData: { characters: 'Label' },
+ parentIndex: { guid: guid(2), position: '!' }
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: {
+ symbolID: guid(2),
+ symbolOverrides: [
+ { guidPath: { guids: [guid(3)] }, name: 'Custom', fontSize: 24, opacity: 0.5 }
+ ]
+ }
+ }
+]
+
+test('scalar descendant claims survive synchronization and edited export', async () => {
+ const { graph, sources } = materializeDocument(records())
+ const root = graph.getNode(sources.get('1:4') ?? '')
+ if (!root) throw new Error('Missing instance')
+ const child = graph.getChildren(root.id)[0]
+ expect(child).toMatchObject({ name: 'Custom', fontSize: 24, opacity: 0.5 })
+ graph.syncInstances(root.componentId ?? '')
+ expect(child).toMatchObject({ name: 'Custom', fontSize: 24, opacity: 0.5 })
+ graph.updateNode(root.id, { x: 1 })
+ await initCodec()
+ const parsed = parseFigBuffer((await exportFigFile(graph)).slice().buffer as ArrayBuffer)
+ const reopened = materializeDocument(parsed.nodeChanges, parsed.blobs).graph
+ const restored = reopened.getAllNodes().find((node) => node.type === 'INSTANCE')
+ expect(restored && reopened.getChildren(restored.id)[0]).toMatchObject({
+ name: 'Custom',
+ fontSize: 24,
+ opacity: 0.5
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/export/self-size-export.test.ts b/packages/core/tests/io/formats/fig/export/self-size-export.test.ts
new file mode 100644
index 000000000..85c970b8b
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/self-size-export.test.ts
@@ -0,0 +1,35 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { parseFigBuffer } from '@open-pencil/fig'
+import type { SymbolData } from '@open-pencil/fig/instance-overrides'
+import { SceneGraph, setInstanceOverride, rescaleNodeTree } from '@open-pencil/scene-graph'
+
+test('serializes self size claims against the instance main component', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id, {
+ width: 100,
+ height: 100
+ })
+ const instance = graph.createInstance(component.id, graph.getPages()[0].id)
+ if (!instance) throw new Error('Missing instance')
+ rescaleNodeTree(graph, instance.id, 0.5)
+ graph.updateNode(instance.id, { width: 16, height: 16, paddingLeft: 10 })
+ setInstanceOverride(instance.instanceOverrides, instance.id, instance.id, 'width', 16)
+ setInstanceOverride(instance.instanceOverrides, instance.id, instance.id, 'paddingLeft', 10)
+ setInstanceOverride(instance.instanceOverrides, instance.id, instance.id, 'height', 16)
+ const bytes = await exportFigFile(graph)
+ const { nodeChanges } = parseFigBuffer(bytes.buffer as ArrayBuffer)
+ const exported = nodeChanges.find((node) => node.type === 'INSTANCE')
+ const symbol = exported?.symbolData as SymbolData | undefined
+ if (!symbol) throw new Error('Missing exported symbol')
+ expect(exported?.size).toEqual({ x: 16, y: 16 })
+ expect(symbol.uniformScaleFactor).toBe(0.5)
+ expect(symbol.symbolOverrides).toContainEqual({
+ guidPath: { guids: [symbol.symbolID] },
+ size: { x: 32, y: 32 },
+ stackHorizontalPadding: 20
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/export/shared-style-export.test.ts b/packages/core/tests/io/formats/fig/export/shared-style-export.test.ts
new file mode 100644
index 000000000..48771b527
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/shared-style-export.test.ts
@@ -0,0 +1,23 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { parseFigBuffer } from '@open-pencil/fig'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('exports shared styles once even when present in a normal page subtree', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id)
+ graph.createNode('TEXT', frame.id, {
+ name: 'Shared typography',
+ sharedStyleType: 'TEXT',
+ text: 'Ag'
+ })
+ const bytes = await exportFigFile(graph)
+ const { nodeChanges } = parseFigBuffer(bytes.buffer as ArrayBuffer)
+ const styles = nodeChanges.filter((node) => node.name === 'Shared typography')
+ expect(styles).toHaveLength(1)
+ const ids = nodeChanges.map((node) => JSON.stringify(node.guid))
+ expect(new Set(ids).size).toBe(ids.length)
+})
diff --git a/packages/core/tests/io/formats/fig/export/text-sizing-export.test.ts b/packages/core/tests/io/formats/fig/export/text-sizing-export.test.ts
new file mode 100644
index 000000000..281d1d26e
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/text-sizing-export.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { parseFigBuffer } from '@open-pencil/fig'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+for (const mode of ['NONE', 'HEIGHT', 'WIDTH_AND_HEIGHT'] as const) {
+ test(`exports actual text sizing ${mode} inside auto-layout without importer metadata`, async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, { layoutMode: 'HORIZONTAL' })
+ graph.createNode('TEXT', frame.id, { text: 'Label', textAutoResize: mode })
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.buffer as ArrayBuffer)
+ expect(parsed.nodeChanges.find((node) => node.type === 'TEXT')?.textAutoResize).toBe(mode)
+ })
+}
diff --git a/packages/core/tests/io/formats/fig/import/stale-overrides.test.ts b/packages/core/tests/io/formats/fig/import/stale-overrides.test.ts
new file mode 100644
index 000000000..6fbb2ab2f
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/import/stale-overrides.test.ts
@@ -0,0 +1,57 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'
+import { parseFigBuffer } from '@open-pencil/fig'
+
+import { readerDiagnostics, registerReaderSession } from '#core/kiwi/fig/session/document-state'
+import { openReaderSession } from '#core/kiwi/fig/session/reader'
+
+import { readFixtureArrayBuffer } from '../../../../helpers/fig/fixtures'
+import { HEAVY_TEST_TIMEOUT_MS, runsHeavyTests } from '../../../../helpers/test-utils'
+
+// material3.fig retains overrides on 58114:20598 that address 57994:10133, a node the
+// archive no longer contains. Figma keeps such records; opening the file must not.
+test.if(runsHeavyTests)(
+ 'opening a file skips overrides against deleted nodes and reports them',
+ () => {
+ const reader = openReaderSession(readFixtureArrayBuffer('material3.fig'), 'all')
+ const stale = reader.diagnostics.filter(
+ (entry) =>
+ (entry.kind === 'property' || entry.kind === 'assignment') &&
+ entry.diagnostic.ownerId === '58114:20598' &&
+ entry.diagnostic.reason === 'missing-target'
+ )
+ expect(stale.length).toBeGreaterThan(0)
+ expect(reader.graph.getPages().length).toBeGreaterThan(1)
+ },
+ HEAVY_TEST_TIMEOUT_MS
+)
+
+// The Internal Only Canvas keeps instances of deleted components. Export loads every page,
+// so an edited document must still export and reopen with those instances intact.
+test.if(runsHeavyTests)(
+ 'an edited document with instances of deleted components exports and reopens',
+ async () => {
+ await initCodec()
+ const reader = openReaderSession(readFixtureArrayBuffer('material3.fig'), 'first-page')
+ const page = reader.graph.getPages()[0]
+ reader.graph.updateNode(page.id, { name: 'Edited page' })
+ registerReaderSession(
+ readFixtureArrayBuffer('material3.fig'),
+ reader.session,
+ reader.diagnostics
+ )
+ const bytes = await exportFigFile(reader.graph)
+ const orphans = readerDiagnostics(reader.graph).filter((entry) => entry.kind === 'component')
+ expect(orphans.length).toBeGreaterThan(0)
+ const reopened = await parseFigFile(bytes.slice().buffer as ArrayBuffer)
+ expect(reopened.getPages().some((node) => node.name === 'Edited page')).toBe(true)
+ // Each orphan is still an instance record, with no component to point at.
+ const { nodeChanges } = parseFigBuffer(bytes.slice().buffer as ArrayBuffer)
+ const exportedOrphans = nodeChanges.filter(
+ (node) => node.type === 'INSTANCE' && !node.symbolData?.symbolID
+ )
+ expect(exportedOrphans).toHaveLength(orphans.length)
+ },
+ HEAVY_TEST_TIMEOUT_MS * 4
+)
diff --git a/packages/core/tests/io/formats/fig/instance/component-sync.test.ts b/packages/core/tests/io/formats/fig/instance/component-sync.test.ts
new file mode 100644
index 000000000..fafa191ed
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/instance/component-sync.test.ts
@@ -0,0 +1,129 @@
+import { expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core'
+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { interpretInstance, materializeInstance } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { guid } from '../../../../helpers/fig/guid'
+
+test('nested instances retain their outer source-child correspondence during sync', () => {
+ const source: NodeChange[] = [
+ { guid: guid(1), type: 'SYMBOL' },
+ { guid: guid(2), type: 'SYMBOL' },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '!' },
+ symbolData: { symbolID: guid(2) }
+ },
+ { guid: guid(4), type: 'INSTANCE', symbolData: { symbolID: guid(1) } }
+ ]
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const outer = graph.createNode('COMPONENT', page.id)
+ const inner = graph.createNode('COMPONENT', page.id)
+ const sourceChild = graph.createInstance(inner.id, outer.id)
+ if (!sourceChild) throw new Error('Missing source instance')
+ const occurrence = interpretInstance(source, '1:4')
+ const result = materializeInstance(
+ graph,
+ page.id,
+ occurrence,
+ new Map([
+ ['1:1', outer.id],
+ ['1:2', inner.id]
+ ]),
+ { sourceChildren: new Map([[occurrence.children[0], sourceChild.id]]) }
+ )
+ const child = graph.getChildren(result.root.id)[0]
+ expect(child.componentId).toBe(inner.id)
+ graph.updateNode(sourceChild.id, { opacity: 0.5 })
+ graph.syncInstances(outer.id)
+ expect(graph.getChildren(result.root.id).map((node) => node.id)).toEqual([child.id])
+ expect(child.opacity).toBe(0.5)
+})
+
+test('swapped nested instances do not regain children from the original component', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const outer = graph.createNode('COMPONENT', page.id)
+ const original = graph.createNode('COMPONENT', page.id)
+ graph.createNode('TEXT', original.id, { text: 'Original' })
+ const replacement = graph.createNode('COMPONENT', page.id)
+ const sourceChild = graph.createInstance(original.id, outer.id)
+ if (!sourceChild) throw new Error('Missing source instance')
+ const occurrence = interpretInstance(
+ [
+ { guid: guid(1), type: 'SYMBOL' },
+ { guid: guid(2), type: 'SYMBOL' },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '!' },
+ symbolData: { symbolID: guid(2) }
+ },
+ { guid: guid(4), type: 'INSTANCE', symbolData: { symbolID: guid(1) } }
+ ],
+ '1:4'
+ )
+ const result = materializeInstance(
+ graph,
+ page.id,
+ occurrence,
+ new Map([
+ ['1:1', outer.id],
+ ['1:2', replacement.id]
+ ]),
+ { sourceChildren: new Map([[occurrence.children[0], sourceChild.id]]) }
+ )
+ const child = graph.getChildren(result.root.id)[0]
+ graph.syncInstances(outer.id)
+ expect(graph.getChildren(result.root.id).map((node) => node.id)).toEqual([child.id])
+ expect(child.componentId).toBe(replacement.id)
+ expect(graph.getChildren(child.id)).toHaveLength(0)
+})
+
+test('existing component synchronization updates unedited occurrences and preserves a text edit', async () => {
+ await initCodec()
+ const source: NodeChange[] = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1), position: '!' },
+ textData: { characters: 'Default' }
+ },
+ { guid: guid(3), type: 'INSTANCE', symbolData: { symbolID: guid(1) } }
+ ]
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id)
+ const label = graph.createNode('TEXT', component.id, { text: 'Default' })
+ const create = () => {
+ const occurrence = interpretInstance(source, '1:3')
+ return materializeInstance(graph, page.id, occurrence, new Map([['1:1', component.id]]), {
+ sourceChildren: new Map([[occurrence.children[0], label.id]])
+ })
+ }
+ const first = create()
+ const second = create()
+ const firstLabel = graph.getChildren(first.root.id)[0]
+ const secondLabel = graph.getChildren(second.root.id)[0]
+ const api = new FigmaAPI(graph)
+ api.wrapNode(firstLabel.id).characters = 'User edit'
+ api.wrapNode(label.id).characters = 'Component edit'
+ graph.syncInstances(component.id)
+ expect(firstLabel.text).toBe('User edit')
+ expect(secondLabel.text).toBe('Component edit')
+ expect(graph.getChildren(first.root.id)).toHaveLength(1)
+ expect(graph.getChildren(second.root.id)).toHaveLength(1)
+ const bytes = await exportFigFile(graph)
+ const restored = await parseFigFile(bytes.buffer as ArrayBuffer)
+ const instanceLabels = [...restored.getAllNodes()]
+ .filter((node) => node.type === 'INSTANCE')
+ .flatMap((node) => restored.getChildren(node.id).map((child) => child.text))
+ expect(instanceLabels.sort()).toEqual(['Component edit', 'User edit'])
+})
diff --git a/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts b/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts
new file mode 100644
index 000000000..7ae84fc17
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts
@@ -0,0 +1,98 @@
+import { expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core'
+import { interpretInstance, materializeInstance } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { guid } from '../../../../helpers/fig/guid'
+
+test('text overrides discard inherited glyph data but accept occurrence-derived replacement data', () => {
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1), position: '!' },
+ textData: { characters: 'Typography' },
+ derivedTextData: { layoutSize: { x: 415, y: 94 } }
+ },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [{ guidPath: { guids: [guid(2)] }, textData: { characters: 'Toolbars' } }]
+ },
+ derivedSymbolData: [
+ { guidPath: { guids: [guid(2)] }, derivedTextData: { layoutSize: { x: 310, y: 94 } } }
+ ]
+ }
+ ] as NodeChange[]
+ expect(interpretInstance(changes, '1:3').children[0].properties.derivedTextData).toBeUndefined()
+ expect(
+ interpretInstance(changes, '1:3', { derivedBounds: true }).children[0].properties
+ .derivedTextData?.layoutSize
+ ).toEqual({ x: 310, y: 94 })
+ expect(changes[1].derivedTextData?.layoutSize).toEqual({ x: 415, y: 94 })
+})
+
+test('occurrence text size replaces source cache and is invalidated by a text edit', () => {
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 67, y: 24 },
+ textData: { characters: 'Source' },
+ derivedTextData: { layoutSize: { x: 67, y: 24 } }
+ },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ symbolData: { symbolID: guid(1) },
+ derivedSymbolData: [{ guidPath: { guids: [guid(2)] }, size: { x: 213, y: 24 } }]
+ }
+ ] as NodeChange[]
+ const occurrence = interpretInstance(changes, '1:3', { derivedBounds: true })
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id)
+ const result = materializeInstance(graph, page.id, occurrence, new Map([['1:1', component.id]]))
+ const label = graph.getChildren(result.root.id)[0]
+ expect(label.derivedLayout).toEqual({ width: 213, height: 24 })
+ new FigmaAPI(graph).wrapNode(label.id).characters = 'Edited'
+ expect(label.derivedLayout).toBeNull()
+})
+
+test('uses explicit derived geometry with its bounds instead of the oversized source path', () => {
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'VECTOR',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 2650, y: 44 },
+ fillGeometry: [{ commandsBlob: 0, windingRule: 'NONZERO' }]
+ },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ symbolData: { symbolID: guid(1) },
+ derivedSymbolData: [
+ {
+ guidPath: { guids: [guid(2)] },
+ size: { x: 375, y: 39 },
+ fillGeometry: [{ commandsBlob: 1, windingRule: 'NONZERO' }]
+ }
+ ]
+ }
+ ] as NodeChange[]
+ const before = structuredClone(changes)
+ const node = interpretInstance(changes, '1:3', { derivedBounds: true }).children[0]
+ expect(node.properties.size).toEqual({ x: 375, y: 39 })
+ expect(node.properties.fillGeometry).toEqual([{ commandsBlob: 1, windingRule: 'NONZERO' }])
+ expect(interpretInstance(changes, '1:3').children[0].properties.size).toEqual({ x: 2650, y: 44 })
+ expect(changes).toEqual(before)
+})
diff --git a/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts b/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts
new file mode 100644
index 000000000..6c0943d08
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts
@@ -0,0 +1,158 @@
+import { expect, test } from 'bun:test'
+
+import { materializeComponentClosure } from '@open-pencil/fig/instance-overrides'
+import {
+ linkInstanceSourceChildren,
+ mapInstanceSourceChildren
+} from '@open-pencil/fig/instance-overrides'
+
+import { FigmaAPI } from '@open-pencil/core'
+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { parseFigBuffer } from '@open-pencil/fig'
+import {
+ type InstanceOccurrence,
+ interpretInstance,
+ materializeInstance
+} from '@open-pencil/fig/instance-overrides'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { readFixtureArrayBuffer } from '../../../../../helpers/fig/fixtures'
+
+function named(node: InstanceOccurrence, name: string): InstanceOccurrence {
+ const child = node.children.find((candidate) => candidate.properties.name === name)
+ if (!child) throw new Error(`Missing ${name} under ${node.properties.name}`)
+ return child
+}
+
+// Expectations captured from gold-preview in Figma, input 1:3503.
+// Exercise the original archive: no pre-resolved SceneGraph or legacy replay.
+test('Gold Preview input resolves badge visibility and distinct avatar swaps like Figma', async () => {
+ const bytes = readFixtureArrayBuffer('gold-preview.fig')
+ const { nodeChanges, blobs } = parseFigBuffer(bytes)
+ const diagnostics: unknown[] = []
+ const input = interpretInstance(nodeChanges, '1:3503', {
+ derivedBounds: true,
+ onUnresolvedProperty: (diagnostic) => diagnostics.push(diagnostic)
+ })
+ const frame = named(named(input, '_input'), 'Input')
+ expect(frame.properties.size?.x).toBeCloseTo(375.7498169, 5)
+ expect(frame.properties.size?.y).toBeCloseTo(39.3802605, 5)
+ const placeholder = named(named(named(frame, 'Content'), 'Placeholder'), 'Placeholder')
+ expect(placeholder.properties.fontSize).toBeCloseTo(12.471817970275879, 6)
+ expect(placeholder.properties.lineHeight).toEqual({ value: 17.816883087158203, units: 'PIXELS' })
+ const tags = named(named(frame, 'Content'), 'Tags')
+ const badges = tags.children.filter((node) => node.properties.name === 'Badge')
+ expect(badges).toHaveLength(3)
+ expect(badges.map((badge) => badge.mainComponentId)).toEqual(['1:935', '1:935', '1:935'])
+ const content = badges.map((badge) => named(badge, '_badge-and-tag'))
+ expect(content.map((node) => named(node, 'Avatar').mainComponentId)).toEqual([
+ '1:726',
+ '1:1759',
+ '1:1761'
+ ])
+ for (const node of content) {
+ expect(named(node, 'Avatar').properties.visible).toBe(true)
+ expect(named(node, 'home').properties.visible).toBe(false)
+ expect(named(node, 'chevron-right').properties.visible).toBe(false)
+ expect(named(node, 'Close-Icon').properties.visible).toBe(true)
+ }
+ expect(named(named(frame, 'Leading'), 'Avatar').properties.visible).toBe(false)
+ expect(named(named(frame, 'Trailing'), 'Avatar').properties.visible).toBe(false)
+ expect(
+ named(frame, 'Trailing').children.some((node) => node.properties.name === 'chevron-down')
+ ).toBe(true)
+ expect(diagnostics).toEqual([])
+
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const closure = materializeComponentClosure(graph, page.id, nodeChanges, input, blobs, {
+ derivedBounds: true,
+ onUnresolvedProperty: (diagnostic) => diagnostics.push(diagnostic)
+ })
+ const components = new Map(
+ [...closure].map(([id, component]) => [id, component.materialized.root.id])
+ )
+ const materialized = materializeInstance(
+ graph,
+ page.id,
+ input,
+ components,
+ blobs,
+ mapInstanceSourceChildren(input, closure)
+ )
+ linkInstanceSourceChildren(input, materialized, closure)
+ const labels = content.map((node) => named(named(node, 'Placeholder'), 'Placeholder'))
+ const first = materialized.nodes.get(labels[0])
+ if (!first) throw new Error('Missing first badge label')
+ const before = structuredClone(input)
+ const api = new FigmaAPI(graph)
+ api.wrapNode(first.id).characters = 'Edited badge'
+ expect(first.text).toBe('Edited badge')
+ expect(materialized.nodes.get(labels[1])?.text).toBe('Badge')
+ expect(materialized.nodes.get(labels[2])?.text).toBe('Badge')
+ expect(input).toEqual(before)
+
+ const badgeComponent = closure.get('1:935')
+ if (!badgeComponent) throw new Error('Missing real badge component')
+ const sourceLabelOccurrence = named(
+ named(named(badgeComponent.occurrence, '_badge-and-tag'), 'Placeholder'),
+ 'Placeholder'
+ )
+ const sourceLabel = badgeComponent.materialized.nodes.get(sourceLabelOccurrence)
+ if (!sourceLabel) throw new Error('Missing badge component label')
+ api.wrapNode(sourceLabel.id).characters = 'Updated component'
+ const beforeIds = [...materialized.nodes.values()].map((node) => node.id)
+ const beforeChildren = [...materialized.nodes.values()].map((node) => [...node.childIds])
+ const avatarIds = content.map(
+ (node) => materialized.nodes.get(named(node, 'Avatar'))?.componentId
+ )
+ graph.syncInstances(badgeComponent.materialized.root.id)
+ expect(first.text).toBe('Edited badge')
+ // Figma reports characters overrides on source badges 1:1820/1:1821/1:1822.
+ // These are inherited explicit overrides, not unoverridden component defaults.
+ expect(materialized.nodes.get(labels[1])?.text).toBe('Badge')
+ expect(materialized.nodes.get(labels[2])?.text).toBe('Badge')
+ expect(beforeIds.every((id) => graph.getNode(id))).toBe(true)
+ expect([...materialized.nodes.values()].map((node) => node.childIds)).toEqual(beforeChildren)
+ expect(content.map((node) => materialized.nodes.get(named(node, 'Avatar'))?.componentId)).toEqual(
+ avatarIds
+ )
+ await initCodec()
+ graph.updateNode(materialized.root.id, { name: 'Gold input acceptance' })
+ const exported = await exportFigFile(graph)
+ const restored = await parseFigFile(exported.buffer as ArrayBuffer)
+ const restoredInput = [...restored.getAllNodes()].find(
+ (node) => node.type === 'INSTANCE' && node.name === 'Gold input acceptance'
+ )
+ if (!restoredInput) throw new Error('Missing restored input')
+ const restoredText: string[] = []
+ const collectText = (id: string): void => {
+ const node = restored.getNode(id)
+ if (node?.type === 'TEXT') restoredText.push(node.text)
+ for (const child of restored.getChildren(id)) collectText(child.id)
+ }
+ collectText(restoredInput.id)
+ expect(restoredText.filter((text) => text === 'Edited badge')).toHaveLength(1)
+ expect(restoredText.filter((text) => text === 'Badge')).toHaveLength(2)
+ expect(restoredText).not.toContain('Updated component')
+ const restoredByName = (id: string, name: string): string => {
+ const child = restored.getChildren(id).find((node) => node.name === name)
+ if (!child) throw new Error(`Missing restored ${name}`)
+ return child.id
+ }
+ const restoredFrame = restoredByName(restoredByName(restoredInput.id, '_input'), 'Input')
+ const restoredTags = restoredByName(restoredByName(restoredFrame, 'Content'), 'Tags')
+ const restoredBadges = restored.getChildren(restoredTags).filter((node) => node.name === 'Badge')
+ expect(restoredBadges).toHaveLength(3)
+ for (const badge of restoredBadges) {
+ const contentId = restoredByName(badge.id, '_badge-and-tag')
+ expect(restored.getNode(restoredByName(contentId, 'home'))?.visible).toBe(false)
+ expect(restored.getNode(restoredByName(contentId, 'chevron-right'))?.visible).toBe(false)
+ }
+
+ for (const node of content) {
+ expect(materialized.nodes.get(named(node, 'home'))?.visible).toBe(false)
+ expect(materialized.nodes.get(named(node, 'chevron-right'))?.visible).toBe(false)
+ }
+})
diff --git a/packages/core/tests/io/formats/fig/instance/source-children.test.ts b/packages/core/tests/io/formats/fig/instance/source-children.test.ts
new file mode 100644
index 000000000..c185661c0
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/instance/source-children.test.ts
@@ -0,0 +1,78 @@
+import { expect, test } from 'bun:test'
+
+import { interpretComponent } from '@open-pencil/fig/instance-overrides'
+import {
+ linkInstanceSourceChildren,
+ mapInstanceSourceChildren
+} from '@open-pencil/fig/instance-overrides'
+
+import { FigmaAPI } from '@open-pencil/core'
+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { interpretInstance, materializeInstance } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { guid } from '../../../../helpers/fig/guid'
+
+test('derives repeated nested child correspondence from materialized component occurrences', async () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1), position: '!' },
+ textData: { characters: 'Label' }
+ },
+ { guid: guid(3), type: 'SYMBOL' },
+ ...[4, 5].map((id) => ({
+ guid: guid(id),
+ type: 'INSTANCE' as const,
+ parentIndex: { guid: guid(3), position: String(id) },
+ symbolData: { symbolID: guid(1) }
+ })),
+ { guid: guid(6), type: 'INSTANCE', symbolData: { symbolID: guid(3) } }
+ ]
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const inner = interpretComponent(changes, '1:1')
+ const innerGraph = materializeInstance(graph, page.id, inner, new Map())
+ const components = new Map([['1:1', { occurrence: inner, materialized: innerGraph }]])
+ const ids = new Map([['1:1', innerGraph.root.id]])
+ const outer = interpretComponent(changes, '1:3')
+ const outerGraph = materializeInstance(graph, page.id, outer, ids, {
+ sourceChildren: mapInstanceSourceChildren(outer, components)
+ })
+ components.set('1:3', { occurrence: outer, materialized: outerGraph })
+ ids.set('1:3', outerGraph.root.id)
+ const occurrence = interpretInstance(changes, '1:6')
+ const mapping = mapInstanceSourceChildren(occurrence, components)
+ const result = materializeInstance(graph, page.id, occurrence, ids, { sourceChildren: mapping })
+ const [first, second] = occurrence.children
+ expect(mapping.get(first)).not.toBe(mapping.get(second))
+ expect(mapping.get(first.children[0])).toBe(mapping.get(second.children[0]))
+ const before = graph.getChildren(result.root.id).map((node) => node.id)
+ linkInstanceSourceChildren(occurrence, result, components)
+ graph.syncInstances(outerGraph.root.id)
+ expect(graph.getChildren(result.root.id).map((node) => node.id)).toEqual(before)
+ expect(
+ graph.getChildren(result.root.id).map((node) => graph.getChildren(node.id).length)
+ ).toEqual([1, 1])
+ const api = new FigmaAPI(graph)
+ const firstLabel = result.nodes.get(first.children[0])
+ const secondLabel = result.nodes.get(second.children[0])
+ if (!firstLabel || !secondLabel) throw new Error('Missing labels')
+ api.wrapNode(firstLabel.id).characters = 'First occurrence'
+ api.wrapNode(secondLabel.id).characters = 'Second occurrence'
+ graph.updateNode(result.root.id, { name: 'Repeated instances acceptance' })
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const restored = await parseFigFile(bytes.buffer as ArrayBuffer)
+ const root = [...restored.getAllNodes()].find(
+ (node) => node.name === 'Repeated instances acceptance'
+ )
+ if (!root) throw new Error('Missing restored root')
+ expect(
+ restored.getChildren(root.id).map((child) => restored.getChildren(child.id)[0]?.text)
+ ).toEqual(['First occurrence', 'Second occurrence'])
+})
diff --git a/packages/core/tests/io/formats/fig/roundtrip/archive-assembly.test.ts b/packages/core/tests/io/formats/fig/roundtrip/archive-assembly.test.ts
new file mode 100644
index 000000000..96826c3ce
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/roundtrip/archive-assembly.test.ts
@@ -0,0 +1,22 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { materializeDocument, materializeFigArchive, parseFigBuffer } from '@open-pencil/fig'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('archive-owned assembly matches record-based assembly and isolates returned graphs', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('TEXT', source.getPages()[0].id, { name: 'Label', text: 'Original' })
+ const bytes = await exportFigFile(source)
+ const parsed = parseFigBuffer(bytes.buffer as ArrayBuffer)
+ const copied = materializeDocument(parsed.nodeChanges, parsed.blobs)
+ const owned = materializeFigArchive(bytes.buffer as ArrayBuffer)
+ const text = (graph: SceneGraph) => [...graph.getAllNodes()].find((node) => node.type === 'TEXT')
+ expect(text(owned.graph)?.text).toBe(text(copied.graph)?.text)
+ const node = text(owned.graph)
+ if (!node) throw new Error('Missing text')
+ owned.graph.updateNode(node.id, { text: 'Changed' })
+ expect(text(materializeFigArchive(bytes.buffer as ArrayBuffer).graph)?.text).toBe('Original')
+})
diff --git a/packages/core/tests/io/formats/fig/session/document-session.test.ts b/packages/core/tests/io/formats/fig/session/document-session.test.ts
new file mode 100644
index 000000000..d5d520a15
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/document-session.test.ts
@@ -0,0 +1,166 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { createFigDocumentSession, materializeFigArchive } from '@open-pencil/fig'
+import { SceneGraph, CommittedGraphEventError } from '@open-pencil/scene-graph'
+
+test('a mid-load creation failure leaves existing nodes and loaded pages unchanged', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('TEXT', source.getPages()[0].id, { name: 'First' })
+ source.createNode('TEXT', source.getPages()[0].id, { name: 'Second' })
+ const bytes = await exportFigFile(source)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ const before = [...session.graph.getAllNodes()].map((node) => ({
+ id: node.id,
+ children: [...node.childIds]
+ }))
+ const created: string[] = []
+ session.graph.onNodeEvents({ created: (node) => created.push(node.id) })
+ const create = session.graph.createNode.bind(session.graph)
+ let calls = 0
+ session.graph.createNode = (...args) => {
+ if (++calls === 2) throw new Error('Injected creation failure')
+ return create(...args)
+ }
+ try {
+ expect(() => session.loadPage(session.pages[0].id)).toThrow('Injected creation failure')
+ } finally {
+ session.graph.createNode = create
+ }
+ expect(
+ [...session.graph.getAllNodes()].map((node) => ({ id: node.id, children: [...node.childIds] }))
+ ).toEqual(before)
+ expect(created).toEqual([])
+ expect(session.loadedPageIds.size).toBe(0)
+ session.loadPage(session.pages[0].id)
+ expect([...session.graph.getAllNodes()].filter((node) => node.type === 'TEXT')).toHaveLength(2)
+})
+
+test('creation observers see committed pages and can load another page reentrantly', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('TEXT', source.getPages()[0].id, { name: 'First' })
+ source.createNode('TEXT', source.addPage('Second').id, { name: 'Second' })
+ const bytes = await exportFigFile(source)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ let committed = false
+ session.graph.onNodeEvents({
+ created: (node) => {
+ if (node.name !== 'First') return
+ committed = session.loadedPageIds.has(session.pages[0].id)
+ session.loadPage(session.pages[1].id)
+ }
+ })
+ session.loadPage(session.pages[0].id)
+ expect(committed).toBe(true)
+ expect(session.loadedPageIds.size).toBe(2)
+ expect([...session.graph.getAllNodes()].filter((node) => node.type === 'TEXT')).toHaveLength(2)
+})
+
+test('observer errors identify a committed load and retry does not duplicate nodes', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('TEXT', source.getPages()[0].id, { name: 'Loaded' })
+ const bytes = await exportFigFile(source)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ session.graph.onNodeEvents({
+ created: () => {
+ throw new Error('Observer failure')
+ }
+ })
+ let error: unknown
+ try {
+ session.loadPage(session.pages[0].id)
+ } catch (caught) {
+ error = caught
+ }
+ expect(error).toBeInstanceOf(CommittedGraphEventError)
+ if (!(error instanceof CommittedGraphEventError)) throw new Error('Expected committed error')
+ expect(error.committed).toBe(true)
+ expect(session.loadedPageIds.has(session.pages[0].id)).toBe(true)
+ expect(() => session.loadPage(session.pages[0].id)).not.toThrow()
+ expect([...session.graph.getAllNodes()].filter((node) => node.type === 'TEXT')).toHaveLength(1)
+})
+
+test('full and reverse-order incremental loads produce equivalent page trees', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ const first = source.getPages()[0]
+ const second = source.addPage('Components')
+ const component = source.createNode('COMPONENT', second.id, { name: 'Shared' })
+ source.createNode('TEXT', component.id, { text: 'Label' })
+ source.createInstance(component.id, first.id)
+ source.createNode('RECTANGLE', first.id, { name: 'Sibling', width: 80 })
+ const bytes = await exportFigFile(source)
+ const eager = materializeFigArchive(bytes.buffer as ArrayBuffer).graph
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ for (const page of [...session.pages].reverse()) session.loadPage(page.id)
+ const snapshot = (graph: SceneGraph) => {
+ const rows: unknown[] = []
+ const visit = (id: string, path: number[]): void => {
+ const node = graph.getNode(id)
+ if (!node) throw new Error('Missing node')
+ rows.push({
+ path,
+ type: node.type,
+ name: node.name,
+ text: node.text,
+ width: node.width,
+ height: node.height,
+ component: node.componentId ? graph.getNode(node.componentId)?.name : null
+ })
+ graph.getChildren(id).forEach((child, index) => visit(child.id, [...path, index]))
+ }
+ graph.getPages().forEach((page, index) => visit(page.id, [index]))
+ return rows
+ }
+ expect(snapshot(session.graph)).toEqual(snapshot(eager))
+ const before = snapshot(session.graph)
+ expect(() => session.loadPage('missing')).toThrow('Unknown page')
+ expect(snapshot(session.graph)).toEqual(before)
+ expect(session.loadedPageIds.size).toBe(2)
+})
+
+test('loading another page preserves existing node identity and text edits', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ graph.createNode('TEXT', graph.getPages()[0].id, { name: 'First', text: 'Original' })
+ const secondPage = graph.addPage('Second')
+ graph.createNode('TEXT', secondPage.id, { name: 'Second', text: 'Second' })
+ const component = graph.createNode('COMPONENT', secondPage.id, { name: 'Shared component' })
+ graph.createNode('TEXT', component.id, { text: 'Default' })
+ graph.createInstance(component.id, graph.getPages()[0].id)
+ graph.createInstance(component.id, secondPage.id)
+ const bytes = await exportFigFile(graph)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ expect([...session.graph.getAllNodes()].filter((n) => n.type === 'TEXT')).toHaveLength(0)
+ session.loadPage(session.pages[0].id)
+ const first = [...session.graph.getAllNodes()].find((n) => n.name === 'First')
+ if (!first) throw new Error('Missing first node')
+ session.graph.updateNode(first.id, { text: 'Edited' })
+ const existingComponent = [...session.graph.getAllNodes()].find(
+ (node) => node.type === 'COMPONENT'
+ )
+ if (!existingComponent) throw new Error('Missing dependency component')
+ session.graph.updateNode(existingComponent.id, { name: 'Edited component' })
+ const collection = session.graph.createCollection('Local')
+ const variable = session.graph.createVariable('Width', 'FLOAT', collection.id, 200)
+ session.graph.updateNode(first.id, { width: 123, boundVariables: { width: variable.id } })
+ const firstPage = session.graph.getPages()[0]
+ firstPage.childIds.reverse()
+ const editedOrder = [...firstPage.childIds]
+ session.loadPage(session.pages[1].id)
+ expect(firstPage.childIds).toEqual(editedOrder)
+ session.loadPage(session.pages[0].id)
+ expect(session.graph.getNode(first.id)).toBe(first)
+ expect(first.text).toBe('Edited')
+ expect(first.width).toBe(123)
+ expect(session.graph.getNode(existingComponent.id)).toBe(existingComponent)
+ expect(existingComponent.name).toBe('Edited component')
+ expect([...session.graph.getAllNodes()].filter((node) => node.type === 'COMPONENT')).toHaveLength(
+ 1
+ )
+ expect([...session.graph.getAllNodes()].filter((n) => n.type === 'TEXT')).toHaveLength(5)
+})
diff --git a/packages/core/tests/io/formats/fig/session/document-state.test.ts b/packages/core/tests/io/formats/fig/session/document-state.test.ts
new file mode 100644
index 000000000..1b69fdf9d
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/document-state.test.ts
@@ -0,0 +1,110 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { serializeSceneGraph, deserializeSceneGraph } from '#core/kiwi/fig/parse/transfer'
+import {
+ createPopulationWorkerClient,
+ registerFigPopulationWorker,
+ releaseFigPopulationWorker
+} from '#core/kiwi/fig/population/client'
+import { applyFigPopulationDelta } from '#core/kiwi/fig/population/delta'
+import {
+ registerReaderRecovery,
+ updateReaderRecovery,
+ recoverReaderPage
+} from '#core/kiwi/fig/session/document-state'
+import type { FigSessionPopulateRequest, FigSessionResponse } from '#core/kiwi/fig/session/protocol'
+import { openReaderSession } from '#core/kiwi/fig/session/reader'
+
+test('rejected worker response cannot mark an unloaded page loaded in recovery', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('RECTANGLE', source.getPages()[0].id, { name: 'First' })
+ source.createNode('RECTANGLE', source.addPage('Second').id, { name: 'Second node' })
+ const bytes = await exportFigFile(source)
+ const backend = openReaderSession(bytes.buffer as ArrayBuffer, 'first-page')
+ const graph = deserializeSceneGraph(serializeSceneGraph(backend.graph))
+ registerReaderRecovery(graph, bytes.buffer as ArrayBuffer, structuredClone(backend.checkpoint()))
+ let request: FigSessionPopulateRequest | undefined
+ const port = {
+ onmessage: null as ((event: MessageEvent<FigSessionResponse>) => void) | null,
+ start: () => undefined,
+ close: () => undefined,
+ postMessage: (message: FigSessionPopulateRequest) => {
+ request = message
+ }
+ }
+ const worker = {
+ terminate: () => undefined,
+ postMessage: () => undefined,
+ onerror: null,
+ onmessage: null
+ }
+ const client = createPopulationWorkerClient(graph, worker, port)
+ const pageId = graph.getPages()[1].id
+ try {
+ const pending = client.populate(pageId)
+ if (!request) throw new Error('Missing request')
+ const result = backend.populate(pageId)
+ graph.updateNode(graph.rootId, { name: 'Edited locally' })
+ port.onmessage?.({
+ data: {
+ type: 'population-result',
+ requestId: request.requestId,
+ baseRevision: request.baseRevision,
+ ...structuredClone(result)
+ }
+ } as MessageEvent<FigSessionResponse>)
+ expect(await pending).toBeNull()
+ expect(graph.getChildren(pageId)).toHaveLength(0)
+ expect(recoverReaderPage(graph, pageId)).toBe(true)
+ expect(graph.getChildren(pageId)[0].name).toBe('Second node')
+ expect(graph.getNode(graph.rootId)?.name).toBe('Edited locally')
+ } finally {
+ client.terminate()
+ releaseFigPopulationWorker(graph)
+ }
+})
+
+test('page preparation recovers an invalidated replacement worker without replacing edited graph', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('RECTANGLE', source.getPages()[0].id, { name: 'First' })
+ source.createNode('RECTANGLE', source.addPage('Second').id, { name: 'Second node' })
+ source.createNode('RECTANGLE', source.addPage('Third').id, { name: 'Third node' })
+ const bytes = await exportFigFile(source)
+ const backend = openReaderSession(bytes.buffer as ArrayBuffer, 'first-page')
+ const graph = deserializeSceneGraph(serializeSceneGraph(backend.graph))
+ registerReaderRecovery(graph, bytes.buffer as ArrayBuffer, structuredClone(backend.checkpoint()))
+ const secondResult = backend.populate(graph.getPages()[1].id)
+ applyFigPopulationDelta(graph, structuredClone(secondResult.delta))
+ if (!secondResult.checkpoint) throw new Error('Missing checkpoint')
+ updateReaderRecovery(graph, structuredClone(secondResult.checkpoint))
+ const secondNode = graph.getChildren(graph.getPages()[1].id)[0]
+ const worker = {
+ terminate: () => undefined,
+ postMessage: () => undefined,
+ onerror: null,
+ onmessage: null
+ } as Worker
+ registerFigPopulationWorker(graph, worker)
+ const editor = createEditor({ graph })
+ const first = graph.getChildren(graph.getPages()[0].id)[0]
+ graph.updateNode(first.id, { name: 'Edited' })
+ try {
+ await editor.preparePage(graph.getPages()[2].id)
+ expect(graph.getChildren(graph.getPages()[1].id)).toEqual([secondNode])
+ expect(graph.getChildren(graph.getPages()[2].id)[0].name).toBe('Third node')
+ expect(editor.graph).toBe(graph)
+ expect(graph.getNode(first.id)).toBe(first)
+ expect(first.name).toBe('Edited')
+ expect(graph.getChildren(graph.getPages()[1].id)[0].name).toBe('Second node')
+ } finally {
+ releaseFigPopulationWorker(graph)
+ }
+ expect(() => recoverReaderPage(graph, graph.getPages()[2].id)).toThrow('No reader recovery state')
+})
diff --git a/packages/core/tests/io/formats/fig/session/main-thread.test.ts b/packages/core/tests/io/formats/fig/session/main-thread.test.ts
new file mode 100644
index 000000000..db1a16a2e
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/main-thread.test.ts
@@ -0,0 +1,119 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import {
+ parseFigFile,
+ populateFigPage,
+ populateAllFigPages
+} from '@open-pencil/core/io/formats/fig'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { releaseFigPopulationWorker } from '#core/kiwi/fig/population/client'
+import { hasReaderSession } from '#core/kiwi/fig/session/document-state'
+
+async function fixture(missingInternalDefault = false) {
+ await initCodec()
+ const graph = new SceneGraph()
+ graph.createNode('TEXT', graph.getPages()[0].id, { text: 'First' })
+ graph.createNode('TEXT', graph.addPage('Second').id, { text: 'Second' })
+ const internal = graph.addPage('Internal resources')
+ graph.updateNode(internal.id, { internalOnly: true })
+ graph.createNode('RECTANGLE', internal.id, { name: 'Retained internal content', width: 37 })
+ if (missingInternalDefault) {
+ graph.createNode('COMPONENT', internal.id, {
+ name: 'Invalid internal component',
+ componentPropertyDefinitions: [
+ {
+ id: '10:1',
+ name: 'Choice',
+ type: 'INSTANCE_SWAP',
+ defaultValue: '999:999'
+ }
+ ]
+ })
+ }
+ const bytes = await exportFigFile(graph)
+ return bytes.slice().buffer as ArrayBuffer
+}
+
+for (const populate of ['all', 'first-page', 'none'] as const) {
+ test(`main-thread reader retains a live session for ${populate}`, async () => {
+ const manifests: string[][] = []
+ const graph = await parseFigFile(await fixture(), {
+ populate,
+ onPages: (pages) => manifests.push(pages.map((page) => page.name))
+ })
+ const pages = graph.getPages()
+ expect(pages).toHaveLength(2)
+ expect(graph.getPages(true)).toHaveLength(3)
+ expect(
+ graph.getPages(true).find((page) => page.name === 'Internal resources')?.internalOnly
+ ).toBe(true)
+ expect(manifests).toHaveLength(1)
+ expect(manifests[0]).toContain('Second')
+ expect(hasReaderSession(graph)).toBe(true)
+ expect(graph.figSchemaDeflated).not.toBeNull()
+ expect(graph.getChildren(pages[0].id)).toHaveLength(populate === 'none' ? 0 : 1)
+ expect(graph.getChildren(pages[1].id)).toHaveLength(populate === 'all' ? 1 : 0)
+ expect(populateAllFigPages(graph)).toBe(populate !== 'all')
+ const first = graph.getChildren(pages[0].id)[0]
+ graph.updateNode(first.id, { text: 'Edited' })
+ expect(populateFigPage(graph, pages[0].id)).toBe(false)
+ expect(graph.getNode(first.id)).toBe(first)
+ expect(first.text).toBe('Edited')
+ expect(populateAllFigPages(graph)).toBe(false)
+ expect(graph.getChildren(pages[1].id)[0].text).toBe('Second')
+ expect(populateFigPage(graph, 'missing')).toBe(false)
+ releaseFigPopulationWorker(graph)
+ expect(hasReaderSession(graph)).toBe(false)
+ })
+}
+
+test('edited export loads missing pages on an isolated graph', async () => {
+ const graph = await parseFigFile(await fixture(), { populate: 'first-page' })
+ const pages = graph.getPages()
+ const first = graph.getChildren(pages[0].id)[0]
+ graph.updateNode(first.id, { text: 'Edited' })
+ const before = structuredClone([...graph.nodes])
+ const bytes = await exportFigFile(graph)
+ expect([...graph.nodes]).toEqual(before)
+ expect(graph.getChildren(pages[1].id)).toHaveLength(0)
+ const reopened = await parseFigFile(bytes.slice().buffer as ArrayBuffer)
+ const reopenedPages = reopened.getPages()
+ expect(reopened.getChildren(reopenedPages[0].id)[0].text).toBe('Edited')
+ expect(reopened.getChildren(reopenedPages[1].id)[0].text).toBe('Second')
+ const internal = reopened.getPages(true).find((page) => page.internalOnly)
+ if (!internal) throw new Error('Missing internal page')
+ expect(populateFigPage(reopened, internal.id)).toBe(true)
+ expect(reopened.getChildren(internal.id).map((node) => [node.name, node.width])).toEqual([
+ ['Retained internal content', 37]
+ ])
+ expect(populateFigPage(graph, pages[1].id)).toBe(true)
+ releaseFigPopulationWorker(graph)
+ releaseFigPopulationWorker(reopened)
+})
+
+// Figma keeps property defaults that name a deleted component; so does an edited export.
+test('export tolerates a deleted internal default without changing the live graph', async () => {
+ const graph = await parseFigFile(await fixture(true), { populate: 'first-page' })
+ const page = graph.getPages()[0]
+ graph.updateNode(page.id, { name: 'Edited' })
+ const before = structuredClone([...graph.nodes])
+ const bytes = await exportFigFile(graph)
+ expect(bytes.byteLength).toBeGreaterThan(0)
+ expect([...graph.nodes]).toEqual(before)
+ releaseFigPopulationWorker(graph)
+})
+
+test('page population is a no-op for non-FIG documents', () => {
+ const graph = new SceneGraph()
+ expect(populateFigPage(graph, graph.getPages()[0].id)).toBe(false)
+ expect(populateAllFigPages(graph)).toBe(false)
+})
+
+test('main-thread parse honors pre-aborted requests', async () => {
+ const controller = new AbortController()
+ controller.abort()
+ await expect(parseFigFile(await fixture(), { signal: controller.signal })).rejects.toThrow()
+})
diff --git a/packages/core/tests/io/formats/fig/session/nested-edits.test.ts b/packages/core/tests/io/formats/fig/session/nested-edits.test.ts
new file mode 100644
index 000000000..814911f09
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/nested-edits.test.ts
@@ -0,0 +1,35 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { createFigDocumentSession } from '@open-pencil/fig'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('outer component edits win over inner defaults for later-loaded nested instance roots', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ const first = source.getPages()[0]
+ const second = source.addPage('Second')
+ const inner = source.createNode('COMPONENT', first.id, { name: 'Inner', opacity: 1 })
+ const outer = source.createNode('COMPONENT', first.id, { name: 'Outer' })
+ source.createInstance(inner.id, outer.id)
+ source.createInstance(outer.id, second.id)
+ const bytes = await exportFigFile(source)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ session.loadPage(session.pages[0].id)
+ const graph = session.graph
+ const liveInner = [...graph.getAllNodes()].find(
+ (node) => node.type === 'COMPONENT' && node.name === 'Inner'
+ )
+ const liveOuter = [...graph.getAllNodes()].find(
+ (node) => node.type === 'COMPONENT' && node.name === 'Outer'
+ )
+ if (!liveInner || !liveOuter) throw new Error('Missing components')
+ graph.updateNode(liveInner.id, { opacity: 0.3 })
+ graph.updateNode(graph.getChildren(liveOuter.id)[0].id, { opacity: 0.6 })
+ session.loadPage(session.pages[1].id)
+ const pageId = session.graphPageId(session.pages[1].id)
+ if (!pageId) throw new Error('Missing second page')
+ const instance = graph.getChildren(pageId)[0]
+ expect(graph.getChildren(instance.id)[0].opacity).toBe(0.6)
+})
diff --git a/packages/core/tests/io/formats/fig/session/new-page.test.ts b/packages/core/tests/io/formats/fig/session/new-page.test.ts
new file mode 100644
index 000000000..70c30182e
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/new-page.test.ts
@@ -0,0 +1,20 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { exportFigFile, parseFigFile, populateFigPage } from '@open-pencil/core/io/formats/fig'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('new pages in reader-backed graphs are live and never queried from the archive', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('RECTANGLE', source.getPages()[0].id)
+ const graph = await parseFigFile((await exportFigFile(source)).slice().buffer as ArrayBuffer, {
+ populate: 'none'
+ })
+ const page = graph.addPage('New page')
+ expect(populateFigPage(graph, page.id)).toBe(false)
+ const editor = createEditor({ graph })
+ await expect(editor.switchPage(page.id)).resolves.toBeUndefined()
+ expect(editor.state.currentPageId).toBe(page.id)
+})
diff --git a/packages/core/tests/io/formats/fig/session/page-instance-sync.test.ts b/packages/core/tests/io/formats/fig/session/page-instance-sync.test.ts
new file mode 100644
index 000000000..6235e77a1
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/page-instance-sync.test.ts
@@ -0,0 +1,42 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { createFigDocumentSession } from '@open-pencil/fig'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+/**
+ * Syncing visits every instance of a component, so doing it per placed instance costs a
+ * pass over the whole graph for each one. A page placing many instances of one component
+ * must still sync it once.
+ */
+test('a resumed page load syncs each component once, not once per instance it places', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ const library = source.getPages()[0]
+ const component = source.createNode('COMPONENT', library.id, { name: 'Badge' })
+ source.createNode('TEXT', component.id, { name: 'Label', text: 'Badge' })
+ const page = source.addPage('Placed')
+ for (let index = 0; index < 8; index++) source.createInstance(component.id, page.id)
+ const bytes = await exportFigFile(source)
+
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ const synced: string[] = []
+ const syncInstances = session.graph.syncInstances.bind(session.graph)
+ session.graph.syncInstances = (componentId: string) => {
+ synced.push(componentId)
+ return syncInstances(componentId)
+ }
+ const placed = session.pages.find((candidate) => candidate.name === 'Placed')
+ if (!placed) throw new Error('Missing placed page')
+ session.loadPage(placed.id)
+
+ // One component placed eight times is one sync, not eight.
+ expect(synced.length).toBe(1)
+ const pageId = session.graphPageId(placed.id)
+ if (!pageId) throw new Error('Missing materialized page')
+ const instances = session.graph.getChildren(pageId)
+ expect(instances).toHaveLength(8)
+ for (const instance of instances)
+ expect(session.graph.getChildren(instance.id)[0].text).toBe('Badge')
+})
diff --git a/packages/core/tests/io/formats/fig/session/reader-backend.test.ts b/packages/core/tests/io/formats/fig/session/reader-backend.test.ts
new file mode 100644
index 000000000..ef09d24df
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/reader-backend.test.ts
@@ -0,0 +1,24 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { openReaderSession } from '#core/kiwi/fig/session/reader'
+
+test('replacement worker backend opens first page and populates by graph page ID', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ graph.createNode('TEXT', graph.getPages()[0].id, { text: 'First' })
+ graph.createNode('TEXT', graph.addPage('Second').id, { text: 'Second' })
+ const bytes = await exportFigFile(graph)
+ const session = openReaderSession(bytes.buffer as ArrayBuffer, 'first-page')
+ const pages = session.graph.getPages()
+ expect(session.graph.getChildren(pages[0].id)).toHaveLength(1)
+ expect(session.graph.getChildren(pages[1].id)).toHaveLength(0)
+ expect(session.graph.figSchemaDeflated).not.toBeNull()
+ expect(session.populate(pages[1].id).populated).toBe(true)
+ expect(session.graph.getChildren(pages[1].id)[0].text).toBe('Second')
+ expect(session.populate(pages[1].id).populated).toBe(false)
+ expect(() => session.populate('missing')).toThrow('Unknown graph page')
+})
diff --git a/packages/core/tests/io/formats/fig/session/reader-delta.test.ts b/packages/core/tests/io/formats/fig/session/reader-delta.test.ts
new file mode 100644
index 000000000..b4f8758fd
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/reader-delta.test.ts
@@ -0,0 +1,94 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { createFigDocumentSession } from '@open-pencil/fig'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { serializeSceneGraph, deserializeSceneGraph } from '#core/kiwi/fig/parse/transfer'
+import {
+ installFigMutationJournal,
+ buildFigPopulationDelta,
+ applyFigPopulationDelta
+} from '#core/kiwi/fig/population/delta'
+
+test('new-reader page loads transfer through the worker delta contract', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('TEXT', source.getPages()[0].id, { text: 'Transferred', name: 'Label' })
+ const library = source.addPage('Library')
+ const component = source.createNode('COMPONENT', library.id, { name: 'Shared' })
+ source.createNode('TEXT', component.id, { text: 'Default' })
+ source.createInstance(component.id, source.getPages()[0].id)
+ source.createInstance(component.id, library.id)
+ const bytes = await exportFigFile(source)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ const receiver = deserializeSceneGraph(serializeSceneGraph(session.graph))
+ const pageId = session.graphPageId(session.pages[0].id)
+ if (!pageId) throw new Error('Missing graph page')
+ const journal = installFigMutationJournal(session.graph)
+ try {
+ session.loadPage(session.pages[0].id)
+ const delta = buildFigPopulationDelta(session.graph, journal, [pageId])
+ applyFigPopulationDelta(receiver, structuredClone(delta))
+ expect(
+ receiver
+ .getChildren(pageId)
+ .filter((node) => node.type === 'TEXT')
+ .map((node) => node.text)
+ ).toEqual(['Transferred'])
+ const receivedComponent = [...receiver.getAllNodes()].find((node) => node.type === 'COMPONENT')
+ if (!receivedComponent) throw new Error('Missing component dependency')
+ const instance = receiver.getChildren(pageId).find((node) => node.type === 'INSTANCE')
+ expect(instance?.componentId).toBe(receivedComponent.id)
+ expect(receiver.instanceIndex.get(receivedComponent.id)?.has(instance?.id ?? '')).toBe(true)
+ expect(receiver.getChildren(pageId).map((node) => node.id)).toEqual(
+ session.graph.getChildren(pageId).map((node) => node.id)
+ )
+ } finally {
+ journal.stop()
+ }
+ const existingComponent = [...receiver.getAllNodes()].find((node) => node.type === 'COMPONENT')
+ if (!existingComponent) throw new Error('Missing shared component')
+ receiver.updateNode(existingComponent.id, { name: 'Receiver edit' })
+ const localInstance = receiver.createInstance(existingComponent.id, pageId)
+ if (!localInstance) throw new Error('Missing locally created instance')
+ const recoveryGraph = deserializeSceneGraph(serializeSceneGraph(receiver))
+ const recoveredComponent = recoveryGraph.getNode(existingComponent.id)
+ const resumed = createFigDocumentSession(
+ bytes.buffer as ArrayBuffer,
+ {},
+ {
+ graph: recoveryGraph,
+ checkpoint: structuredClone(session.checkpoint())
+ }
+ )
+ resumed.loadPage(resumed.pages[1].id)
+ expect(recoveredComponent?.name).toBe('Receiver edit')
+ expect(recoveryGraph.getNode(existingComponent.id)).toBe(recoveredComponent)
+ expect([...recoveryGraph.getAllNodes()].filter((node) => node.type === 'COMPONENT')).toHaveLength(
+ 1
+ )
+ expect(recoveryGraph.instanceIndex.get(existingComponent.id)?.has(localInstance.id)).toBe(true)
+ const secondJournal = installFigMutationJournal(session.graph)
+ try {
+ session.loadPage(session.pages[1].id)
+ applyFigPopulationDelta(
+ receiver,
+ structuredClone(
+ buildFigPopulationDelta(
+ session.graph,
+ secondJournal,
+ session.graph.getPages().map((page) => page.id)
+ )
+ )
+ )
+ expect(receiver.getNode(existingComponent.id)).toBe(existingComponent)
+ expect(existingComponent.name).toBe('Receiver edit')
+ expect([...receiver.getAllNodes()].filter((node) => node.type === 'COMPONENT')).toHaveLength(1)
+ expect(receiver.instanceIndex.get(existingComponent.id)?.size).toBe(3)
+ expect(receiver.instanceIndex.get(existingComponent.id)?.has(localInstance.id)).toBe(true)
+ } finally {
+ secondJournal.stop()
+ }
+})
diff --git a/packages/core/tests/io/formats/fig/session/stale-delta.test.ts b/packages/core/tests/io/formats/fig/session/stale-delta.test.ts
new file mode 100644
index 000000000..e78c678e4
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/stale-delta.test.ts
@@ -0,0 +1,84 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { createPopulationWorkerClient } from '#core/kiwi/fig/population/client'
+import type { FigSessionPopulateRequest, FigSessionResponse } from '#core/kiwi/fig/session/protocol'
+
+test('aborting a population request terminates its transport and ignores late results', async () => {
+ const graph = new SceneGraph()
+ let terminated = false
+ const port = {
+ onmessage: null as ((event: MessageEvent<FigSessionResponse>) => void) | null,
+ postMessage: () => undefined,
+ start: () => undefined,
+ close: () => undefined
+ }
+ const worker = {
+ terminate: () => {
+ terminated = true
+ },
+ postMessage: () => undefined,
+ onerror: null,
+ onmessage: null
+ }
+ const client = createPopulationWorkerClient(graph, worker, port)
+ const controller = new AbortController()
+ const pending = client.populate(graph.getPages()[0].id, controller.signal)
+ controller.abort()
+ await expect(pending).rejects.toThrow('Aborted')
+ expect(terminated).toBe(true)
+ expect(await client.populate(graph.getPages()[0].id)).toBeNull()
+ client.terminate()
+})
+
+for (const mutation of ['local-child', 'reorder', 'wrong-revision'] as const) {
+ test(`rejects population deltas after ${mutation}`, async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const first = graph.createNode('RECTANGLE', page.id)
+ const second = graph.createNode('RECTANGLE', page.id)
+ let request: FigSessionPopulateRequest | undefined
+ const port = {
+ onmessage: null as ((event: MessageEvent<FigSessionResponse>) => void) | null,
+ start: () => undefined,
+ close: () => undefined,
+ postMessage(message: FigSessionPopulateRequest) {
+ request = message
+ }
+ }
+ const worker = {
+ terminate: () => undefined,
+ postMessage: () => undefined,
+ onerror: null,
+ onmessage: null
+ }
+ const client = createPopulationWorkerClient(graph, worker, port)
+ try {
+ const pending = client.populate(page.id)
+ if (!request) throw new Error('Missing request')
+ if (mutation === 'local-child') graph.createNode('RECTANGLE', page.id)
+ if (mutation === 'reorder') graph.insertChildAt(second.id, page.id, 0)
+ const expected = [...page.childIds]
+ port.onmessage?.({
+ data: {
+ type: 'population-result',
+ requestId: request.requestId,
+ baseRevision: request.baseRevision + (mutation === 'wrong-revision' ? 1 : 0),
+ populated: true,
+ delta: {
+ created: [],
+ updated: [[page.id, { childIds: [first.id] }]],
+ deleted: [],
+ instanceIndex: [],
+ populatedRootIds: [page.id]
+ }
+ }
+ } as MessageEvent<FigSessionResponse>)
+ expect(await pending).toBeNull()
+ expect(page.childIds).toEqual(expected)
+ } finally {
+ client.terminate()
+ }
+ })
+}
diff --git a/packages/core/tests/io/formats/fig/session/structural-edits.test.ts b/packages/core/tests/io/formats/fig/session/structural-edits.test.ts
new file mode 100644
index 000000000..846f86a92
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/structural-edits.test.ts
@@ -0,0 +1,45 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { createFigDocumentSession } from '@open-pencil/fig'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+for (const mutation of ['delete', 'reorder', 'add'] as const) {
+ test(`later loads preserve live ${mutation} of component children`, async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ const first = source.getPages()[0]
+ const second = source.addPage('Second')
+ const component = source.createNode('COMPONENT', first.id)
+ source.createNode('RECTANGLE', component.id, { name: 'A' })
+ source.createNode('RECTANGLE', component.id, { name: 'B' })
+ source.createInstance(component.id, second.id)
+ const bytes = await exportFigFile(source)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ session.loadPage(session.pages[0].id)
+ const live = [...session.graph.getAllNodes()].find((node) => node.type === 'COMPONENT')
+ if (!live) throw new Error('Missing component')
+ if (mutation === 'delete') session.graph.deleteNode(live.childIds[0])
+ else if (mutation === 'reorder') session.graph.insertChildAt(live.childIds[1], live.id, 0)
+ else session.graph.createNode('ELLIPSE', live.id, { name: 'C' })
+ const before = structuredClone([...session.graph.nodes])
+ session.loadPage(session.pages[1].id)
+ expect(session.loadedPageIds.has(session.pages[1].id)).toBe(true)
+ const after = session.graph.getNode(live.id)
+ if (mutation === 'delete') expect(after?.childIds).toHaveLength(1)
+ else if (mutation === 'add') {
+ expect(after?.childIds).toHaveLength(3)
+ const placed = session.graph
+ .getAllNodes()
+ .find(
+ (node) => node.type === 'INSTANCE' && node.parentId === session.graph.getPages()[1].id
+ )
+ expect(placed && session.graph.getChildren(placed.id).map((node) => node.name)).toEqual([
+ 'A',
+ 'B',
+ 'C'
+ ])
+ } else expect(after?.childIds).toEqual(before.find(([id]) => id === live.id)?.[1].childIds)
+ })
+}
diff --git a/packages/core/tests/io/formats/fig/session/structural-export.test.ts b/packages/core/tests/io/formats/fig/session/structural-export.test.ts
new file mode 100644
index 000000000..8ac293104
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/structural-export.test.ts
@@ -0,0 +1,24 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile, initCodec } from '@open-pencil/core'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { openReaderSession } from '#core/kiwi/fig/session/reader'
+
+async function sessionWithComponent() {
+ await initCodec()
+ const source = new SceneGraph()
+ const component = source.createNode('COMPONENT', source.getPages()[0].id, { name: 'Component' })
+ source.createNode('RECTANGLE', component.id, { name: 'Delete me' })
+ const bytes = await exportFigFile(source)
+ return openReaderSession(bytes.slice().buffer as ArrayBuffer, 'all')
+}
+
+test('loaded structural component edits can be checkpointed and exported', async () => {
+ const session = await sessionWithComponent()
+ const component = session.graph.getAllNodes().find((node) => node.name === 'Component')
+ if (!component) throw new Error('Missing component')
+ session.graph.deleteNode(session.graph.getChildren(component.id)[0].id)
+ expect(() => session.checkpoint()).not.toThrow()
+ await expect(exportFigFile(session.graph)).resolves.toBeInstanceOf(Uint8Array)
+})
diff --git a/packages/core/tests/io/formats/fig/session/unavailable-reader.test.ts b/packages/core/tests/io/formats/fig/session/unavailable-reader.test.ts
new file mode 100644
index 000000000..0af3bbbff
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/unavailable-reader.test.ts
@@ -0,0 +1,27 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+import {
+ registerFigPopulationWorker,
+ releaseFigPopulationWorker
+} from '#core/kiwi/fig/population/client'
+
+test('new live pages do not require unavailable reader recovery', async () => {
+ const editor = createEditor()
+ const page = editor.graph.addPage('Unloaded')
+ const worker = {
+ terminate: () => undefined,
+ postMessage: () => undefined,
+ onerror: null,
+ onmessage: null
+ } as Worker
+ registerFigPopulationWorker(editor.graph, worker)
+ editor.graph.updateNode(editor.graph.rootId, { name: 'User edit' })
+ try {
+ await expect(editor.preparePage(page.id)).resolves.toMatchObject({ pageId: page.id })
+ expect(editor.graph.getChildren(page.id)).toEqual([])
+ } finally {
+ releaseFigPopulationWorker(editor.graph)
+ }
+})
diff --git a/packages/core/tests/io/formats/fig/session/undo-redo.test.ts b/packages/core/tests/io/formats/fig/session/undo-redo.test.ts
new file mode 100644
index 000000000..7136ea430
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/undo-redo.test.ts
@@ -0,0 +1,161 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { createFigDocumentSession } from '@open-pencil/fig'
+import { SceneGraph, recordInstanceOverride } from '@open-pencil/scene-graph'
+
+test('a deleted source node stays deleted across resume and remains undoable', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('RECTANGLE', source.getPages()[0].id, { name: 'Delete me' })
+ source.createNode('RECTANGLE', source.addPage('Second').id, { name: 'Other' })
+ const bytes = await exportFigFile(source)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ session.loadPage(session.pages[0].id)
+ const graph = session.graph
+ const editor = createEditor({ graph })
+ const node = [...graph.getAllNodes()].find((node) => node.name === 'Delete me')
+ if (!node) throw new Error('Missing source node')
+ const checkpoint = session.checkpoint()
+ editor.select([node.id])
+ editor.deleteSelected()
+ expect(graph.getNode(node.id)).toBeUndefined()
+ const resumed = createFigDocumentSession(bytes.buffer as ArrayBuffer, {}, { graph, checkpoint })
+ resumed.loadPage(resumed.pages[1].id)
+ expect(graph.getNode(node.id)).toBeUndefined()
+ editor.undo.undo()
+ expect(graph.getNode(node.id)?.name).toBe('Delete me')
+ editor.undo.redo()
+ expect(graph.getNode(node.id)).toBeUndefined()
+})
+
+test('later page instances inherit edits to an already loaded component', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ const first = source.getPages()[0]
+ const second = source.addPage('Second')
+ const component = source.createNode('COMPONENT', first.id, { name: 'Shared' })
+ source.createNode('TEXT', component.id, { text: 'Original' })
+ source.createInstance(component.id, first.id)
+ source.createInstance(component.id, second.id)
+ const overridden = source.createInstance(component.id, second.id)
+ if (!overridden) throw new Error('Missing overridden instance')
+ const overriddenText = source.getChildren(overridden.id)[0]
+ source.updateNode(overriddenText.id, { text: 'Explicit' })
+ recordInstanceOverride(source, overriddenText.id, ['text'])
+ const bytes = await exportFigFile(source)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ session.loadPage(session.pages[0].id)
+ const graph = session.graph
+ const liveComponent = [...graph.getAllNodes()].find((node) => node.type === 'COMPONENT')
+ if (!liveComponent) throw new Error('Missing component')
+ const label = graph.getChildren(liveComponent.id)[0]
+ graph.updateNode(liveComponent.id, { opacity: 0.4 })
+ graph.updateNode(label.id, { text: 'Component edit' })
+ graph.syncInstances(liveComponent.id)
+ const checkpointBeforeSecondPage = session.checkpoint()
+ session.loadPage(session.pages[1].id)
+ const pageId = session.graphPageId(session.pages[1].id)
+ if (!pageId) throw new Error('Missing page')
+ const instance = graph.getChildren(pageId).find((node) => node.type === 'INSTANCE')
+ if (!instance) throw new Error('Missing instance')
+ expect(instance.opacity).toBe(0.4)
+ expect(graph.getChildren(instance.id)[0].text).toBe('Component edit')
+ expect(
+ graph
+ .getChildren(pageId)
+ .filter((node) => node.type === 'INSTANCE')
+ .map((node) => graph.getChildren(node.id)[0].text)
+ ).toEqual(['Component edit', 'Explicit'])
+ const beforeFailure = graph.nodes.size
+ graph.createNode('RECTANGLE', liveComponent.id, { name: 'Added child' })
+ const retry = createFigDocumentSession(
+ bytes.buffer as ArrayBuffer,
+ {},
+ { graph, checkpoint: checkpointBeforeSecondPage }
+ )
+ retry.loadPage(session.pages[1].id)
+ expect(graph.nodes.size).toBeGreaterThan(beforeFailure)
+ const added = graph.getChildren(liveComponent.id).find((node) => node.name === 'Added child')
+ expect(added).toBeDefined()
+ const retryPage = retry.graphPageId(session.pages[1].id)
+ const retryInstance =
+ retryPage && graph.getChildren(retryPage).find((node) => node.type === 'INSTANCE')
+ expect(
+ retryInstance && graph.getChildren(retryInstance.id).some((node) => node.name === 'Added child')
+ ).toBe(true)
+})
+
+test('loading a destination page preserves an existing reparented node', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('RECTANGLE', source.getPages()[0].id, { name: 'Moved' })
+ source.createNode('RECTANGLE', source.addPage('Second').id, { name: 'Other' })
+ const bytes = await exportFigFile(source)
+ const session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ session.loadPage(session.pages[0].id)
+ const graph = session.graph
+ const node = [...graph.getAllNodes()].find((node) => node.name === 'Moved')
+ const destination = session.graphPageId(session.pages[1].id)
+ if (!node || !destination) throw new Error('Missing nodes')
+ graph.reparentNode(node.id, destination)
+ session.loadPage(session.pages[1].id)
+ expect(graph.getNode(node.id)).toBe(node)
+ expect(node.parentId).toBe(destination)
+ expect(graph.getChildren(destination).filter((child) => child.id === node.id)).toHaveLength(1)
+})
+
+for (const resume of [false, true]) {
+ test(`page loading preserves editor undo/redo (resume=${resume})`, async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ const firstPage = source.getPages()[0]
+ const secondPage = source.addPage('Second')
+ const component = source.createNode('COMPONENT', secondPage.id, {
+ name: 'Card',
+ componentPropertyDefinitions: [
+ { id: '10:1', name: 'Shown', type: 'BOOLEAN', defaultValue: 'true' }
+ ]
+ })
+ source.createNode('RECTANGLE', component.id, {
+ name: 'Target',
+ componentPropertyReferences: [{ propertyId: '10:1', field: 'VISIBLE' }]
+ })
+ source.createInstance(component.id, firstPage.id)
+ source.createInstance(component.id, secondPage.id)
+ const bytes = await exportFigFile(source)
+ let session = createFigDocumentSession(bytes.buffer as ArrayBuffer)
+ session.loadPage(session.pages[0].id)
+ const graph = session.graph
+ const editor = createEditor({ graph })
+ const pageId = session.graphPageId(session.pages[0].id)
+ if (!pageId) throw new Error('Missing page')
+ const instance = graph.getChildren(pageId).find((node) => node.type === 'INSTANCE')
+ if (!instance) throw new Error('Missing instance')
+ const target = graph.getChildren(instance.id)[0]
+ editor.setInstanceComponentProperty(instance.id, '10:1', 'false')
+ expect(target.visible).toBe(false)
+ editor.undo.undo()
+ expect(target.visible).toBe(true)
+ if (resume)
+ session = createFigDocumentSession(
+ bytes.buffer as ArrayBuffer,
+ {},
+ { graph, checkpoint: session.checkpoint() }
+ )
+ session.loadPage(session.pages[1].id)
+ expect(editor.graph).toBe(graph)
+ expect(graph.getNode(target.id)).toBe(target)
+ editor.undo.redo()
+ expect(target.visible).toBe(false)
+ editor.undo.undo()
+ expect(target.visible).toBe(true)
+ const secondId = session.graphPageId(session.pages[1].id)
+ if (!secondId) throw new Error('Missing second page')
+ const second = graph.getChildren(secondId).find((node) => node.type === 'INSTANCE')
+ if (!second) throw new Error('Missing second instance')
+ expect(graph.getChildren(second.id)[0].visible).toBe(true)
+ })
+}
diff --git a/packages/core/tests/io/formats/fig/session/worker-reader.test.ts b/packages/core/tests/io/formats/fig/session/worker-reader.test.ts
new file mode 100644
index 000000000..14581d5d1
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/worker-reader.test.ts
@@ -0,0 +1,95 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import type { FigSessionResponse } from '#core/kiwi/fig/session/protocol'
+
+test.each(['first-page', 'none'] as const)(
+ 'session worker opens and populates with %s',
+ async (populate) => {
+ await initCodec()
+ const graph = new SceneGraph()
+ graph.createNode('TEXT', graph.getPages()[0].id, { text: 'First' })
+ graph.createNode('TEXT', graph.addPage('Second').id, { text: 'Second' })
+ const bytes = await exportFigFile(graph)
+ const worker = new Worker(
+ new URL('../../../../../src/kiwi/fig/session/worker.ts', import.meta.url),
+ { type: 'module' }
+ )
+ const channel = new MessageChannel()
+ const messages: FigSessionResponse[] = []
+ let notify: (() => void) | undefined
+ channel.port1.onmessage = (event) => {
+ messages.push(event.data)
+ notify?.()
+ }
+ const wait = (type: string) =>
+ new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error(`Timed out waiting for ${type}`)), 10000)
+ notify = () => {
+ clearTimeout(timeout)
+ resolve()
+ }
+ })
+ const next = async (type: FigSessionResponse['type']): Promise<FigSessionResponse> => {
+ for (;;) {
+ const index = messages.findIndex((message) => message.type === type)
+ if (index !== -1) return messages.splice(index, 1)[0]
+ await wait(type)
+ }
+ }
+ try {
+ worker.postMessage(
+ {
+ type: 'open',
+ originalBuffer: bytes.slice().buffer,
+ archiveBuffer: bytes.slice().buffer,
+ options: { populate },
+ port: channel.port2
+ },
+ [channel.port2]
+ )
+ expect((await next('page-manifest')).type).toBe('page-manifest')
+ const opened = await next('graph')
+ if (opened.type !== 'graph' || !opened.graph) throw new Error('Missing worker graph')
+ const { deserializeSceneGraph } = await import('#core/kiwi/fig/parse/transfer')
+ const received = deserializeSceneGraph(opened.graph)
+ expect(received.getChildren(received.getPages()[0].id)).toHaveLength(
+ populate === 'none' ? 0 : 1
+ )
+ channel.port1.postMessage({ type: 'original-archive', requestId: 'archive' })
+ const archive = await next('original-archive-result')
+ if (archive.type !== 'original-archive-result') throw new Error('Missing archive response')
+ expect(archive.bytes).toEqual(bytes)
+ channel.port1.postMessage({
+ type: 'populate',
+ requestId: 'bad-page',
+ baseRevision: 0,
+ pageId: 'missing'
+ })
+ const failure = await next('population-error')
+ if (failure.type !== 'population-error') throw new Error('Missing population error')
+ expect(failure.requestId).toBe('bad-page')
+ expect(failure.error).toContain('Unknown graph page')
+ const page = received.getPages()[1]
+ channel.port1.postMessage({
+ type: 'populate',
+ requestId: 'page-2',
+ baseRevision: 0,
+ pageId: page.id
+ })
+ const result = await next('population-result')
+ expect(result.type).toBe('population-result')
+ if (result.type === 'population-result')
+ expect(result.delta.created.some(([, node]) => node.text === 'Second')).toBe(true)
+ channel.port1.postMessage({ type: 'dispose' })
+ await next('disposed')
+ } finally {
+ channel.port1.close()
+ worker.terminate()
+ }
+ },
+ 20000
+)
diff --git a/packages/core/tests/text/derived-text/saved-height.test.ts b/packages/core/tests/text/derived-text/saved-height.test.ts
new file mode 100644
index 000000000..0c894956c
--- /dev/null
+++ b/packages/core/tests/text/derived-text/saved-height.test.ts
@@ -0,0 +1,33 @@
+import { expect, test } from 'bun:test'
+
+import { computeAllLayouts, getTextMeasurer, setTextMeasurer } from '@open-pencil/core/layout'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('saved glyph height wins over a different font measurer at unchanged width', () => {
+ const graph = new SceneGraph()
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, {
+ width: 878,
+ height: 200,
+ layoutMode: 'VERTICAL'
+ })
+ const text = graph.createNode('TEXT', frame.id, {
+ width: 878,
+ height: 60,
+ text: 'Saved text',
+ textAutoResize: 'HEIGHT',
+ derivedTextGlyphs: [{ commandsBlob: new Uint8Array([0]), x: 0, y: 20, fontSize: 20 }]
+ })
+ const previous = getTextMeasurer()
+ setTextMeasurer(() => ({ width: 878, height: 90 }))
+ try {
+ computeAllLayouts(graph)
+ expect(text.height).toBe(60)
+ expect(text.derivedTextGlyphs).toHaveLength(1)
+ graph.updateNode(text.id, { width: 800 })
+ computeAllLayouts(graph)
+ expect(text.height).toBe(90)
+ expect(text.derivedTextGlyphs).toBeNull()
+ } finally {
+ setTextMeasurer(previous)
+ }
+})
diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.ts
index a1be4df81..28d837e1f 100644
--- a/packages/docs/.vitepress/sidebars.ts
+++ b/packages/docs/.vitepress/sidebars.ts
@@ -111,6 +111,7 @@ export const developmentSidebar = (
{ text: 'Contributing', link: `${prefix}/development/contributing` },
{ text: 'Testing', link: `${prefix}/development/testing` },
{ text: labels.architecture, link: `${prefix}/development/architecture` },
+ { text: '.fig Reader Architecture', link: '/development/fig-reader' },
{ text: labels.techStack, link: `${prefix}/development/tech-stack` },
...(!prefix
? [
diff --git a/packages/docs/development/architecture.md b/packages/docs/development/architecture.md
index 64d65147e..2c2bce1cd 100644
--- a/packages/docs/development/architecture.md
+++ b/packages/docs/development/architecture.md
@@ -2,6 +2,9 @@
## System Overview
+For source identity, override evaluation, page sessions, and export contracts, see
+[.fig Reader Architecture](./fig-reader).
+
```mermaid
graph TB
subgraph Tauri["Tauri v2 Shell"]
diff --git a/packages/docs/development/fig-reader.md b/packages/docs/development/fig-reader.md
new file mode 100644
index 000000000..e4a6456c9
--- /dev/null
+++ b/packages/docs/development/fig-reader.md
@@ -0,0 +1,59 @@
+# .fig Reader Architecture
+
+The reader interprets Figma source records into independently editable scene occurrences.
+One reader serves the application, CLI, MCP, and worker paths; the earlier importer and its
+repair pipeline are gone.
+
+::: warning Implementation status
+The reader is the only import path: synchronous parsing, the document worker, page population,
+recovery, export, and clipboard paste all use it, and the previous importer is removed.
+Corpus-wide fidelity (export still reassigns node identities and drops some raw text metadata)
+and performance acceptance remain unfinished. The diagram describes responsibilities, not a
+claim of complete Figma parity.
+:::
+
+```mermaid
+flowchart TD
+ Archive[FIG archive and resources] --> Sources[Indexed source records]
+ Sources --> Closure[Selected pages and component dependencies]
+ Closure --> Evaluation[Occurrence evaluation and provenance]
+ Evaluation --> Graph[Editable SceneGraph]
+ Graph --> Sessions[Page sessions and recovery]
+ Graph --> Editor[Editor actions and undo]
+ Editor --> Export[FIG export]
+ Export --> Oracle[Figma reopen and visual validation]
+```
+
+## Key distinctions
+
+- A **source record** identifies an archive node; an **occurrence** identifies one use of it.
+- An **owner** establishes the component scope for an override **claim**.
+- An effective value is not enough to determine whether it is inherited or overridden.
+- Saved appearance, editable layout, and exported-file fidelity are separate contracts.
+
+```text
+ Inherited default Explicit equal value
+Initial text "Badge" "Badge"
+Component changes "Updated" "Updated"
+Instance result "Updated" "Badge"
+```
+
+## Package documentation
+
+The canonical implementation documentation lives alongside the package in
+[`packages/fig/docs`](https://github.com/open-pencil/open-pencil/tree/master/packages/fig/docs).
+This page is the development-site entry point, not a second copy of those contracts.
+
+Read in order:
+
+1. [Architecture and ownership](https://github.com/open-pencil/open-pencil/blob/master/packages/fig/docs/architecture.md)
+2. [Source model and identities](https://github.com/open-pencil/open-pencil/blob/master/packages/fig/docs/source-model.md)
+3. [Instance evaluation and precedence](https://github.com/open-pencil/open-pencil/blob/master/packages/fig/docs/instance-evaluation.md)
+4. [SceneGraph materialization](https://github.com/open-pencil/open-pencil/blob/master/packages/fig/docs/materialization.md)
+5. [Document sessions, rollback, and recovery](https://github.com/open-pencil/open-pencil/blob/master/packages/fig/docs/document-sessions.md)
+6. [Export contracts](https://github.com/open-pencil/open-pencil/blob/master/packages/fig/docs/export.md)
+7. [Validation and oracle methodology](https://github.com/open-pencil/open-pencil/blob/master/packages/fig/docs/validation.md)
+
+See also [system architecture](./architecture), [testing](./testing), and the
+[development roadmap](./roadmap). Fixture provenance belongs next to fixtures; individual
+benchmark runs and temporary oracle results do not belong in architecture documentation.
diff --git a/packages/docs/development/roadmap.md b/packages/docs/development/roadmap.md
index a33aa6a0e..1d78144e9 100644
--- a/packages/docs/development/roadmap.md
+++ b/packages/docs/development/roadmap.md
@@ -225,7 +225,7 @@ Figma's design documentation groups features into these areas:
| Font variations / OpenType features | ✅ | ✅ | — | ✅ | — | Imported `fontVariations`, common ligature/caps/numeric OpenType fields, and raw `toggledOnOTFeatures` / `toggledOffOTFeatures` are applied to CanvasKit text styles and exported; UI controls are not exposed. |
| Variables: collections/modes/aliases | ✅ | ◐ | ◐ | ✅ | ✅ | Color/number/string/boolean model exists; inspector coverage is still incomplete. |
| Variables bound to fills/strokes | ✅ | ✅ | ✅ | ✅ | ✅ | Common color bindings render and edit. |
-| Variables bound to text/layout/visibility/effects | ◐ | ◐ | ◐ | ◐ | ✅ | Some bindings exist; not full Figma property coverage. |
+| Variables bound to text/layout/visibility/effects | ◐ | ◐ | ◐ | ◐ | ✅ | Text content and numeric layout bindings resolve on read; colour and numeric bindings also re-resolve when a variable or mode changes, string ones do not. Effect bindings are not modelled. |
| Variables in prototypes / expressions / conditionals | — | — | — | — | — | Depends on prototype system, which is not implemented. |
| Libraries / publish / update review | ↩ | — | ◐ | ↩ | — | Figma library metadata survives round-trip. OpenPencil supports its own component-library publishing, catalogs, revision previews, and linked-instance updates, not synchronization with Figma-hosted libraries. |
| Prototype flows / starting points | — | — | — | — | — | Not modeled. |
@@ -285,7 +285,7 @@ These are parsed or visible in Figma docs and most likely to cause visible diffe
| Source edit tracking | `packages/scene-graph/src/source-metadata.ts` |
| `.fig` metadata policy | `packages/fig/src/source-metadata.ts` |
| Kiwi import mapping | `packages/fig/src/node-change/convert.ts` |
-| Kiwi export mapping | `packages/fig/src/node-change/export-node.ts`, `packages/fig/src/node-change/serialize.ts` |
+| Kiwi export mapping | `packages/fig/src/node-change/export/node.ts`, `packages/fig/src/node-change/serialize.ts` |
| Kiwi schema | `packages/kiwi/src/fig/schema/fig.kiwi`, `tests/engine/io/fig/import/schema-coverage.test.ts` |
| Renderer dispatch | `packages/core/src/canvas/scene.ts` |
| Fills / images / gradients | `packages/core/src/canvas/fills.ts` |
diff --git a/packages/fig/AGENTS.md b/packages/fig/AGENTS.md
index 9456af057..019363a0f 100644
--- a/packages/fig/AGENTS.md
+++ b/packages/fig/AGENTS.md
@@ -3,8 +3,12 @@
`@open-pencil/kiwi` owns Kiwi schema, runtime, codecs, containers, and parse helpers without SceneGraph knowledge. `@open-pencil/fig` owns complete `.fig` archive parsing, SceneGraph conversion, metadata policy, component/instance interpretation, and the Figma clipboard format. Core owns format-neutral orchestration, runtime fonts and workers, and thumbnails.
- Keep Kiwi runtime changes minimal; put project policy in wrappers, not in the runtime.
-- Figma clipboard envelope encoding, decoding, bounds, and SceneGraph import conversion belong to `@open-pencil/fig/clipboard`. Core prepares runtime fonts and text and owns editor placement and history; browser and Tauri adapters own system clipboard I/O. Do not add platform clipboard APIs here.
+- Figma clipboard envelope encoding, decoding, and bounds belong to `@open-pencil/fig/clipboard`; converting those records to a SceneGraph is `materializeFigFragment` in `packages/fig/src/document/fragment.ts`, which Core drives from `packages/core/src/clipboard/fig-import.ts`. Core prepares runtime fonts and text and owns editor placement and history; browser and Tauri adapters own system clipboard I/O. Do not add platform clipboard APIs here.
+- One reader serves every `.fig` path — parse, worker, page population, session recovery, export, and paste — through the document sessions in `packages/fig/src/document/`. Read what it could not resolve with `readerDiagnostics(graph)` from `packages/core/src/kiwi/fig/session/document-state.ts`; do not add a second import path.
- Browser `.fig` export uses fflate and `@open-pencil/fig`; Tauri uses `build_fig_file` in `desktop/`.
- Vector networks use the reverse-engineered `vectorNetworkBlob`; codecs live under `packages/core/src/vector/` and types in Scene Graph.
- Changes to `.fig` behavior require round-trip validation in Figma. `packages/docs/development/roadmap.md` tracks raw metadata coverage and the code map for import/export mapping and schema files.
+- Measure a reader change over a whole archive, not one frame: capture before and after with `visual-oracles compare digest --file F --out baseline.json` then `--baseline baseline.json`, and account for every node it reports. `compare interpreted-document` checks one frame against live Figma and will report no change while a rule breaks pages it does not cover.
+- A rule about Figma's override or binding semantics holds only where it was observed. Before encoding one, find a second archive or frame that exercises it and confirm the outcome in live Figma; several plausible rules here fit one file and are contradicted by the next.
- Fixtures under `tests/fixtures/*.fig` use Git LFS; use a normal `git push` when they change, and `git push --no-verify` to skip the LFS hook otherwise.
+- Tests address the package by alias rather than drilling: `#fig/*` for source, `#fig-tests/*` for shared test helpers, both registered in `tools/checks/architecture/src/steiger-rules/support.ts`.
diff --git a/packages/fig/README.md b/packages/fig/README.md
index b79328aa1..5f68bb04c 100644
--- a/packages/fig/README.md
+++ b/packages/fig/README.md
@@ -19,6 +19,11 @@ Current ownership:
- SceneGraph-to-`NodeChange` export conversion with an explicit glyph-outline runtime service
- Package-local archive, conversion, instance, export, and dist smoke tests
+## Architecture documentation
+
+Start with [the package docs](./docs/README.md) for the source model, instance evaluation,
+materialization, document sessions, export, and validation contracts.
+
Planned ownership:
- Oracle-backed `.fig` fixtures
diff --git a/packages/fig/docs/README.md b/packages/fig/docs/README.md
new file mode 100644
index 000000000..b91aa8da4
--- /dev/null
+++ b/packages/fig/docs/README.md
@@ -0,0 +1,40 @@
+# FIG package architecture
+
+These documents explain the `.fig` reader and its editing/export contracts.
+They are package implementation documentation, not a release-status log.
+
+## Reading order
+
+| Document | Question |
+| --- | --- |
+| [Architecture](./architecture.md) | Which package owns each stage? |
+| [Source model](./source-model.md) | What are records, resources, and identities? |
+| [Instance evaluation](./instance-evaluation.md) | How do bindings and overrides resolve? |
+| [Materialization](./materialization.md) | How do occurrences become editable nodes? |
+| [Document sessions](./document-sessions.md) | How do incremental loads and recovery work? |
+| [Export](./export.md) | How are runtime identities and claims encoded? |
+| [Validation](./validation.md) | What constitutes compatibility evidence? |
+
+```text
+archive -> source model -> instance evaluation -> materialization
+ |
+ document sessions + editor actions
+ |
+ export
+ |
+ Figma validation
+```
+
+## Status vocabulary
+
+- **Required invariant:** a correctness constraint, whether or not all cases satisfy it yet.
+- **Implemented:** behavior present in the linked modules and covered by the cited tests.
+- **Known limitation:** a boundary not yet implemented or validated; not a supported fallback.
+
+Every consumer uses this reader; the previous importer and its repair pipeline are gone, so there is
+one interpretation path, not a legacy mode. Remaining work is fidelity and performance
+acceptance against Figma, tracked per document as known limitations.
+
+Keep temporary file keys, benchmark runs, experimental findings, and current blockers in
+ignored `scratch/` notes or the integration PR. Fixture provenance belongs alongside fixtures.
+The [public roadmap](../../docs/development/roadmap.md) owns product-level direction.
diff --git a/packages/fig/docs/architecture.md b/packages/fig/docs/architecture.md
new file mode 100644
index 000000000..76fb40701
--- /dev/null
+++ b/packages/fig/docs/architecture.md
@@ -0,0 +1,60 @@
+# Architecture
+
+```mermaid
+flowchart TD
+ Kiwi[Kiwi: schema, codec, container] --> Archive[FIG archive and source index]
+ Archive --> Dependencies[Dependency closure]
+ Dependencies --> Evaluation[Occurrence evaluation]
+ Evaluation --> Graph[SceneGraph materialization]
+ Graph --> Core[Core: editor, undo, layout, fonts]
+ Core --> Consumers[App, CLI, MCP, automation]
+```
+
+This shows responsibility flow, not a dependency graph of package imports.
+
+## Ownership
+
+| Domain | Owner |
+| --- | --- |
+| Kiwi schema/runtime and protocol containers | `@open-pencil/kiwi` |
+| FIG archives, record interpretation, resource association, format conversion | `@open-pencil/fig` |
+| Format-neutral graph, component-property mutations, override storage | `@open-pencil/scene-graph` |
+| Editor actions, undo, render invalidation, layout scheduling, runtime fonts | `@open-pencil/core` |
+| Worker lifecycle and format-neutral document I/O | Core |
+
+**Required invariant:** adapters converge on the same document semantics. Neither Vue nor
+an automation adapter implements an independent override resolver.
+
+## Reader entry points
+
+The package exposes record-based assembly, archive-owned assembly, and incremental sessions.
+They share one evaluation/materialization path. Core uses it for synchronous parsing, the
+document worker, page population, recovery, export of unloaded pages, and clipboard paste
+(`materializeFigFragment`); CLI and MCP consume Core's `parseFigFile`. See
+[document sessions](./document-sessions.md) for ownership and lifecycle details.
+
+- [Archive parsing and assembly](../src/archive.ts)
+- [Document reader](../src/document/read.ts)
+- [Document materialization](../src/document/materialize.ts)
+- [Public exports](../src/index.ts)
+
+## Replacement boundary
+
+There is one reader and no post-import repair replay. The previous importer, its lazy
+population path, and its sync-repair helpers are deleted rather than kept as fallbacks; reusing
+independent codec, font, geometry, and resource utilities is appropriate, retaining an old
+interpretation algorithm behind renamed wrappers is not.
+
+**Known limitation:** export reassigns node GUIDs and drops raw text metadata Figma keeps on
+outlined vectors, so an edited design-system file does not yet round-trip node for node.
+Corpus-wide fidelity and performance acceptance remain open; see [validation](./validation.md)
+and the integration PR for current measurements.
+
+Relevant boundaries:
+
+- [Session worker](../../core/src/kiwi/fig/session/worker.ts)
+- [Format-neutral FIG read orchestration](../../core/src/io/formats/fig/read.ts)
+- [Page controller](../../core/src/editor/pages.ts)
+
+Compatibility is judged against Figma, not output agreement with the implementation being
+removed. See [validation](./validation.md).
diff --git a/packages/fig/docs/document-sessions.md b/packages/fig/docs/document-sessions.md
new file mode 100644
index 000000000..e3eff0b2b
--- /dev/null
+++ b/packages/fig/docs/document-sessions.md
@@ -0,0 +1,113 @@
+# Document sessions
+
+```mermaid
+stateDiagram-v2
+ [*] --> Unloaded
+ Unloaded --> Preparing: loadPage
+ Preparing --> Unloaded: preflight rejects
+ Preparing --> Mutating: dependencies valid
+ Mutating --> Unloaded: rollback and discard events
+ Mutating --> Loaded: commit and mark loaded
+ Loaded --> Loaded: publish events or repeat load
+```
+
+Observer failure occurs after `Loaded`; it does not transition back to `Unloaded`.
+
+## APIs and ownership
+
+`materializeDocument(records)` copies caller data. `materializeFigArchive(bytes)` owns its
+parsed records. Both support source-page selection through `pageIds`.
+
+`createFigDocumentSession(bytes)` starts with page shells. `loadPage(sourcePageId)` adds content
+to the same graph and is idempotent for loaded pages. `graphPageId(sourcePageId)` bridges source
+IDs to runtime IDs used by worker requests. Existing graph/node identities and the editor's
+undo manager must survive later loads and recovery.
+
+Page loading is not a user edit: it must neither add undo commands nor clear redo history.
+Failed-load rollback is separate from user undo.
+
+`DocumentAssemblyOptions` extends the interpreter options: the handlers a session is created
+with decide whether records addressing deleted nodes or components fail the load or are skipped
+and reported. Broken hierarchy in the dependency closure is always fatal. Core creates its
+open, recovery, and export sessions with one shared diagnostics sink per document.
+
+## Transaction semantics
+
+**Implemented:** a scoped synchronous journal restores selected existing nodes, child lists,
+instance indexes, and reader lookup maps, and removes newly created nodes if the load action
+throws. It is not a general SceneGraph transaction. Unrelated document payloads are not cloned.
+
+Graph events are buffered until the mutation succeeds. Nested buffers merge into their outer
+buffer. Observers run after the page is marked loaded. `CommittedGraphEventError` means graph
+state committed but notification failed; callers must not retry as if the graph rolled back.
+Queued events continue to be attempted. The underlying nanoevents dispatch may stop remaining
+listeners for a single event when one listener throws.
+
+## Worker results and recovery
+
+```mermaid
+sequenceDiagram
+ participant C as Client
+ participant W as Reader worker
+ participant G as Edited graph
+ C->>W: Populate page at base revision
+ W-->>C: Delta and checkpoint
+ alt Revision matches
+ C->>G: Apply delta
+ C->>C: Accept checkpoint
+ else Result is stale
+ C->>C: Reject delta and checkpoint
+ C->>G: Resume reader against existing graph
+ end
+```
+
+Only an accepted delta advances the receiver's checkpoint. Original archive bytes remain
+available for recovery and are released with session ownership. Recovery never replaces the
+edited graph.
+
+Checkpoints contain source-to-node mappings, loaded pages, saved-size tracking, and component
+topology addressed by complete source-identity paths. Occurrence property payloads are
+reconstructed from source records when recovery is needed. Restore validates paths, component
+identity, coverage, and roots before attaching to graph nodes.
+
+```text
+Checkpoint stores Recovery reconstructs
+------------------------------- -------------------------------
+source path -> graph node ID occurrence properties
+main-component identity binding evaluation
+loaded source page IDs source-derived geometry
+saved-size tracking links to EXISTING graph objects
+```
+
+## Rollback example
+
+```text
+ Before load During load After failure
+Existing node ID n17 n17 n17
+Existing edit "Custom" "Custom" "Custom"
+New nodes -- n21, n22 --
+Loaded pages {A} {A} {A}
+Load notifications -- buffered discarded
+```
+
+This is load rollback, not an undo command. Existing user history remains intact.
+
+## Known limitations
+
+- Component child additions, deletions, and reordering are rejected before another page load;
+ structural reconciliation is not implemented.
+- All frontend lifecycle and cancellation scenarios are not yet accepted. Synchronous work
+ cannot be interrupted merely by queuing a cancel message; transport termination is tested.
+- Large-page construction and checkpoint costs still require performance work.
+
+## Implementation and tests
+
+- [Session and assembly API](../src/document/materialize.ts)
+- [Page-load rollback](../src/document/load-transaction.ts)
+- [Compact component checkpoints](../src/document/component/checkpoint.ts)
+- [Buffered graph events](../../scene-graph/src/buffered-events.ts)
+- [Worker backend](../../core/src/kiwi/fig/session/reader.ts)
+- [Recovery](../../core/src/kiwi/fig/session/recovery.ts)
+- [Session tests](../tests/document/session.test.ts)
+- [Checkpoint validation](../tests/document/checkpoint.test.ts)
+- [Worker/undo/recovery integration tests](../../../tests/engine/io/fig/session/)
diff --git a/packages/fig/docs/export.md b/packages/fig/docs/export.md
new file mode 100644
index 000000000..8e76d8c5a
--- /dev/null
+++ b/packages/fig/docs/export.md
@@ -0,0 +1,122 @@
+# Export
+
+```text
+editable SceneGraph
+ +-- canonical node/resource identities
+ +-- explicit owner-scoped overrides
+ +-- retained source metadata + edited-field tracking
+ |
+ v
+ export-scoped GUID allocation
+ |
+ node records + full-path claims
+ |
+ schema encoding + blobs + images
+ |
+ v
+ FIG archive
+```
+
+## Identity and references
+
+Export must assign one identity to each node/resource and use it consistently in references.
+A source GUID string is not necessarily the destination graph ID. INSTANCE_SWAP defaults and
+assignments must be linked to graph nodes before export GUID resolution.
+
+Shared styles are emitted once through the resource path, not again through ordinary scene
+traversal. Sibling positions must use one consistent ordering scheme matching runtime order.
+Remote style references and local style references are distinct: remote assets can require a
+key/version rather than a locally assigned GUID.
+
+## Override addressing
+
+```text
+owner + target correspondence
+ |
+ v
+[root component key] self claim
+[nested instance, source child] descendant claim
+[nested A, nested B, source child] deeper descendant claim
+```
+
+Do not serialize a nested claim as only its final source GUID. Structured self overrides use
+an empty target ID internally; the exporter must interpret that as the owner, not discard it.
+
+A segment names the target record by GUID, or by its `overrideKey` when the target came from a
+published library and carries one — Figma writes both forms and the reader accepts either.
+`material3.fig` addresses 51,332 segments by GUID against 24 by key, while every segment in the
+library-based `gold-preview.fig` is a key.
+
+Which scene fields are claimable, which raw field each serializes to, and which are placed-space
+lengths comes from one registry (`instance-overrides/fields.ts`); materialization records
+claims and export serializes them from the same table.
+
+A descendant `size` claim has no effect in Figma, which does not allow resizing a layer inside
+an instance: no size claim in `gold-preview.fig`, `material3.fig` or `nuxtui.fig` targets a
+descendant that is not an instance, and the ones that target a nested instance restate that
+instance's own size. OpenPencil permits the edit, so the writer records it and the reader
+restores it; Figma keeps the layer at its component's size on open.
+
+A paint colour alias lives inside the paint, not in the node's parameter map. A `fills` or
+`strokes` claim is therefore written with each paint's `colorVar`, and a
+`boundVariables/fills/N/color` override is serialized as that paint claim rather than as a
+consumption entry, which has no field for it. Reading a claimed paint records its binding claim
+as well, so a later component sync cannot restore the component's variable.
+
+## Values and layout
+
+- Root size claims and placed sizes occupy different coordinate spaces when uniformly scaled.
+- Do not apply the root-size scaling rule indiscriminately to padding or other fields.
+- Preserve explicit sizing/grow/alignment claims, not just text or final rectangles.
+- Untouched layout metadata retains omission and implicit-size semantics.
+- Edited fields export current values rather than stale retained metadata.
+- Text sizing is explicit state. Being inside auto-layout does not justify forcing `HEIGHT`.
+
+These rules are supported by focused tests, but coordinate-space handling across all nested
+scaling and layout combinations is not complete.
+
+```text
+Root size claim Uniform scale Placed node size
+100 x 40 0.5 50 x 20
+ | |
+ +-- export in root-claim space +-- export as node.size
+
+Writing 50 x 20 into both places can apply the scale twice.
+```
+
+This example describes root dimensions only. Padding and other fields require their own
+coordinate-space contracts; do not apply the same division to every numeric property.
+
+## Component properties and parameters
+
+Current Figma records use typed `varValue` data for definitions and assignments, and `PROP_REF`
+entries in `parameterConsumptionMap` for bindings. Older value/reference forms also exist.
+Writing only the older fields can produce visible content with nonfunctional property controls.
+
+Variable bindings and component-property bindings share parameter maps. Combining them must
+preserve both; one must not replace the whole map containing the other.
+
+## Validation boundary
+
+An archive that encodes successfully is not necessarily interpreted correctly by Figma. A
+writer and reader can agree on the same mistake. Require both record-level regressions and
+[external reopen checks](./validation.md), including actual property actions after import.
+
+**Known limitations:** explicit-name persistence, complete style associations, all override
+fields, and structural editing/export interactions remain acceptance gaps. Do not present
+selected passing properties as complete editable-document compatibility.
+
+## Implementation and tests
+
+- [Node-change serialization](../src/node-change/export/node.ts)
+- [Override claims](../src/node-change/export/override-claims.ts)
+- [Export context and identity allocation](../src/node-change/export/context.ts)
+- [Property/layout conversion](../src/node-change/serialize.ts)
+- [Archive assembly](../src/archive.ts)
+- [Core export orchestration](../../core/src/io/formats/fig/export.ts)
+- [Figma-authored contract fixture](../tests/document/fixtures/README.md)
+- [Self-size export](../tests/document/self-size-export.test.ts)
+- [Edited layout export](../tests/document/layout-edit-export.test.ts)
+- [Shared-style uniqueness](../tests/document/shared-style-export.test.ts)
+- [Full-document editing round trip](../tests/document/gold-edit.test.ts)
+- [Instance paint alias round trip](../../../tests/engine/io/fig/roundtrip/variables.test.ts)
diff --git a/packages/fig/docs/instance-evaluation.md b/packages/fig/docs/instance-evaluation.md
new file mode 100644
index 000000000..d4a98dcb3
--- /dev/null
+++ b/packages/fig/docs/instance-evaluation.md
@@ -0,0 +1,140 @@
+# Instance evaluation
+
+```mermaid
+flowchart TD
+ Layers[Owner layers: swaps, assignments, property claims] --> Route[Route structural layers to the instance they configure]
+ Route --> Expand[Expand each occurrence once with its effective component and bindings]
+ Expand --> Claims[Owners apply property claims onto the built subtree, inner to outer]
+ Claims --> Derived[Saved occurrence-derived data]
+ Derived --> Result[Effective values and provenance]
+```
+
+The model has three parts. An instance expands its component's subtree. Every owner
+contributes *layers*: a partial record at a path relative to that owner. Where layers
+overlap, the outermost owner wins.
+
+A layer is *structural* when it carries a swap (`overriddenSymbolID`) or component-property
+assignments; it selects what a nested instance expands. Everything else is a *property* layer.
+Structural layers are routed down to the instance they address before it expands, so each
+occurrence expands exactly once with its effective component and complete assignment list.
+Property layers are applied by their declaring owner after its subtree is built, which keeps
+their values in that owner's coordinate space and orders inner owners before outer ones.
+
+## Addressing
+
+A property path is relative to its declaring owner. Ordinary containers may be traversed
+without adding an instance boundary; nested instances require an explicit segment.
+
+```text
+Owner
+ +-- instance A -> Label (source L)
+ +-- instance B -> Label (source L)
+
+[A, L] != [B, L] valid distinct addresses
+[L] across an instance boundary not an implicit recursive search
+```
+
+Component GUIDs and component override keys can address the root. A binding-driven replacement
+can retain the source component's root identity without retaining its old descendant targets.
+A placed instance's explicit size remains separate from unscaled root-override size.
+
+## Provenance
+
+| Origin | Interpretation |
+| --- | --- |
+| Component default | Inherited unless superseded. |
+| Property assignment | Supplies a binding value; not equivalent to its default. |
+| Explicit path override | Declared by an owner against a complete path. |
+| Saved derived data | Effective geometry/typography; not automatically a user override. |
+| Editor mutation | Recorded through the shared editing domains after materialization. |
+
+```text
+default Label = "Badge"
+ +-- untouched instance -> inherits later component changes
+ +-- explicit "Badge" -> remains overridden despite equal text
+```
+
+Definitions with `parentPropDefId` inherit semantics within source ancestry while retaining
+local property identity. Current typed `varValue` and `PROP_REF` parameter records are
+normalized alongside older property forms.
+
+**Implemented:** an outer owner's assignment supersedes an inner owner's explicit claim on the
+same field; unrelated fields of that claim are kept. A claim whose path passes through a swapped
+instance and resolved in the replaced component is stale and dropped. A missing target that did
+not resolve there either is reported, never remapped onto a similarly named replacement child.
+
+## Worked precedence example
+
+```text
+Contribution text opacity
+-------------------------- -------------- -------
+Component default "Badge" 1.0
+Intermediate explicit claim "Custom" 0.4
+Outer text assignment "Assigned" --
+
+Effective result "Assigned" 0.4
+Retained intermediate claim -- 0.4
+```
+
+The outer assignment supersedes the intermediate text claim without erasing unrelated opacity.
+Within one owner, its assignments bind before its explicit claims, so an explicit child claim
+wins over that owner's own assignment to the same field.
+
+```text
+BEFORE SWAP AFTER SWAP
+Component A Component B
+ A/Label [explicit text claim] B/Icon
+ A/Icon B/Caption
+
+A/Label does NOT become B/Caption merely because both contain text.
+```
+
+## Names
+
+Stored `name` alone is not proof of an explicit rename. Figma save captures distinguish
+root-targeted name claims. Untouched replacement instances use the component name, or the
+component-set name for variants. Initial stored names are not globally rewritten.
+
+**Known limitation:** complex compositions of inherited renames, bindings, and structural
+swaps still have unresolved oracle cases. Direct `swapComponent()` behavior must not be assumed
+to describe every saved-record composition.
+
+## Derived text
+
+Changing text or shaping properties invalidates inherited glyph caches unless a patch supplies
+replacement data. Later occurrence-derived glyph data can replace that invalidated cache.
+Paint-only changes do not alter glyph positions; every claim application applies the same
+validity rule.
+See [materialization](./materialization.md) for rendering and editing boundaries.
+
+## Diagnostics
+
+The library is strict by default: a missing or ambiguous target throws. `InterpretInstanceOptions`
+lets a caller skip and report instead: `onUnresolvedProperty` and `onUnresolvedAssignment` for
+records that address nodes the archive no longer contains, and `onMissingComponent` for an
+instance of a deleted component, which then stays a childless instance with its saved
+reference. A swap reports the same way when its target layer no longer exists, which Figma
+retains as readily as a stale property override; an address that matches more than one record
+is a wrong path rather than a stale one and stays fatal. Reports retain owner, effective
+component context, complete path, and assignment payload where applicable.
+
+Figma retains such records after deletions, so the application reader opts into all three
+(`readerSessionOptions` in Core) and exposes the collected records through
+`readerDiagnostics(graph)`. Oracle tooling stays strict unless a flag names the concession.
+
+## Implementation and tests
+
+- [Interpreter](../src/instance-overrides/interpret.ts)
+- [Static source routing](../src/instance-overrides/source-index.ts)
+- [Occurrence path resolution](../src/instance-overrides/occurrence-path.ts)
+- [Binding evaluation](../src/instance-overrides/interpret-bindings.ts)
+- [Text provenance](../src/instance-overrides/text-provenance.ts)
+- [Addressing tests](../tests/instance/addressing.test.ts)
+- [Binding precedence tests](../tests/instance/bindings.test.ts)
+- [Root-key tests](../tests/instance/root-key.test.ts)
+- [Swap provenance tests](../tests/instance/swap-provenance.test.ts)
+- [Name capture provenance](../tests/instance/fixtures/README.md)
+
+**Known limitation:** field coverage and provenance transitions are not complete. Assignments
+whose definition only exists on a detached ancestor are reported as unresolved rather than
+remapped through `detachedSymbolId` lineage.
diff --git a/packages/fig/docs/materialization.md b/packages/fig/docs/materialization.md
new file mode 100644
index 000000000..68ae3c4c3
--- /dev/null
+++ b/packages/fig/docs/materialization.md
@@ -0,0 +1,197 @@
+# Materialization
+
+```text
+source ownership + evaluated occurrences
+ |
+ allocate canonical identities
+ |
+ populate children in saved order
+ |
+ link source correspondence by owner
+ |
+ record explicit/bound overrides
+ |
+ resolve resources and live edits
+ v
+ editable SceneGraph
+```
+
+## Construction and correspondence
+
+Canonical page/container/component identities are allocated before dependent instances are
+populated. A component referenced from another page must not be duplicated when its own page
+loads. Occurrence nodes are mapped by source identity, not names or sibling indexes.
+
+```text
+Nested Label's live node
+ +-- owner: Inner instance -> original Label in Inner component
+ +-- owner: Outer instance -> Label in Outer's expanded Inner instance
+
+One node can need both correspondences for different editing operations.
+```
+
+Swapping an instance preserves its role in the enclosing component, including property
+references, while changing its main component and descendant expansion. Correspondence into
+removed descendants ends at the swap boundary.
+
+Component-property definitions belong to components/sets. Instances retain assignments and
+references, not copied definition lists. A variant's `variantPropSpecs` name definitions its
+component set owns, so its `componentPropertyValues` resolve to names after the set exists in
+the graph, not during occurrence conversion.
+
+Explicit claims are recorded as instance overrides through the shared field registry; a
+claimed paint that carries a colour alias also records its `boundVariables` claim. An instance
+of a deleted component is materialized as a childless `INSTANCE` with `componentId: null`.
+
+## Editing responsibilities
+
+SceneGraph owns format-neutral override storage and mutation/query helpers. Core's editor owns
+undo transactions, layout scheduling, and render invalidation. Import code must not simulate
+editing with test-only undo closures or replay repairs after construction.
+
+Later-page loading applies supported live component-field edits only to newly created
+occurrences. Explicit destination overrides remain protected. Structural component edits are
+currently rejected by the [session](./document-sessions.md) guard rather than replayed from stale
+source data.
+
+## Saved geometry and text
+
+**Required invariant:** valid saved text geometry describes the saved appearance. Available
+family/style is not proof that reshaping uses the same font binary.
+
+**Implemented:** plain solid text and supported solid-color runs prefer valid saved glyphs.
+Character indices associate glyph clusters with style-run paint. Occurrence-derived text sizes
+supersede inherited source caches. Text/shaping/layout edits invalidate affected caches unless
+the same update supplies replacements; paint-only edits preserve geometry.
+
+**Known limitations:** complex text fills, complete decoration behavior, actual ligature
+coverage, and exact font-identity reporting remain incomplete. Saved appearance is not proof
+that subsequent layout recomputation or editing is correct.
+
+Retained FIG layout metadata preserves distinctions such as implicit-size Hug. Explicit edits
+must take precedence over retained values during [export](./export.md). Raw/pre-scale dimensions
+and effective node geometry must not be conflated.
+
+```text
+Mutation Characters Saved glyph geometry
+------------------------- --------------- --------------------
+Move node unchanged retain
+Change solid fill color unchanged retain
+Change text changed invalidate
+Change font variation unchanged invalidate
+Supply reshaped glyphs changed or same replace explicitly
+```
+
+This is a cache-validity example, not permission to retain geometry after untested
+shaping-affecting changes. The invalidation tests define the implemented coverage.
+
+## Live numeric binding units
+
+Numeric variables stay in their declared units. The FIG materializer records each binding's
+conversion to occurrence coordinates in SceneGraph's format-neutral `variableBindingScales`
+map. Nested instance factors compose; opacity's percentage conversion is separate from
+geometric scale, and rotation is not scaled. The metadata is copied with nodes and retained
+through worker transfer rather than reconstructed from current geometry or value ratios.
+
+```text
+Token value Occurrence multiplier Effective padding
+8 0.8908441663 7.1267533302
+16 0.8908441663 14.2535066605
+undo -> 8 0.8908441663 7.1267533302
+```
+
+Core editor variable actions resolve aliases and inherited modes, apply changed numeric
+values without authoring overrides, and recompute affected layout. Token undo/redo follows
+the same path. Explicit node-mode edits and binding changes use that reconciliation too.
+The editor and Figma API share the graph-only layout reconciliation under Core's layout domain.
+Figma API token/binding methods therefore update headless CLI results too. Direct variable-map
+mutations bypass this contract; such callers must arrange reconciliation rather than only repainting.
+
+Legacy variable maps and modern parameter-map aliases participate in field-wise inheritance.
+A binding declaration starts in its declaring owner's units, replacing only that field's inherited
+conversion. Later enclosing instance scales then compose with it. A node-wide multiplier cannot
+represent both cases:
+
+```text
+Inherited inner binding: token 20 × inner 0.5 × outer 0.5 = padding 5
+Outer-owner declaration: token 12 × outer 0.5 = padding 6
+```
+
+The [captured nested declaration](./observations/nested-binding-ownership.md) retains its
+alias through import, token editing, undo, and re-encoding. Independently reopened Figma preserves
+the alias and responds to token edits; an exact raster comparison covers the restored value.
+Export records declarations per field rather than reauthoring unrelated inherited bindings in the
+wrong owner's space.
+
+Saved numeric consumption expressions support finite constant products with exactly one alias,
+including nested `MULTIPLY` terms. References inside expressions participate in resource
+normalization. Modern declarations shadow legacy fields before reference resolution.
+
+A source instance's own saved expression already includes its local scale. The reader removes
+that scale from declaration units before occurrence scaling, while retaining enclosing scales.
+A saved `0.5 × alias` under another `0.5` occurrence therefore yields a multiplier of `0.25`,
+not `0.125`. Override-path declarations remain in their declaring owner's units. Export writes
+effective own-record coefficients and owner-relative claim coefficients instead of substituting
+unscaled aliases. Unsupported operators, multiple aliases, constant-only binding expressions,
+and non-finite products fail explicitly.
+
+[Captured expression acceptance](./observations/nested-binding-expression.md) covers
+import, token edits/history, edited re-encoding, Figma reactivity, and exact pixels. It does not
+establish a general expression engine or arbitrary expression/component-edit interactions.
+
+[Per-field binding inheritance](./observations/per-field-binding-reopen.md) preserves
+an explicit placed binding while unrelated definition bindings update and remain live after
+Figma reopen. Protection is normalized within each declaring owner before combining scopes;
+one owner's granular declarations cannot weaken another owner's legacy whole-map protection.
+
+Other tests cover alias updates, modes, clone isolation, unbinding undo, and portable transfer.
+This does not establish complete scaled-text semantics or every component binding mutation.
+New declarations use sparse, format-neutral `variableAssignmentScales` on the owning occurrence,
+not the previous binding's conversion. The owner is the outermost containing instance, bounded by
+a component definition. Assignment records per-field claims before notifying observers; history
+restores prior values, conversions, and claims without reauthoring an inherited binding. Cloning
+and portable transfer retain the assignment units.
+
+[New root and nested assignments](./observations/nested-binding-authoring.md) now pass
+editor/API, local re-encoding, independent Figma reopen, and exact raster checks.
+
+SceneGraph's explicit `componentScale` records occurrence coordinate conversion separately from
+variable units. Synchronization converts source properties into target coordinates using these
+recorded factors, including nested source occurrences and newly materialized children. Numeric
+fields controlled by protected bindings remain protected. Only changed properties notify the
+graph, so unchanged text does not lose saved glyph caches. Shared geometry rescaling lives in
+SceneGraph's `scaling/` domain; the Core Figma API delegates there.
+
+[Placed-owner rescaling](./observations/nested-owner-rescale.md) exports the live
+`componentScale`, owner-relative numeric claims, and refreshed descendant geometry snapshots.
+Those snapshots do not author new descendant size claims. A captured half-scale operation
+passes independent Figma reopen, continued token reactivity, exact pixels, and browser projection.
+Local tests additionally cover enlargement to unit scale and literal padding claims.
+
+[Native nested rescale probes](./observations/nested-rescale-restrictions.md) distinguish
+placed occurrence descendants from children inside a component definition. Figma's Plugin API
+rejects the former, even at factor one, while permitting the latter. Core's API applies this
+restriction before mutation; the generic SceneGraph scaling primitive remains policy-neutral.
+[A captured definition-level rescale](./observations/nested-definition-rescale.md)
+now propagates through the editor scheduler, exports/reopens in Figma, retains token reactivity,
+and matches exact native pixels. Existing child occurrence scales derive from the source child
+and source/target parent scales, rather than retaining stale pre-edit coordinate metadata.
+Undo, transitive multi-definition changes, and overridden scale interactions remain separate
+acceptance requirements.
+
+The captured component-padding edit passes undo/redo, independent Figma reopen, exact pixels,
+and a browser geometry snapshot. Full lifecycle acceptance remains open: broader expressions,
+typography, nested rescale/export, reparenting, and structural edits need further coverage.
+No coordinate factor is inferred from current dimensions or numeric variable values.
+
+## Implementation and tests
+
+- [Document assembly](../src/document/materialize.ts)
+- [Occurrence materializer](../src/instance-overrides/materialize-instance.ts)
+- [Owner-scoped correspondence](../src/instance-overrides/source-children.ts)
+- [Live component edits](../src/instance-overrides/live-component-edits.ts)
+- [Component-property domain](../../scene-graph/src/components/properties.ts)
+- [Text cache invalidation](../../scene-graph/src/text-picture.ts)
+- [Full-document editing test](../tests/document/gold-edit.test.ts)
+- [Occurrence conversion/isolation tests](../tests/document/occurrence-conversion.test.ts)
+- [Saved-glyph visual test](../../../tests/e2e/canvas/saved-glyph-visual.spec.ts)
diff --git a/packages/fig/docs/observations/clipboard-transfer-reopen.json b/packages/fig/docs/observations/clipboard-transfer-reopen.json
new file mode 100644
index 000000000..0d4fa6581
--- /dev/null
+++ b/packages/fig/docs/observations/clipboard-transfer-reopen.json
@@ -0,0 +1,24 @@
+{
+ "reopened": {
+ "id": "1:12",
+ "width": 33.5,
+ "height": 7,
+ "children": [
+ {
+ "width": 13.5,
+ "left": 6,
+ "binding": {
+ "paddingLeft": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:0:7"
+ }
+ }
+ }
+ ]
+ },
+ "token": {
+ "width": 35.5,
+ "nestedWidth": 15.5,
+ "left": 8
+ }
+}
diff --git a/packages/fig/docs/observations/clipboard-transfer-reopen.md b/packages/fig/docs/observations/clipboard-transfer-reopen.md
new file mode 100644
index 000000000..92aafe710
--- /dev/null
+++ b/packages/fig/docs/observations/clipboard-transfer-reopen.md
@@ -0,0 +1,16 @@
+# Clipboard transfer external reopen
+
+A captured nested instance is encoded as Figma clipboard HTML, pasted through the real editor
+into a fresh graph, and exported as a document. Reopened Figma reports outer 33.5×7, nested
+width 13.5, and left padding 6 with a direct alias to the remapped variable. Changing token 12→16
+gives outer 35.5, nested 15.5, and left 8. The token is restored to 12.
+
+`clipboard-transfer-reopen.json` records those native observations. Figma renames the placed
+root to `Outer` on reopen, dropping the custom `Clipboard acceptance` name. This is not name
+preservation acceptance. This test exercises encoded clipboard import plus exported-document
+reopen, not trusted operating-system clipboard events or native copy/paste UI.
+
+Editor engine tests cover ordinary paste and paste-to-replace, owned hidden definitions and
+variables through undo/redo, post-placement coordinates, committed observer errors, and a redo
+identity collision leaving the original replacement target intact. Mutation failures during
+original-target deletion and resource reuse beyond these tests remain separate gaps.
diff --git a/packages/fig/docs/observations/freeform-constraint-resize.json b/packages/fig/docs/observations/freeform-constraint-resize.json
new file mode 100644
index 000000000..c7e24a772
--- /dev/null
+++ b/packages/fig/docs/observations/freeform-constraint-resize.json
@@ -0,0 +1,24 @@
+[
+ {
+ "component": "6:5",
+ "instance": "6:7",
+ "horizontal": "MAX",
+ "child": {
+ "x": 180,
+ "y": 10,
+ "width": 10,
+ "height": 100
+ }
+ },
+ {
+ "component": "6:9",
+ "instance": "6:11",
+ "horizontal": "STRETCH",
+ "child": {
+ "x": 10,
+ "y": 10,
+ "width": 180,
+ "height": 100
+ }
+ }
+]
diff --git a/packages/fig/docs/observations/nested-binding-authoring.md b/packages/fig/docs/observations/nested-binding-authoring.md
new file mode 100644
index 000000000..c7137fe3c
--- /dev/null
+++ b/packages/fig/docs/observations/nested-binding-authoring.md
@@ -0,0 +1,29 @@
+# New binding authoring
+
+The source is `nested-binding-ownership-records.json`. Its placed outer occurrence and nested
+instance both have a newly declared `paddingRight` binding to the direct token (value 12).
+
+Independent Figma Plugin API assignment gives paddingRight 6 on both nodes, nested width 17,
+and outer width 33. An OpenPencil Figma API export reopened in Figma retains those values and
+both aliases. Geometry and bound-variable captures are in `nested-binding-authoring.json`.
+
+`tests/fixtures/nested-binding-authoring-figma.png` is an independent Figma export of the native assignment,
+at scale 8 (264×56). The headless authored-binding regression compares exact decoded sRGB RGBA
+pixels, without resampling or tolerance.
+
+## Component-edit acceptance
+
+On the reopened file, changing the Inner main component's paddingTop from 4 to 8 produces
+nested paddingTop 2 and height 8. Both direct aliases remain live and paddingRight stays 6.
+The source property is restored to 4 after capture. `document/binding/authoring.test.ts` now
+passes the independently captured value 2, preserves the bindings, and covers undo/redo.
+`tests/fixtures/nested-component-scale-figma.png` is the independent 264×64 Figma raster at 8×; headless pixels
+match exactly. A browser snapshot also covers the before/after geometry projection.
+
+An OpenPencil export after the component edit reopens in Figma with root size 33×8, nested
+paddingTop 2, paddingRight 6, and both aliases intact. This establishes this component-edit
+contract, not complete typography, rescale/export, reparenting, or structural lifecycle acceptance.
+
+The source archive also encodes the canonical nested inherited padding as a MULTIPLY expression
+(constant 0.5 × alias), rather than a plain alias. The pure-inheritance undo test deliberately
+removes that expression to isolate assignment provenance; it does not establish expression support.
diff --git a/packages/fig/docs/observations/nested-binding-expression.json b/packages/fig/docs/observations/nested-binding-expression.json
new file mode 100644
index 000000000..36eb5352d
--- /dev/null
+++ b/packages/fig/docs/observations/nested-binding-expression.json
@@ -0,0 +1,28 @@
+{
+ "nativeBefore": {
+ "id": "293777:7",
+ "padding": 5,
+ "width": 32.5
+ },
+ "nativeAfter": {
+ "value": 40,
+ "padding": 10,
+ "width": 37.5
+ },
+ "reopened": {
+ "root": {
+ "width": 37.5,
+ "height": 7
+ },
+ "nested": {
+ "padding": 10,
+ "width": 17.5,
+ "boundVariables": {}
+ }
+ },
+ "reopenedEdit": {
+ "value": 60,
+ "padding": 15,
+ "width": 42.5
+ }
+}
diff --git a/packages/fig/docs/observations/nested-binding-expression.md b/packages/fig/docs/observations/nested-binding-expression.md
new file mode 100644
index 000000000..dbe2a1bf8
--- /dev/null
+++ b/packages/fig/docs/observations/nested-binding-expression.md
@@ -0,0 +1,30 @@
+# Saved inherited binding expressions
+
+The source is `nested-binding-ownership-records.json`, with only the placed owner's direct
+padding declaration removed by the shared test helper. The canonical child retains Figma's
+saved `MULTIPLY(0.5, alias)` expression. Unlike the earlier synthetic inheritance test, this
+fixture does not remove that expression.
+
+An independent native Figma instance has nested padding 5 and outer width 32.5 at token 20.
+Changing the token to 40 gives padding 10 and width 37.5. This horizontal probe uses the earlier
+component-edit document; its changed top padding is not compared with the original fixture's
+vertical geometry. The reopened document and PNG below use the original fixture's top padding.
+The expression is in its own record's
+placed units: its coefficient must not be multiplied by the same instance scale again. The
+outer occurrence's 0.5 factor still applies, giving a final binding multiplier of 0.25.
+
+OpenPencil edits the token to 40 and re-encodes the document. Reopened Figma reports padding 10,
+nested width 17.5, and outer size 37.5×7. Changing the reopened token to 60 gives padding 15 and
+outer width 42.5, proving the expression remains live. It is restored to 40 before PNG capture.
+Figma's `boundVariables` projection is empty for this inherited expression; that does not mean
+it is unbound. Captures are in `nested-binding-expression.json`.
+
+`tests/fixtures/nested-binding-expression-figma.png` is the reopened 8× Figma export (300×56). Headless tests
+edit the imported token to 60 and back to 40 and compare exact decoded sRGB RGBA pixels. A
+separate browser snapshot covers the before/after geometry projection. Engine tests cover
+editor history, same-alias rebinding, and local edited re-encoding.
+
+Acceptance is limited to products of finite constants and one alias, including nested products.
+Other operators, multiple-alias products, and constant-only binding expressions are not accepted;
+they fail explicitly instead of silently losing a binding. This does not establish all expression
+forms, arbitrary expression/component-edit interactions, typography, or rescale/export lifecycle.
diff --git a/packages/fig/docs/observations/nested-binding-ownership.json b/packages/fig/docs/observations/nested-binding-ownership.json
new file mode 100644
index 000000000..4cb3441e6
--- /dev/null
+++ b/packages/fig/docs/observations/nested-binding-ownership.json
@@ -0,0 +1,121 @@
+{
+ "inherited": {
+ "value": 20,
+ "nodes": [
+ {
+ "id": "293733:8",
+ "width": 32.5,
+ "height": 7,
+ "x": 150,
+ "y": 0,
+ "paddingLeft": 10,
+ "boundVariables": {}
+ },
+ {
+ "id": "I293733:8;1:5",
+ "width": 12.5,
+ "height": 7,
+ "x": 10,
+ "y": 0,
+ "paddingLeft": 5,
+ "boundVariables": {}
+ },
+ {
+ "id": "I293733:8;1:5;1:3",
+ "width": 5,
+ "height": 5,
+ "x": 5,
+ "y": 1,
+ "boundVariables": {}
+ }
+ ]
+ },
+ "direct": {
+ "before": {
+ "value": 8,
+ "nodes": [
+ {
+ "id": "293733:8",
+ "padding": 10,
+ "width": 31.5,
+ "boundVariables": {}
+ },
+ {
+ "id": "I293733:8;1:5",
+ "padding": 4,
+ "width": 11.5,
+ "boundVariables": {
+ "paddingLeft": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ }
+ }
+ }
+ ]
+ },
+ "after": {
+ "value": 12,
+ "nodes": [
+ {
+ "id": "293733:8",
+ "padding": 10,
+ "width": 33.5,
+ "boundVariables": {}
+ },
+ {
+ "id": "I293733:8;1:5",
+ "padding": 6,
+ "width": 13.5,
+ "boundVariables": {
+ "paddingLeft": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "reencoded": {
+ "value": 12,
+ "nodes": [
+ {
+ "id": "1:7",
+ "width": 33.5,
+ "height": 7,
+ "x": 150,
+ "y": 0,
+ "padding": 10,
+ "boundVariables": {}
+ },
+ {
+ "id": "I1:7;1:5",
+ "width": 13.5,
+ "height": 7,
+ "x": 10,
+ "y": 0,
+ "padding": 6,
+ "boundVariables": {
+ "paddingLeft": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ }
+ }
+ },
+ {
+ "id": "I1:7;1:5;1:3",
+ "width": 5,
+ "height": 5,
+ "x": 6,
+ "y": 1,
+ "boundVariables": {}
+ }
+ ],
+ "after": {
+ "value": 16,
+ "width": 35.5,
+ "nestedWidth": 15.5,
+ "padding": 8
+ }
+ }
+}
diff --git a/packages/fig/docs/observations/nested-binding-ownership.md b/packages/fig/docs/observations/nested-binding-ownership.md
new file mode 100644
index 000000000..be961ce58
--- /dev/null
+++ b/packages/fig/docs/observations/nested-binding-ownership.md
@@ -0,0 +1,39 @@
+# Nested binding ownership oracle
+
+`nested-binding-ownership.json` records Figma Plugin API observations in a controlled document
+with a 0.5-scaled inner instance inside a 0.5-scaled outer instance. The inner component has a
+padding variable binding. The observed instance is identified by its exact node ID throughout.
+
+| Binding declaration | Token | Effective nested padding |
+| --------------------------------------------------------------------- | ----: | -----------------------: |
+| Inherited from the inner component | 20 | 5 |
+| Assigned directly to the nested instance through the outer occurrence | 8 | 4 |
+| Same direct binding after a token edit | 12 | 6 |
+
+The direct assignment uses the declaring outer instance's scale, not the compounded inner
+scale. Figma reports the explicit alias in the nested node's `boundVariables`; the inherited
+scaled binding is absent from that Plugin API projection despite remaining a live dependency.
+The token values are the values supplied to the variable setters immediately before capture.
+The experiment modifies only a disposable imported document, not the original Gold document.
+
+`nested-binding-ownership-records.json` contains the 12 records and three base 64 blobs from
+Figma's local-save canvas payload after the direct token reaches 12. Top-level edit attribution
+is omitted. The binding is a `parameterConsumptionMap` entry on the outer instance's
+`symbolOverrides` path `[1:5]`; the outer record retains `uniformScaleFactor: 0.5`.
+
+The document tests now retain the explicit alias, apply its declaring-owner scale, and preserve
+it through token editing, undo, and local re-encoding. A synthetic extension binds an unrelated
+inherited field to the same variable: its multiplier remains 0.25 while the direct field uses 0.5.
+Interpretation uses recorded declarations and paths, not equal values or node names.
+
+## Independent re-export acceptance
+
+The interpreted document is edited, undone, and re-encoded, then reopened in Figma. The nested
+instance retains its explicit variable alias and padding 6, with nested/outer widths 13.5/33.5.
+Changing the token from 12 to 16 in reopened Figma changes padding to 8 and widths to 15.5/35.5.
+The token is restored to 12 before capturing `tests/fixtures/nested-binding-ownership-figma.png`: a 268×56 PNG
+at scale 8. A headless raster regression edits the imported token to 16 and back to 12, then
+compares exact decoded sRGB RGBA pixels with this independent image, without fuzz or resampling.
+
+This establishes the captured imported declaration's behavior, not all new binding assignments
+through OpenPencil's APIs, scaled text metrics, or general file parity.
diff --git a/packages/fig/docs/observations/nested-definition-rescale.json b/packages/fig/docs/observations/nested-definition-rescale.json
new file mode 100644
index 000000000..99b3acaa4
--- /dev/null
+++ b/packages/fig/docs/observations/nested-definition-rescale.json
@@ -0,0 +1,55 @@
+{
+ "before": {
+ "componentId": "293885:13",
+ "instanceId": "293885:15",
+ "before": {
+ "root": {
+ "width": 16.25,
+ "height": 3.5,
+ "left": 5,
+ "right": 5
+ },
+ "nested": {
+ "width": 6.25,
+ "height": 3.5,
+ "left": 2.5,
+ "right": 1.25
+ }
+ }
+ },
+ "after": {
+ "root": {
+ "width": 22.5,
+ "height": 7,
+ "left": 5,
+ "right": 5
+ },
+ "nested": {
+ "width": 12.5,
+ "height": 7,
+ "left": 5,
+ "right": 2.5
+ },
+ "definition": {
+ "width": 50,
+ "height": 28,
+ "left": 20,
+ "right": 10
+ }
+ },
+ "reopened": {
+ "width": 22.5,
+ "height": 7,
+ "nested": {
+ "width": 12.5,
+ "height": 7,
+ "left": 5,
+ "right": 2.5
+ }
+ },
+ "token": {
+ "width": 27.5,
+ "left": 10,
+ "nestedWidth": 17.5
+ }
+}
diff --git a/packages/fig/docs/observations/nested-definition-rescale.md b/packages/fig/docs/observations/nested-definition-rescale.md
new file mode 100644
index 000000000..7ce1be2ed
--- /dev/null
+++ b/packages/fig/docs/observations/nested-definition-rescale.md
@@ -0,0 +1,21 @@
+# Definition-level rescale propagation
+
+The native fixture clones the outer component definition, creates a placed instance at scale
+0.25, then doubles the scale of the nested instance inside the definition. Before the edit,
+outer size is 16.25×3.5 and nested size 6.25×3.5, with left/right padding 2.5/1.25. Afterward,
+outer size is 22.5×7 and nested size 12.5×7, with left/right padding 5/2.5.
+
+OpenPencil imports the inherited-expression variant of `nested-binding-ownership-records.json`,
+halves the placed owner's scale, and doubles the definition child's scale. The editor's queued
+component synchronization updates occurrence coordinate scales as well as numeric properties.
+Export reopened in Figma retains matching geometry. Token 20→40 gives nested left 10, nested
+width 17.5, and outer width 27.5. The token is restored to 20.
+
+`nested-definition-rescale.json` records native before/after, reopen, and token observations.
+`tests/fixtures/nested-definition-rescale-figma.png` is the native after-edit export at 8× (180×56). The engine
+renderer matches exact decoded sRGB RGBA pixels. Engine tests separately exercise editor
+scheduling, local edited re-encoding, token updates, and coordinate metadata.
+
+This is not coverage of arbitrary scale overrides, swaps, definition-rescale undo, reparenting,
+transitive multi-definition edits, or typography. Native Plugin API restrictions on directly
+rescaling placed descendants remain described in `nested-rescale-restrictions.md`.
diff --git a/packages/fig/docs/observations/nested-layout-scale.md b/packages/fig/docs/observations/nested-layout-scale.md
new file mode 100644
index 000000000..8a1b2859b
--- /dev/null
+++ b/packages/fig/docs/observations/nested-layout-scale.md
@@ -0,0 +1,33 @@
+# Nested layout scale
+
+`nested-layout-scale.json` contains controlled Figma save payloads before and after editing a
+nested scaled auto-layout instance. The inner component uses horizontal padding 10, vertical
+padding 4, spacing 6, and a 20×20 child. Its instance is scaled by 0.5 inside an outer component
+with horizontal padding 20 and spacing 8. The placed outer instance is also scaled by 0.5.
+
+The `before` snapshot has effective outer padding 10 and inner padding 2.5. In `edited`, Figma's
+Plugin API sets outer padding to 13 and inner padding to 7. The save stores owner-relative
+padding overrides of 26 and 14 respectively, while the placed root record stores padding 13.
+Effective widths are 30/10 before and 37.5/14.5 after (outer/inner). The rectangle remains 5×5.
+
+Only the controlled page and its five scene records are retained. A document root is supplied
+by the tests. Edit attribution is omitted, and referenced geometry blobs are remapped to the
+fixture's base 64 table. The temporary page was removed after capture.
+
+Tests cover interpretation, layout recomputation, editor undo/redo, local edited re-encoding,
+and a browser canvas snapshot of the interpreted before/edited trees at 6× zoom. The snapshot
+projects only geometry and paint fields; it does not exercise browser file loading. This fixture
+does not by itself establish exported-file reopening or pixel parity in Figma.
+
+## Independent edited export acceptance
+
+Starting from `before`, the editor changes outer paddingLeft to 13 and nested paddingLeft to 7,
+then exports a new `.fig` archive. Figma reopens that archive with outer/nested widths 37.5/14.5,
+paddingLeft 13/7, and a 5×5 rectangle at nested position (7, 1). `tests/fixtures/nested-layout-scale-figma.png`
+is the reopened root's 300×56 PNG, exported through Figma's Plugin API at scale 8. The headless
+raster test compares decoded sRGB RGBA pixels at the same size without fuzz or resampling.
+The comparison has zero differing pixels.
+
+This acceptance is limited to this controlled geometry/paint fixture. It does not cover text,
+live variable updates, or general instance fidelity. Figma renames the custom-named root to its
+component name on reopening; instance-name preservation remains a separate failing contract.
diff --git a/packages/fig/docs/observations/nested-owner-rescale.json b/packages/fig/docs/observations/nested-owner-rescale.json
new file mode 100644
index 000000000..e25b98cb2
--- /dev/null
+++ b/packages/fig/docs/observations/nested-owner-rescale.json
@@ -0,0 +1,33 @@
+{
+ "native": {
+ "id": "293841:7",
+ "width": 16.5,
+ "height": 3.5,
+ "right": 3,
+ "nested": {
+ "width": 8.5,
+ "height": 3.5,
+ "left": 3,
+ "right": 3
+ }
+ },
+ "reopened": {
+ "width": 16.5,
+ "height": 3.5,
+ "right": 3,
+ "nested": {
+ "width": 8.5,
+ "left": 3,
+ "right": 3
+ }
+ },
+ "reopenedEdit": {
+ "width": 19.5,
+ "right": 4,
+ "nested": {
+ "width": 10.5,
+ "left": 4,
+ "right": 4
+ }
+ }
+}
diff --git a/packages/fig/docs/observations/nested-owner-rescale.md b/packages/fig/docs/observations/nested-owner-rescale.md
new file mode 100644
index 000000000..68667941f
--- /dev/null
+++ b/packages/fig/docs/observations/nested-owner-rescale.md
@@ -0,0 +1,23 @@
+# Rescaling a placed owner
+
+The source is `nested-binding-ownership-records.json`. Both root and nested right padding
+are bound to the direct token, as in `nested-binding-authoring.md`. A native Figma clone
+is rescaled by 0.5: outer size becomes 16.5×3.5, nested width 8.5, and the root right and
+nested left/right padding all become 3.
+
+OpenPencil performs the same binding assignments and API rescale, then exports and reopens
+in Figma. `nested-owner-rescale.json` records matching geometry. Changing the reopened
+direct token from 12 to 16 gives outer width 19.5, nested width 10.5, and padding 4.
+The token is restored to 12 afterward.
+
+`tests/fixtures/nested-owner-rescale-figma.png` is the independent native clone export at 8× (132×28).
+The reopened Figma export and OpenPencil headless rendering both match its decoded sRGB
+RGBA pixels exactly. A separate browser snapshot covers before/after graph geometry.
+
+Local tests additionally cover enlargement back to unit occurrence scale, literal padding
+claims, continued token reactivity, and preservation of derived geometry as snapshots
+rather than new authored descendant size claims. Those additional cases are local evidence,
+not independently captured Figma acceptance.
+
+This establishes rescaling the placed owner, not independently rescaling nested instances,
+reparenting, rescaled typography, structural edits, or all unloaded-page lifecycle behavior.
diff --git a/packages/fig/docs/observations/nested-protected-rescale-figma.png b/packages/fig/docs/observations/nested-protected-rescale-figma.png
new file mode 100644
index 000000000..40e0407ff
Binary files /dev/null and b/packages/fig/docs/observations/nested-protected-rescale-figma.png differ
diff --git a/packages/fig/docs/observations/nested-protected-rescale.json b/packages/fig/docs/observations/nested-protected-rescale.json
new file mode 100644
index 000000000..c059eb3f9
--- /dev/null
+++ b/packages/fig/docs/observations/nested-protected-rescale.json
@@ -0,0 +1,33 @@
+{
+ "before": {
+ "componentId": "293747:7",
+ "instanceId": "293747:9",
+ "root": {
+ "width": 20.5,
+ "height": 7,
+ "left": 5,
+ "right": 5
+ },
+ "nested": {
+ "width": 10.5,
+ "height": 7,
+ "left": 3,
+ "right": 2.5
+ }
+ },
+ "after": {
+ "width": 28,
+ "height": 14,
+ "nested": {
+ "width": 18,
+ "height": 14,
+ "left": 3,
+ "right": 5
+ }
+ },
+ "token": {
+ "width": 29,
+ "left": 4,
+ "nestedWidth": 19
+ }
+}
diff --git a/packages/fig/docs/observations/nested-protected-rescale.md b/packages/fig/docs/observations/nested-protected-rescale.md
new file mode 100644
index 000000000..efa0e4bf2
--- /dev/null
+++ b/packages/fig/docs/observations/nested-protected-rescale.md
@@ -0,0 +1,20 @@
+# Protected binding during definition rescale
+
+Native Figma clone of the already-rescaled outer component has a placed instance at scale 0.25.
+Its nested left padding is explicitly bound to the direct token 12, giving padding 3, nested
+width 10.5, and outer width 20.5. Doubling the definition child's scale changes inherited geometry:
+outer 28×14, nested 18×14, right padding 5. Explicit left padding stays 3.
+
+Changing the direct token 12→16 then gives left 4, nested 19, and outer 29. It is restored to 12.
+`nested-protected-rescale.json` contains the native observations. This confirms that the placed
+binding retains its declaring-owner units, not the newly scaled definition's units.
+
+Engine regression tests reproduce these values through the editor scheduler and verify a local
+edited export/reimport. Existing synchronization already preserves this case; no production
+change was necessary.
+
+The protected case is also exported and reopened in Figma: geometry remains outer 28×14,
+nested 18×14, and padding 3/5. Its decoded sRGB RGBA raster matches the independent native
+capture exactly at 8× (224×112), saved as `nested-protected-rescale-figma.png`.
+Multiple independently inherited binding fields, undo, and transitive dependencies are separate
+contracts.
diff --git a/packages/fig/docs/observations/nested-rescale-restrictions.json b/packages/fig/docs/observations/nested-rescale-restrictions.json
new file mode 100644
index 000000000..4cf582f98
--- /dev/null
+++ b/packages/fig/docs/observations/nested-rescale-restrictions.json
@@ -0,0 +1,25 @@
+{
+ "occurrence": [
+ {
+ "type": "INSTANCE",
+ "error": "Error: in rescale: This property cannot be overridden in an instance: size"
+ },
+ {
+ "type": "RECTANGLE",
+ "error": "Error: in rescale: This property cannot be overridden in an instance: size"
+ }
+ ],
+ "definition": {
+ "id": "293870:10",
+ "before": {
+ "width": 25,
+ "height": 14,
+ "left": 10
+ },
+ "after": {
+ "width": 50,
+ "height": 28,
+ "left": 20
+ }
+ }
+}
diff --git a/packages/fig/docs/observations/nested-rescale-restrictions.md b/packages/fig/docs/observations/nested-rescale-restrictions.md
new file mode 100644
index 000000000..f978c76de
--- /dev/null
+++ b/packages/fig/docs/observations/nested-rescale-restrictions.md
@@ -0,0 +1,16 @@
+# Native nested rescale restrictions
+
+`nested-rescale-restrictions.json` records native Figma Plugin API probes against the
+placed-owner rescale acceptance document. Calling `rescale(1)` on either its nested instance
+or rectangle descendant throws `This property cannot be overridden in an instance: size`.
+A prior `rescale(2)` probe on a cloned placed owner's nested instance throws the same error.
+
+A separate clone of the outer component definition permits rescaling its nested instance by
+2: width 25→50, height 14→28, bound left padding 10→20. These are different contexts: a child
+inside a definition is not an override of a placed occurrence.
+
+OpenPencil's Figma API rejects rescale on occurrence descendants before mutation and permits
+rescale inside component definitions. The format-neutral SceneGraph scaling operation is not
+restricted by this Plugin API policy. Tests cover unchanged rejected targets and allowed
+component-definition children. This evidence does not establish definition-edit propagation,
+export, or reparenting fidelity.
diff --git a/packages/fig/docs/observations/per-field-binding-reopen.json b/packages/fig/docs/observations/per-field-binding-reopen.json
new file mode 100644
index 000000000..13a559246
--- /dev/null
+++ b/packages/fig/docs/observations/per-field-binding-reopen.json
@@ -0,0 +1,14 @@
+{
+ "reopened": {
+ "width": 36,
+ "height": 7,
+ "left": 6,
+ "right": 5,
+ "nestedWidth": 16
+ },
+ "token": {
+ "width": 41,
+ "left": 6,
+ "right": 10
+ }
+}
diff --git a/packages/fig/docs/observations/per-field-binding-reopen.md b/packages/fig/docs/observations/per-field-binding-reopen.md
new file mode 100644
index 000000000..1afea1f2f
--- /dev/null
+++ b/packages/fig/docs/observations/per-field-binding-reopen.md
@@ -0,0 +1,18 @@
+# Per-field binding inheritance
+
+The inherited-expression fixture receives a placed left-padding binding to direct token 12
+and a definition-level right-padding binding to inherited token 20. After synchronization,
+left padding is 6 and right padding 5; outer width 36 and nested width 16.
+
+Export reopened in Figma retains those values. Changing the inherited token 20→40 changes
+right padding 5→10 and outer width 36→41, while explicitly bound left padding stays 6. The token
+is restored to 20. `per-field-binding-reopen.json` records both observations.
+
+SceneGraph synchronization merges bindings and conversion factors per field. Whole-map
+legacy protection remains effective when declared by an owner without per-field claims.
+Another owner's per-field claims must not weaken that protection; synthetic regression tests
+cover both outer-owner and self-owner combinations. The mixed legacy test is a SceneGraph
+provenance contract, not a claim that Figma writes the same internal protection representation.
+
+No pixel oracle is provided for this case. Explicit unbinding and later inheritance of another
+field are covered locally, not by this external reopen capture.
diff --git a/packages/fig/docs/observations/reader-reopen.json b/packages/fig/docs/observations/reader-reopen.json
new file mode 100644
index 000000000..154cef65f
--- /dev/null
+++ b/packages/fig/docs/observations/reader-reopen.json
@@ -0,0 +1,68 @@
+{
+ "capturedOn": "2026-09-22",
+ "figma": "126.6.12 desktop",
+ "syntheticOverrides": {
+ "instance": {
+ "name": "Card instance",
+ "width": 320,
+ "paddingLeft": 32,
+ "primaryAxisSizingMode": "FIXED"
+ },
+ "icon": {
+ "name": "icon (override)",
+ "opacity": 0.5,
+ "fillVariable": "On Surface Variant",
+ "size": [24, 24]
+ },
+ "componentIcon": { "fillVariable": "On Surface" },
+ "label": { "characters": "Overridden label", "fontSize": 18 },
+ "badge": { "fill": [0, 0, 1], "count": "42" },
+ "orphan": { "type": "INSTANCE", "mainComponent": null }
+ },
+ "syntheticOverridesB": {
+ "instance": { "name": "Panel" },
+ "box": {
+ "strokeVariable": "Accent",
+ "cornerRadius": 8,
+ "boundVariableKeys": ["cornerRadius", "strokes"]
+ },
+ "title": { "textStyle": "Heading style", "fontSize": 24 },
+ "row": {
+ "size": [200, 32],
+ "claimedSize": [180, 40],
+ "paddingLeft": 16,
+ "itemSpacing": 12,
+ "primaryAxisSizingMode": "FIXED"
+ },
+ "hidden": { "name": "hidden later", "visible": false },
+ "marker": { "mainComponent": "Star", "size": [16, 16], "claimedSize": [24, 24] },
+ "sizeClaimsApplied": false,
+ "descendantResizeSupportedByFigma": false
+ },
+ "goldPreviewEdited": {
+ "inputFrame": { "width": 376.34124755859375, "height": 39.3802604675293 },
+ "placeholder": { "fontSize": 12.471817970275879, "lineHeight": 17.816883087158203 },
+ "badgeAvatars": ["avatar04", "avatar05", "avatar06"],
+ "badgeVisibility": { "avatar": true, "home": false, "chevronRight": false, "closeIcon": true },
+ "leadingAvatarVisible": false,
+ "trailingAvatarVisible": false,
+ "trailingHasChevronDown": true
+ },
+ "material3Edited": {
+ "pages": 33,
+ "listItemMain": "Condition=1 line, Leading=Icon, Trailing=None, Show overline=False, Show supporting text=False",
+ "appBarLeadingIcons": [
+ {
+ "configuration": "Small-centered",
+ "icon": "menu",
+ "vectorFillVariable": "Schemes/On Surface Variant"
+ },
+ {
+ "configuration": "Small",
+ "icon": "arrow_back",
+ "vectorFillVariable": "Schemes/On Surface Variant"
+ }
+ ],
+ "buttonSet": { "variants": 50, "axes": ["Type", "Size", "State"] }
+ }
+}
diff --git a/packages/fig/docs/observations/reader-reopen.md b/packages/fig/docs/observations/reader-reopen.md
new file mode 100644
index 000000000..7dce48a44
--- /dev/null
+++ b/packages/fig/docs/observations/reader-reopen.md
@@ -0,0 +1,75 @@
+# Reader exports reopened in Figma
+
+Four exports from the occurrence-scoped reader, imported into Figma desktop and read back
+through the Plugin API. `reader-reopen.json` records the observations.
+
+**Synthetic overrides.** A `Card` component with a variable-bound icon, a label, and a nested
+`Badge` instance; an instance of it carrying every override kind recorded through the Figma
+API. Figma applies the root claims (name, size, padding, sizing mode) and the descendant claims
+(name, opacity, text, font size, paint on a nested instance, text inside a nested instance),
+and binds the overridden icon fill to `On Surface Variant` while the component keeps
+`On Surface`. An instance whose component was deleted before export reopens as an instance
+with no main component. Figma's own API refuses to resize that icon inside the instance, so a
+`size` claim on it is not applied; that is Figma's rule, not an export gap.
+
+Two findings came from this file and are fixed: the Figma API's `name` setter and `resize()`
+did not record instance overrides, and an override inside a nested instance was addressed by
+the enclosing component's copy of the child rather than the nested component's child, which
+Figma's own clipboard encoding of the same edit names.
+
+**Synthetic overrides, second round.** A `Panel` component with a stroked box, a heading, and an
+auto-layout `row` holding a child that is later hidden and a nested `Dot` instance named
+`marker`; an instance carrying the override kinds the first round did not cover. Figma binds the
+box stroke colour to `Accent` and its corner radius to a numeric variable resolving to 8, applies
+the `Heading style` text style to the heading, applies the row's padding, item spacing, and
+primary sizing mode, hides the hidden child, and swaps `marker` to `Star`. It ignored the `size`
+claims on `row` and `marker`, which reopened at the component's sizes; reverting a control edit
+to the component's own `row` confirmed the instance was inheriting rather than overriding.
+
+Figma does not apply those two `size` claims, and the reason is that the edit they describe does
+not exist in Figma. A descendant inside an instance cannot be resized: `resize()` through the
+Plugin API is a silent no-op on any instance descendant, in an imported file and in a component
+the API creates itself, and the handles are unavailable in the UI. Across `gold-preview.fig`,
+`material 3.fig` and `nuxtui.fig` not one size claim targets a descendant that is not an
+instance, and of the 100 that target a nested instance and differ from its record, 82 restate
+that instance's own size claim while the rest are hug heights its text produced. A descendant
+`size` claim is therefore a restatement of a nested instance's own size, never a free resize.
+
+Three encodings were tried before that was clear, each suggested by one archive and refuted by
+another, and all three are reverted: addressing path segments by `overrideKey` (`gold-preview`
+is a file of library instances and addresses every segment by key, while `material 3` uses a
+GUID for 51,332 of its segments), `overrideLevel` on descendant claims, and
+`derivedSymbolDataLayoutVersion`.
+
+OpenPencil does allow resizing a layer inside an instance, so it can hold a document Figma
+cannot represent. The writer still records those claims — the reader restores them, so the edit
+survives in OpenPencil — and Figma ignores them on open, keeping the layer at its component's
+size.
+
+Three findings came from this file and are fixed: applied shared styles (`fillStyleId`,
+`strokeStyleId`, `textStyleId`, `effectStyleId`, `gridStyleId`) were not recorded as instance
+overrides, a nested swap lost the child's correspondence to its source so later overrides on it
+were addressed by the wrong record, and the export addressed nested overrides by non-definition
+records.
+
+**gold-preview (edited).** The Input instance matches `packages/fig/tests/instance/gold-preview.test.ts`:
+three Badge instances with distinct avatar swaps, the badge icon visibility, hidden leading and
+trailing avatars, the trailing chevron, and placeholder typography. Figma recomputes the hug
+width with its own text metrics (376.34 against 375.75 saved).
+
+**material 3 (edited).** Opens with all pages after every page was loaded and exported,
+including the internal canvas that holds instances of deleted components. A List item swapped
+to another variant by its List reopens as that variant; App bar leading icons resolve to the
+icon each owner assigned; icon vectors keep their `On Surface Variant` alias. The Button set
+keeps its 50 variants and axis properties.
+
+Import was done by hand through Figma's Import dialog; inspection ran through `figma-use eval`
+and then through `visual-oracles compare interpreted-document` against each
+imported file (`--file` the exported archive, `--figma-key` the imported file). Property
+differences: synthetic instance 0 of 5 nodes, synthetic Panel instance 0 of 6 nodes, material 3
+App bar `Configuration=Small, Elevation=Flat` 0 of 25 nodes, gold-preview Input 0 of 89 nodes.
+The Panel instance has 14 geometry-only differences: four from the unapplied `size` claims, and
+the positions of its auto-layout children, which the fixture saved at the instance origin
+without a layout pass and Figma laid out. The gold-preview Input has
+91 geometry-only differences: its hug layout was snapshotted from OpenPencil's layout
+(356.34 wide) and Figma recomputed it (376.34). No pixel comparison was made.
diff --git a/packages/fig/docs/observations/styled-saved-glyphs.json b/packages/fig/docs/observations/styled-saved-glyphs.json
new file mode 100644
index 000000000..e3610a298
--- /dev/null
+++ b/packages/fig/docs/observations/styled-saved-glyphs.json
@@ -0,0 +1,380 @@
+{
+ "text": "office affine",
+ "fontFamily": "Inter",
+ "fontSize": 40,
+ "fontWeight": 400,
+ "width": 227,
+ "height": 48,
+ "fills": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0,
+ "g": 0,
+ "b": 0,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL"
+ }
+ ],
+ "styleRuns": [
+ {
+ "start": 0,
+ "length": 6,
+ "style": {
+ "fills": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.800000011920929,
+ "g": 0.10000000149011612,
+ "b": 0.20000000298023224,
+ "a": 1
+ },
+ "opacity": 0.5,
+ "visible": true,
+ "blendMode": "NORMAL"
+ }
+ ]
+ }
+ },
+ {
+ "start": 7,
+ "length": 6,
+ "style": {
+ "fills": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.10000000149011612,
+ "g": 0.30000001192092896,
+ "b": 0.800000011920929,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL"
+ }
+ ]
+ }
+ }
+ ],
+ "derivedTextGlyphs": [
+ {
+ "commandsBlob": [
+ 0, 1, 47, 186, 152, 62, 140, 46, 58, 188, 3, 117, 209, 101, 62, 140, 46, 58, 188, 47, 186,
+ 44, 62, 187, 232, 194, 60, 3, 0, 0, 232, 61, 94, 116, 113, 61, 0, 0, 168, 61, 140, 46, 250,
+ 61, 3, 94, 116, 81, 61, 117, 209, 61, 62, 94, 116, 81, 61, 140, 46, 138, 62, 3, 94, 116, 81,
+ 61, 117, 209, 181, 62, 0, 0, 168, 61, 24, 93, 214, 62, 3, 0, 0, 232, 61, 187, 232, 246, 62,
+ 47, 186, 44, 62, 93, 116, 4, 63, 3, 117, 209, 101, 62, 93, 116, 13, 63, 47, 186, 152, 62,
+ 93, 116, 13, 63, 3, 163, 139, 190, 62, 93, 116, 13, 63, 187, 232, 218, 62, 93, 116, 4, 63,
+ 3, 94, 116, 247, 62, 187, 232, 246, 62, 233, 162, 3, 63, 24, 93, 214, 62, 3, 233, 162, 11,
+ 63, 117, 209, 181, 62, 233, 162, 11, 63, 140, 46, 138, 62, 3, 233, 162, 11, 63, 117, 209,
+ 61, 62, 233, 162, 3, 63, 140, 46, 250, 61, 3, 94, 116, 247, 62, 94, 116, 113, 61, 187, 232,
+ 218, 62, 187, 232, 194, 60, 3, 163, 139, 190, 62, 140, 46, 58, 188, 47, 186, 152, 62, 140,
+ 46, 58, 188, 0, 1, 47, 186, 152, 62, 186, 232, 130, 61, 3, 93, 116, 181, 62, 186, 232, 130,
+ 61, 0, 0, 200, 62, 117, 209, 189, 61, 3, 163, 139, 218, 62, 47, 186, 248, 61, 94, 116, 227,
+ 62, 24, 93, 44, 62, 3, 24, 93, 236, 62, 24, 93, 92, 62, 24, 93, 236, 62, 140, 46, 138, 62,
+ 3, 24, 93, 236, 62, 140, 46, 166, 62, 94, 116, 227, 62, 24, 93, 190, 62, 3, 163, 139, 218,
+ 62, 163, 139, 214, 62, 0, 0, 200, 62, 94, 116, 229, 62, 3, 93, 116, 181, 62, 24, 93, 244,
+ 62, 47, 186, 152, 62, 24, 93, 244, 62, 3, 0, 0, 120, 62, 24, 93, 244, 62, 187, 232, 82, 62,
+ 94, 116, 229, 62, 3, 117, 209, 45, 62, 163, 139, 214, 62, 0, 0, 28, 62, 24, 93, 190, 62, 3,
+ 140, 46, 10, 62, 140, 46, 166, 62, 140, 46, 10, 62, 140, 46, 138, 62, 3, 140, 46, 10, 62,
+ 24, 93, 92, 62, 0, 0, 28, 62, 24, 93, 44, 62, 3, 117, 209, 45, 62, 47, 186, 248, 61, 187,
+ 232, 82, 62, 117, 209, 189, 61, 3, 0, 0, 120, 62, 186, 232, 130, 61, 47, 186, 152, 62, 186,
+ 232, 130, 61, 0
+ ],
+ "x": 0,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 0,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 233, 162, 163, 62, 233, 162, 11, 63, 2, 233, 162, 163, 62, 187, 232, 242, 62, 2, 94,
+ 116, 209, 60, 187, 232, 242, 62, 2, 94, 116, 209, 60, 233, 162, 11, 63, 2, 233, 162, 163,
+ 62, 233, 162, 11, 63, 0, 1, 47, 186, 232, 61, 0, 0, 0, 0, 2, 47, 186, 232, 61, 186, 232, 30,
+ 63, 3, 47, 186, 232, 61, 187, 232, 42, 63, 186, 232, 10, 62, 187, 232, 50, 63, 3, 93, 116,
+ 33, 62, 187, 232, 58, 63, 93, 116, 69, 62, 187, 232, 62, 63, 3, 94, 116, 105, 62, 187, 232,
+ 66, 63, 47, 186, 136, 62, 187, 232, 66, 63, 3, 163, 139, 152, 62, 187, 232, 66, 63, 163,
+ 139, 162, 62, 233, 162, 65, 63, 3, 163, 139, 172, 62, 24, 93, 64, 63, 93, 116, 177, 62, 210,
+ 69, 63, 63, 2, 70, 23, 165, 62, 47, 186, 44, 63, 3, 117, 209, 161, 62, 210, 69, 45, 63, 0,
+ 0, 156, 62, 70, 23, 46, 63, 3, 24, 93, 150, 62, 187, 232, 46, 63, 70, 23, 141, 62, 187, 232,
+ 46, 63, 3, 233, 162, 111, 62, 187, 232, 46, 63, 47, 186, 92, 62, 163, 139, 41, 63, 3, 140,
+ 46, 74, 62, 140, 46, 36, 63, 140, 46, 74, 62, 117, 209, 25, 63, 2, 140, 46, 74, 62, 0, 0, 0,
+ 0, 2, 47, 186, 232, 61, 0, 0, 0, 0, 0
+ ],
+ "x": 23.8671875,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 1,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 233, 162, 163, 62, 233, 162, 11, 63, 2, 233, 162, 163, 62, 187, 232, 242, 62, 2, 94,
+ 116, 209, 60, 187, 232, 242, 62, 2, 94, 116, 209, 60, 233, 162, 11, 63, 2, 233, 162, 163,
+ 62, 233, 162, 11, 63, 0, 1, 47, 186, 232, 61, 0, 0, 0, 0, 2, 47, 186, 232, 61, 186, 232, 30,
+ 63, 3, 47, 186, 232, 61, 187, 232, 42, 63, 186, 232, 10, 62, 187, 232, 50, 63, 3, 93, 116,
+ 33, 62, 187, 232, 58, 63, 93, 116, 69, 62, 187, 232, 62, 63, 3, 94, 116, 105, 62, 187, 232,
+ 66, 63, 47, 186, 136, 62, 187, 232, 66, 63, 3, 163, 139, 152, 62, 187, 232, 66, 63, 163,
+ 139, 162, 62, 233, 162, 65, 63, 3, 163, 139, 172, 62, 24, 93, 64, 63, 93, 116, 177, 62, 210,
+ 69, 63, 63, 2, 70, 23, 165, 62, 47, 186, 44, 63, 3, 117, 209, 161, 62, 210, 69, 45, 63, 0,
+ 0, 156, 62, 70, 23, 46, 63, 3, 24, 93, 150, 62, 187, 232, 46, 63, 70, 23, 141, 62, 187, 232,
+ 46, 63, 3, 233, 162, 111, 62, 187, 232, 46, 63, 47, 186, 92, 62, 163, 139, 41, 63, 3, 140,
+ 46, 74, 62, 140, 46, 36, 63, 140, 46, 74, 62, 117, 209, 25, 63, 2, 140, 46, 74, 62, 0, 0, 0,
+ 0, 2, 47, 186, 232, 61, 0, 0, 0, 0, 0
+ ],
+ "x": 38.28125,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 2,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 70, 23, 157, 61, 0, 0, 0, 0, 2, 70, 23, 157, 61, 233, 162, 11, 63, 2, 24, 93, 36, 62,
+ 233, 162, 11, 63, 2, 24, 93, 36, 62, 0, 0, 0, 0, 2, 70, 23, 157, 61, 0, 0, 0, 0, 0, 1, 24,
+ 93, 244, 61, 186, 232, 34, 63, 3, 140, 46, 194, 61, 186, 232, 34, 63, 117, 209, 157, 61,
+ 140, 46, 39, 63, 3, 24, 93, 116, 61, 93, 116, 43, 63, 24, 93, 116, 61, 93, 116, 49, 63, 3,
+ 24, 93, 116, 61, 93, 116, 55, 63, 117, 209, 157, 61, 47, 186, 59, 63, 3, 140, 46, 194, 61,
+ 0, 0, 64, 63, 24, 93, 244, 61, 0, 0, 64, 63, 3, 210, 69, 19, 62, 0, 0, 64, 63, 70, 23, 37,
+ 62, 47, 186, 59, 63, 3, 210, 69, 55, 62, 93, 116, 55, 63, 210, 69, 55, 62, 93, 116, 49, 63,
+ 3, 210, 69, 55, 62, 93, 116, 43, 63, 70, 23, 37, 62, 140, 46, 39, 63, 3, 210, 69, 19, 62,
+ 186, 232, 34, 63, 24, 93, 244, 61, 186, 232, 34, 63, 0
+ ],
+ "x": 52.6953125,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 3,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 47, 186, 152, 62, 140, 46, 58, 188, 3, 187, 232, 98, 62, 140, 46, 58, 188, 140, 46,
+ 42, 62, 233, 162, 203, 60, 3, 187, 232, 226, 61, 140, 46, 122, 61, 117, 209, 165, 61, 210,
+ 69, 255, 61, 3, 94, 116, 81, 61, 47, 186, 64, 62, 94, 116, 81, 61, 140, 46, 138, 62, 3, 94,
+ 116, 81, 61, 47, 186, 180, 62, 210, 69, 167, 61, 210, 69, 213, 62, 3, 163, 139, 230, 61, 0,
+ 0, 246, 62, 233, 162, 43, 62, 140, 46, 4, 63, 3, 24, 93, 100, 62, 93, 116, 13, 63, 0, 0,
+ 152, 62, 93, 116, 13, 63, 3, 93, 116, 181, 62, 93, 116, 13, 63, 70, 23, 205, 62, 0, 0, 8,
+ 63, 3, 47, 186, 228, 62, 163, 139, 2, 63, 117, 209, 243, 62, 94, 116, 241, 62, 3, 93, 116,
+ 1, 63, 117, 209, 221, 62, 210, 69, 3, 63, 233, 162, 195, 62, 2, 233, 162, 219, 62, 233, 162,
+ 195, 62, 3, 47, 186, 214, 62, 47, 186, 214, 62, 117, 209, 197, 62, 94, 116, 229, 62, 3, 70,
+ 23, 181, 62, 24, 93, 244, 62, 47, 186, 152, 62, 24, 93, 244, 62, 3, 210, 69, 127, 62, 24,
+ 93, 244, 62, 94, 116, 89, 62, 210, 69, 231, 62, 3, 0, 0, 52, 62, 24, 93, 218, 62, 186, 232,
+ 30, 62, 47, 186, 194, 62, 3, 140, 46, 10, 62, 210, 69, 171, 62, 140, 46, 10, 62, 233, 162,
+ 139, 62, 3, 140, 46, 10, 62, 163, 139, 86, 62, 163, 139, 30, 62, 163, 139, 38, 62, 3, 210,
+ 69, 51, 62, 70, 23, 237, 61, 47, 186, 88, 62, 0, 0, 184, 61, 3, 163, 139, 126, 62, 186, 232,
+ 130, 61, 47, 186, 152, 62, 186, 232, 130, 61, 3, 93, 116, 169, 62, 186, 232, 130, 61, 70,
+ 23, 183, 62, 140, 46, 154, 61, 3, 47, 186, 196, 62, 93, 116, 177, 61, 140, 46, 206, 62, 70,
+ 23, 221, 61, 3, 233, 162, 215, 62, 24, 93, 4, 62, 233, 162, 219, 62, 186, 232, 34, 62, 2,
+ 210, 69, 3, 63, 186, 232, 34, 62, 3, 93, 116, 1, 63, 187, 232, 226, 61, 163, 139, 244, 62,
+ 233, 162, 147, 61, 3, 24, 93, 230, 62, 140, 46, 10, 61, 187, 232, 206, 62, 24, 93, 52, 60,
+ 3, 233, 162, 183, 62, 140, 46, 58, 188, 47, 186, 152, 62, 140, 46, 58, 188, 0
+ ],
+ "x": 62.1875,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 4,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 24, 93, 156, 62, 140, 46, 58, 188, 3, 0, 0, 104, 62, 140, 46, 58, 188, 93, 116, 45,
+ 62, 0, 0, 192, 60, 3, 163, 139, 230, 61, 0, 0, 112, 61, 210, 69, 167, 61, 47, 186, 248, 61,
+ 3, 94, 116, 81, 61, 70, 23, 61, 62, 94, 116, 81, 61, 93, 116, 137, 62, 3, 94, 116, 81, 61,
+ 24, 93, 180, 62, 210, 69, 167, 61, 70, 23, 213, 62, 3, 163, 139, 230, 61, 0, 0, 246, 62,
+ 233, 162, 43, 62, 140, 46, 4, 63, 3, 24, 93, 100, 62, 93, 116, 13, 63, 0, 0, 152, 62, 93,
+ 116, 13, 63, 3, 117, 209, 173, 62, 93, 116, 13, 63, 70, 23, 195, 62, 117, 209, 9, 63, 3, 24,
+ 93, 216, 62, 140, 46, 6, 63, 117, 209, 233, 62, 0, 0, 252, 62, 3, 210, 69, 251, 62, 117,
+ 209, 235, 62, 117, 209, 2, 63, 70, 23, 209, 62, 3, 0, 0, 8, 63, 24, 93, 182, 62, 0, 0, 8,
+ 63, 210, 69, 143, 62, 2, 0, 0, 8, 63, 140, 46, 122, 62, 2, 187, 232, 226, 61, 140, 46, 122,
+ 62, 2, 187, 232, 226, 61, 140, 46, 162, 62, 2, 24, 93, 228, 62, 140, 46, 162, 62, 3, 24, 93,
+ 228, 62, 117, 209, 185, 62, 187, 232, 218, 62, 24, 93, 204, 62, 3, 233, 162, 209, 62, 187,
+ 232, 222, 62, 24, 93, 192, 62, 233, 162, 233, 62, 3, 210, 69, 175, 62, 24, 93, 244, 62, 0,
+ 0, 152, 62, 24, 93, 244, 62, 3, 47, 186, 124, 62, 24, 93, 244, 62, 210, 69, 87, 62, 233,
+ 162, 231, 62, 3, 140, 46, 50, 62, 70, 23, 219, 62, 140, 46, 30, 62, 187, 232, 198, 62, 3,
+ 140, 46, 10, 62, 47, 186, 178, 62, 140, 46, 10, 62, 233, 162, 155, 62, 2, 140, 46, 10, 62,
+ 186, 232, 130, 62, 3, 140, 46, 10, 62, 163, 139, 70, 62, 0, 0, 32, 62, 163, 139, 26, 62, 3,
+ 140, 46, 54, 62, 117, 209, 221, 61, 94, 116, 93, 62, 0, 0, 176, 61, 3, 24, 93, 130, 62, 186,
+ 232, 130, 61, 24, 93, 156, 62, 186, 232, 130, 61, 3, 210, 69, 173, 62, 186, 232, 130, 61,
+ 187, 232, 186, 62, 117, 209, 149, 61, 3, 47, 186, 200, 62, 93, 116, 169, 61, 47, 186, 210,
+ 62, 0, 0, 208, 61, 3, 47, 186, 220, 62, 210, 69, 247, 61, 140, 46, 226, 62, 47, 186, 24, 62,
+ 2, 117, 209, 5, 63, 93, 116, 1, 62, 3, 163, 139, 2, 63, 163, 139, 174, 61, 233, 162, 245,
+ 62, 70, 23, 93, 61, 3, 140, 46, 230, 62, 70, 23, 189, 60, 93, 116, 207, 62, 140, 46, 186,
+ 59, 3, 47, 186, 184, 62, 140, 46, 58, 188, 24, 93, 156, 62, 140, 46, 58, 188, 0
+ ],
+ "x": 84.53125,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 5,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [0],
+ "x": 107.8125,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 6,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 187, 232, 114, 62, 94, 116, 81, 188, 3, 117, 209, 61, 62, 94, 116, 81, 188, 163, 139,
+ 18, 62, 70, 23, 221, 59, 3, 163, 139, 206, 61, 140, 46, 218, 60, 233, 162, 155, 61, 186,
+ 232, 130, 61, 3, 94, 116, 81, 61, 0, 0, 208, 61, 94, 116, 81, 61, 163, 139, 30, 62, 3, 94,
+ 116, 81, 61, 163, 139, 78, 62, 163, 139, 142, 61, 24, 93, 108, 62, 3, 24, 93, 180, 61, 210,
+ 69, 133, 62, 233, 162, 243, 61, 117, 209, 141, 62, 3, 93, 116, 25, 62, 24, 93, 150, 62, 233,
+ 162, 63, 62, 163, 139, 154, 62, 3, 140, 46, 102, 62, 186, 232, 158, 62, 163, 139, 134, 62,
+ 93, 116, 161, 62, 3, 0, 0, 160, 62, 47, 186, 164, 62, 117, 209, 175, 62, 24, 93, 166, 62, 3,
+ 117, 209, 191, 62, 140, 46, 168, 62, 70, 23, 199, 62, 24, 93, 172, 62, 3, 163, 139, 206, 62,
+ 163, 139, 176, 62, 163, 139, 206, 62, 187, 232, 186, 62, 2, 163, 139, 206, 62, 24, 93, 188,
+ 62, 3, 163, 139, 206, 62, 210, 69, 215, 62, 117, 209, 191, 62, 140, 46, 230, 62, 3, 210, 69,
+ 177, 62, 70, 23, 245, 62, 233, 162, 147, 62, 70, 23, 245, 62, 3, 117, 209, 105, 62, 70, 23,
+ 245, 62, 187, 232, 70, 62, 233, 162, 231, 62, 3, 0, 0, 36, 62, 140, 46, 218, 62, 117, 209,
+ 21, 62, 187, 232, 202, 62, 2, 47, 186, 136, 61, 94, 116, 217, 62, 3, 24, 93, 180, 61, 187,
+ 232, 242, 62, 70, 23, 253, 61, 163, 139, 0, 63, 3, 210, 69, 35, 62, 47, 186, 7, 63, 163,
+ 139, 78, 62, 163, 139, 10, 63, 3, 140, 46, 122, 62, 93, 116, 13, 63, 140, 46, 146, 62, 93,
+ 116, 13, 63, 3, 233, 162, 159, 62, 93, 116, 13, 63, 70, 23, 177, 62, 117, 209, 11, 63, 3,
+ 47, 186, 194, 62, 210, 69, 10, 63, 70, 23, 211, 62, 24, 93, 5, 63, 3, 233, 162, 227, 62, 93,
+ 116, 0, 63, 163, 139, 238, 62, 70, 23, 237, 62, 3, 94, 116, 249, 62, 210, 69, 217, 62, 94,
+ 116, 249, 62, 0, 0, 184, 62, 2, 94, 116, 249, 62, 0, 0, 0, 0, 2, 163, 139, 206, 62, 0, 0, 0,
+ 0, 2, 163, 139, 206, 62, 210, 69, 151, 61, 2, 24, 93, 204, 62, 210, 69, 151, 61, 3, 0, 0,
+ 200, 62, 117, 209, 101, 61, 117, 209, 189, 62, 186, 232, 18, 61, 3, 233, 162, 179, 62, 0, 0,
+ 128, 60, 47, 186, 162, 62, 140, 46, 186, 58, 3, 117, 209, 145, 62, 94, 116, 81, 188, 187,
+ 232, 114, 62, 94, 116, 81, 188, 0, 1, 0, 0, 128, 62, 0, 0, 128, 61, 3, 93, 116, 153, 62, 0,
+ 0, 128, 61, 187, 232, 170, 62, 0, 0, 168, 61, 3, 163, 139, 188, 62, 0, 0, 208, 61, 93, 116,
+ 197, 62, 233, 162, 7, 62, 3, 163, 139, 206, 62, 210, 69, 39, 62, 163, 139, 206, 62, 140, 46,
+ 74, 62, 2, 163, 139, 206, 62, 24, 93, 140, 62, 3, 117, 209, 203, 62, 70, 23, 137, 62, 163,
+ 139, 194, 62, 24, 93, 134, 62, 3, 93, 116, 185, 62, 117, 209, 131, 62, 93, 116, 173, 62,
+ 117, 209, 129, 62, 3, 233, 162, 161, 62, 0, 0, 128, 62, 24, 93, 150, 62, 70, 23, 125, 62, 3,
+ 210, 69, 139, 62, 163, 139, 122, 62, 24, 93, 132, 62, 47, 186, 120, 62, 3, 210, 69, 103, 62,
+ 24, 93, 116, 62, 140, 46, 74, 62, 163, 139, 106, 62, 3, 93, 116, 45, 62, 70, 23, 97, 62,
+ 233, 162, 27, 62, 117, 209, 77, 62, 3, 140, 46, 10, 62, 187, 232, 58, 62, 140, 46, 10, 62,
+ 140, 46, 26, 62, 3, 140, 46, 10, 62, 187, 232, 218, 61, 210, 69, 43, 62, 70, 23, 173, 61, 3,
+ 47, 186, 76, 62, 0, 0, 128, 61, 0, 0, 128, 62, 0, 0, 128, 61, 0
+ ],
+ "x": 119.0625,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 7,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 233, 162, 163, 62, 233, 162, 11, 63, 2, 233, 162, 163, 62, 187, 232, 242, 62, 2, 94,
+ 116, 209, 60, 187, 232, 242, 62, 2, 94, 116, 209, 60, 233, 162, 11, 63, 2, 233, 162, 163,
+ 62, 233, 162, 11, 63, 0, 1, 47, 186, 232, 61, 0, 0, 0, 0, 2, 47, 186, 232, 61, 186, 232, 30,
+ 63, 3, 47, 186, 232, 61, 187, 232, 42, 63, 186, 232, 10, 62, 187, 232, 50, 63, 3, 93, 116,
+ 33, 62, 187, 232, 58, 63, 93, 116, 69, 62, 187, 232, 62, 63, 3, 94, 116, 105, 62, 187, 232,
+ 66, 63, 47, 186, 136, 62, 187, 232, 66, 63, 3, 163, 139, 152, 62, 187, 232, 66, 63, 163,
+ 139, 162, 62, 233, 162, 65, 63, 3, 163, 139, 172, 62, 24, 93, 64, 63, 93, 116, 177, 62, 210,
+ 69, 63, 63, 2, 70, 23, 165, 62, 47, 186, 44, 63, 3, 117, 209, 161, 62, 210, 69, 45, 63, 0,
+ 0, 156, 62, 70, 23, 46, 63, 3, 24, 93, 150, 62, 187, 232, 46, 63, 70, 23, 141, 62, 187, 232,
+ 46, 63, 3, 233, 162, 111, 62, 187, 232, 46, 63, 47, 186, 92, 62, 163, 139, 41, 63, 3, 140,
+ 46, 74, 62, 140, 46, 36, 63, 140, 46, 74, 62, 117, 209, 25, 63, 2, 140, 46, 74, 62, 0, 0, 0,
+ 0, 2, 47, 186, 232, 61, 0, 0, 0, 0, 0
+ ],
+ "x": 141.6015625,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 8,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 233, 162, 163, 62, 233, 162, 11, 63, 2, 233, 162, 163, 62, 187, 232, 242, 62, 2, 94,
+ 116, 209, 60, 187, 232, 242, 62, 2, 94, 116, 209, 60, 233, 162, 11, 63, 2, 233, 162, 163,
+ 62, 233, 162, 11, 63, 0, 1, 47, 186, 232, 61, 0, 0, 0, 0, 2, 47, 186, 232, 61, 186, 232, 30,
+ 63, 3, 47, 186, 232, 61, 187, 232, 42, 63, 186, 232, 10, 62, 187, 232, 50, 63, 3, 93, 116,
+ 33, 62, 187, 232, 58, 63, 93, 116, 69, 62, 187, 232, 62, 63, 3, 94, 116, 105, 62, 187, 232,
+ 66, 63, 47, 186, 136, 62, 187, 232, 66, 63, 3, 163, 139, 152, 62, 187, 232, 66, 63, 163,
+ 139, 162, 62, 233, 162, 65, 63, 3, 163, 139, 172, 62, 24, 93, 64, 63, 93, 116, 177, 62, 210,
+ 69, 63, 63, 2, 70, 23, 165, 62, 47, 186, 44, 63, 3, 117, 209, 161, 62, 210, 69, 45, 63, 0,
+ 0, 156, 62, 70, 23, 46, 63, 3, 24, 93, 150, 62, 187, 232, 46, 63, 70, 23, 141, 62, 187, 232,
+ 46, 63, 3, 233, 162, 111, 62, 187, 232, 46, 63, 47, 186, 92, 62, 163, 139, 41, 63, 3, 140,
+ 46, 74, 62, 140, 46, 36, 63, 140, 46, 74, 62, 117, 209, 25, 63, 2, 140, 46, 74, 62, 0, 0, 0,
+ 0, 2, 47, 186, 232, 61, 0, 0, 0, 0, 0
+ ],
+ "x": 156.015625,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 9,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 70, 23, 157, 61, 0, 0, 0, 0, 2, 70, 23, 157, 61, 233, 162, 11, 63, 2, 24, 93, 36, 62,
+ 233, 162, 11, 63, 2, 24, 93, 36, 62, 0, 0, 0, 0, 2, 70, 23, 157, 61, 0, 0, 0, 0, 0, 1, 24,
+ 93, 244, 61, 186, 232, 34, 63, 3, 140, 46, 194, 61, 186, 232, 34, 63, 117, 209, 157, 61,
+ 140, 46, 39, 63, 3, 24, 93, 116, 61, 93, 116, 43, 63, 24, 93, 116, 61, 93, 116, 49, 63, 3,
+ 24, 93, 116, 61, 93, 116, 55, 63, 117, 209, 157, 61, 47, 186, 59, 63, 3, 140, 46, 194, 61,
+ 0, 0, 64, 63, 24, 93, 244, 61, 0, 0, 64, 63, 3, 210, 69, 19, 62, 0, 0, 64, 63, 70, 23, 37,
+ 62, 47, 186, 59, 63, 3, 210, 69, 55, 62, 93, 116, 55, 63, 210, 69, 55, 62, 93, 116, 49, 63,
+ 3, 210, 69, 55, 62, 93, 116, 43, 63, 70, 23, 37, 62, 140, 46, 39, 63, 3, 210, 69, 19, 62,
+ 186, 232, 34, 63, 24, 93, 244, 61, 186, 232, 34, 63, 0
+ ],
+ "x": 170.4296875,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 10,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 24, 93, 36, 62, 0, 0, 168, 62, 2, 24, 93, 36, 62, 0, 0, 0, 0, 2, 70, 23, 157, 61, 0,
+ 0, 0, 0, 2, 70, 23, 157, 61, 233, 162, 11, 63, 2, 93, 116, 33, 62, 233, 162, 11, 63, 2, 93,
+ 116, 33, 62, 233, 162, 235, 62, 2, 47, 186, 40, 62, 233, 162, 235, 62, 3, 24, 93, 60, 62,
+ 93, 116, 0, 63, 24, 93, 100, 62, 186, 232, 6, 63, 3, 140, 46, 134, 62, 93, 116, 13, 63, 117,
+ 209, 165, 62, 93, 116, 13, 63, 3, 140, 46, 194, 62, 93, 116, 13, 63, 94, 116, 215, 62, 233,
+ 162, 7, 63, 3, 47, 186, 236, 62, 186, 232, 1, 63, 163, 139, 248, 62, 24, 93, 236, 62, 3,
+ 140, 46, 2, 63, 70, 23, 213, 62, 140, 46, 2, 63, 93, 116, 177, 62, 2, 140, 46, 2, 63, 0, 0,
+ 0, 0, 2, 94, 116, 217, 62, 0, 0, 0, 0, 2, 94, 116, 217, 62, 163, 139, 174, 62, 3, 94, 116,
+ 217, 62, 93, 116, 207, 62, 24, 93, 200, 62, 117, 209, 225, 62, 3, 210, 69, 183, 62, 24, 93,
+ 244, 62, 93, 116, 153, 62, 24, 93, 244, 62, 3, 186, 232, 132, 62, 24, 93, 244, 62, 94, 116,
+ 105, 62, 94, 116, 235, 62, 3, 93, 116, 73, 62, 163, 139, 226, 62, 187, 232, 54, 62, 94, 116,
+ 209, 62, 3, 24, 93, 36, 62, 24, 93, 192, 62, 24, 93, 36, 62, 0, 0, 168, 62, 0
+ ],
+ "x": 179.921875,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 11,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": [
+ 0, 1, 24, 93, 156, 62, 140, 46, 58, 188, 3, 0, 0, 104, 62, 140, 46, 58, 188, 93, 116, 45,
+ 62, 0, 0, 192, 60, 3, 163, 139, 230, 61, 0, 0, 112, 61, 210, 69, 167, 61, 47, 186, 248, 61,
+ 3, 94, 116, 81, 61, 70, 23, 61, 62, 94, 116, 81, 61, 93, 116, 137, 62, 3, 94, 116, 81, 61,
+ 24, 93, 180, 62, 210, 69, 167, 61, 70, 23, 213, 62, 3, 163, 139, 230, 61, 0, 0, 246, 62,
+ 233, 162, 43, 62, 140, 46, 4, 63, 3, 24, 93, 100, 62, 93, 116, 13, 63, 0, 0, 152, 62, 93,
+ 116, 13, 63, 3, 117, 209, 173, 62, 93, 116, 13, 63, 70, 23, 195, 62, 117, 209, 9, 63, 3, 24,
+ 93, 216, 62, 140, 46, 6, 63, 117, 209, 233, 62, 0, 0, 252, 62, 3, 210, 69, 251, 62, 117,
+ 209, 235, 62, 117, 209, 2, 63, 70, 23, 209, 62, 3, 0, 0, 8, 63, 24, 93, 182, 62, 0, 0, 8,
+ 63, 210, 69, 143, 62, 2, 0, 0, 8, 63, 140, 46, 122, 62, 2, 187, 232, 226, 61, 140, 46, 122,
+ 62, 2, 187, 232, 226, 61, 140, 46, 162, 62, 2, 24, 93, 228, 62, 140, 46, 162, 62, 3, 24, 93,
+ 228, 62, 117, 209, 185, 62, 187, 232, 218, 62, 24, 93, 204, 62, 3, 233, 162, 209, 62, 187,
+ 232, 222, 62, 24, 93, 192, 62, 233, 162, 233, 62, 3, 210, 69, 175, 62, 24, 93, 244, 62, 0,
+ 0, 152, 62, 24, 93, 244, 62, 3, 47, 186, 124, 62, 24, 93, 244, 62, 210, 69, 87, 62, 233,
+ 162, 231, 62, 3, 140, 46, 50, 62, 70, 23, 219, 62, 140, 46, 30, 62, 187, 232, 198, 62, 3,
+ 140, 46, 10, 62, 47, 186, 178, 62, 140, 46, 10, 62, 233, 162, 155, 62, 2, 140, 46, 10, 62,
+ 186, 232, 130, 62, 3, 140, 46, 10, 62, 163, 139, 70, 62, 0, 0, 32, 62, 163, 139, 26, 62, 3,
+ 140, 46, 54, 62, 117, 209, 221, 61, 94, 116, 93, 62, 0, 0, 176, 61, 3, 24, 93, 130, 62, 186,
+ 232, 130, 61, 24, 93, 156, 62, 186, 232, 130, 61, 3, 210, 69, 173, 62, 186, 232, 130, 61,
+ 187, 232, 186, 62, 117, 209, 149, 61, 3, 47, 186, 200, 62, 93, 116, 169, 61, 47, 186, 210,
+ 62, 0, 0, 208, 61, 3, 47, 186, 220, 62, 210, 69, 247, 61, 140, 46, 226, 62, 47, 186, 24, 62,
+ 2, 117, 209, 5, 63, 93, 116, 1, 62, 3, 163, 139, 2, 63, 163, 139, 174, 61, 233, 162, 245,
+ 62, 70, 23, 93, 61, 3, 140, 46, 230, 62, 70, 23, 189, 60, 93, 116, 207, 62, 140, 46, 186,
+ 59, 3, 47, 186, 184, 62, 140, 46, 58, 188, 24, 93, 156, 62, 140, 46, 58, 188, 0
+ ],
+ "x": 203.3203125,
+ "y": 38.54545593261719,
+ "fontSize": 40,
+ "firstCharacter": 12,
+ "rotation": 0
+ }
+ ]
+}
diff --git a/packages/fig/docs/observations/styled-saved-glyphs.md b/packages/fig/docs/observations/styled-saved-glyphs.md
new file mode 100644
index 000000000..39a8be596
--- /dev/null
+++ b/packages/fig/docs/observations/styled-saved-glyphs.md
@@ -0,0 +1,7 @@
+# Styled saved glyph fixture
+
+`styled-saved-glyphs.json` is a reduced SceneGraph conversion of a temporary Figma-authored text node containing `office affine` at 40 px Inter Regular. The first word has a red solid fill at 50% opacity; the second has a blue solid fill. The node was captured from Figma's Save local copy canvas payload, then the temporary page was removed.
+
+Only typography, dimensions, fills, style runs, and saved glyph outlines/character indices are retained. This is not a full document or font binary. It contains 13 glyphs for 13 characters and **does not prove ligature coverage**.
+
+Used by `tests/e2e/canvas/saved-glyph-visual.spec.ts`. The synthetic cluster case in that test and the renderer pixel assertions separately verify cluster-to-run selection and inherited paint.
diff --git a/packages/fig/docs/source-model.md b/packages/fig/docs/source-model.md
new file mode 100644
index 000000000..949e8dc97
--- /dev/null
+++ b/packages/fig/docs/source-model.md
@@ -0,0 +1,91 @@
+# Source model
+
+```text
+Source archive
+ +-- node-change records ----> source index (GUID -> record)
+ +-- blobs ------------------> geometry / saved glyph payloads
+ +-- images -----------------> content-addressed image resources
+ +-- schema/version ---------> decoding and later export
+
+Selected pages
+ -> content dependencies -> required component trees
+ -> ownership ancestors, not all their siblings
+```
+
+## Vocabulary and identity
+
+| Term | Meaning |
+| --- | --- |
+| Source record | A node-change record identified by its archive GUID. |
+| Component definition | The source tree expanded by an instance. |
+| Occurrence | One use of a source node within a particular expansion. |
+| Owner | The occurrence whose component scope declares or applies a claim. |
+| Claim | A property contribution retaining its origin and target address. |
+| Materialized node | An editable SceneGraph node created for an occurrence or source. |
+
+```text
+Component A
+ +-- nested instance ----------------------> Component B
+ +-- Label occurrence
+ +-- source: B's Label
+ +-- outer correspondence: Label in A's expanded instance
+ +-- address within A: [nested instance, Label]
+
+Another use of A -> another Label occurrence, not the same mutable node
+```
+
+**Required invariant:** main-component identity, source correspondence, and occurrence address
+are distinct. Names, geometry, variant-value similarity, and terminal-GUID matches do not
+establish occurrence identity.
+
+```text
+Use Source node Owner-relative address
+------------------- -------------- ----------------------
+Badge A / Label 1:42 [Badge A, 1:42]
+Badge B / Label 1:42 [Badge B, 1:42]
+ ^ same source ^ different occurrences
+```
+
+The names above label the example; real addresses use source identities, not those labels.
+Matching only `1:42` loses which occurrence is targeted.
+
+## Resources and dependencies
+
+Variable collections/variables are not scene children. Internal source pages can retain
+resources that are not live content. Dependency discovery follows selected page trees,
+component references, supported INSTANCE_SWAP defaults/assignments, and preferred choices.
+Ownership ancestors do not imply that unrelated siblings must be expanded.
+
+Components the archive no longer contains are reported by the closure as
+`missingComponentIds`; broken hierarchy or style references remain fatal `missingIds`. Figma
+keeps instances of deleted components, so with `onMissingComponent` the interpreter keeps such
+an instance as a childless occurrence that retains its saved reference and reports the owner;
+without it, expansion fails. Unavailable preferred choices are recorded separately as external
+choices. Neither permits ignoring a missing effective dependency silently.
+
+`ancestorPathBeforeDeletion` alone is **not** a liveness flag: Figma can retain it on live
+component sets. Current hierarchy and reference semantics must be considered independently.
+
+## Ownership
+
+- Record-based reading copies caller-supplied records.
+- Archive-owned reading takes ownership of records it parses, avoiding a second full tree.
+- Exposed source/resource snapshots are copied.
+- Evaluations produce independently mutable occurrence data.
+- Blob and image references must remain valid across transfer and export.
+
+Do not replace copying with shared mutable objects merely to improve memory measurements.
+
+## Implementation and tests
+
+- [Dependency closure](../src/document/dependency-closure.ts)
+- [Component dependencies](../src/document/component/dependencies.ts)
+- [Resource references](../src/document/resource-reference.ts)
+- [Property-definition ancestry](../src/document/property-inheritance.ts)
+- [Closure tests](../tests/document/dependency-closure.test.ts)
+- [Deletion-history tests](../tests/document/retained-records.test.ts)
+- [Archive ownership tests](../tests/document/archive-assembly.test.ts)
+
+**Known limitation:** reference coverage, retained-resource export, and large-document memory
+usage still require corpus-wide acceptance. A discovered dependency closure is not proof that
+every record in the archive has been understood.
diff --git a/packages/fig/docs/validation.md b/packages/fig/docs/validation.md
new file mode 100644
index 000000000..bc8f16b76
--- /dev/null
+++ b/packages/fig/docs/validation.md
@@ -0,0 +1,116 @@
+# Validation
+
+```text
+Figma-authored archive
+ |
+ v
+ new reader ------> direct renderer ------> compare Figma image
+ |
+ v
+ editor action -> undo/redo -> export
+ |
+ +------------+-------------+
+ | |
+ v v
+ new reader Figma reopen
+ | |
+ state assertions state + actions + image
+```
+
+## Distinct contracts
+
+| Check | Proves | Does not prove |
+| --- | --- | --- |
+| Encoded-field assertions | Requested records were emitted | Figma interprets them correctly |
+| OpenPencil round trip | Reader and writer agree on tested behavior | Independent format correctness |
+| Figma property comparison | Tested effective properties match | Actual pixels or untested metadata |
+| Direct render comparison | New-reader graph renders similarly | Export/reopen fidelity |
+| Figma reopen and interaction | External interpretation and tested editing work | All documents/features work |
+
+**Required invariant:** Figma is the compatibility oracle. Round-trip stability through our own
+reader proves only that we are self-consistent.
+
+## Comparison discipline
+
+- Verify the active Figma file key and target before capture.
+- Use world-space coordinates; group-relative conventions can differ between APIs.
+- Capture complete trees, including hidden descendants. Report hidden geometry separately.
+- Match bounds, scale, fonts, and color space before measuring pixels.
+- Use native resolution or increased export scale; do not downsample away differences.
+- Do not judge rendering by exporting and reimporting through our own reader.
+- Separate font availability from exact binary identity.
+- Compare edited output to the same edit in original Figma, not an unchanged original.
+- After mutation, allow dependent state to settle before reading the result.
+- Inspect images as well as numbers. Small aggregate differences can hide wrong icons.
+
+Use temporary clones for destructive oracle edits and verify cleanup. Record stable fixture
+provenance next to the fixture, not transient cloud-file IDs in architecture documents.
+
+## Maintained property comparison
+
+Run from the repository root, with the matching Figma document open:
+
+```sh
+bun open-pencil-visual-oracles compare interpreted-document \
+ --file tests/fixtures/gold-preview.fig --node 1:3461 \
+ --figma-key NmoHzskYNiSKOaRX14bMdw --output /tmp/gold-oracle
+```
+
+This writes source/actual captures, differences, and grouped diagnostics. It checks selected
+properties, not pixels. `--allow-partial-assignments` is diagnostic-only: skipped assignments
+are recorded and cause a nonzero exit. It does not turn partial interpretation into success.
+
+The same command is the reopen check for an export: import the exported archive into Figma
+(the desktop app has no scriptable import; drag the file onto Drafts), pass that archive as
+`--file` and the imported file's key, and the comparison reads Figma's interpretation of the
+export against the reader's. Captures target the active document, so bring the imported
+file's tab to the front first:
+
+```sh
+bun open-pencil-visual-oracles activate-tab --title gold-preview-edited
+```
+
+Property and structural differences are export defects. Geometry differences on hug and fill
+layouts are expected: the reader applies saved derived geometry without a layout pass, while
+Figma recomputes layout with its own text metrics. See [the reopen log](./observations/reader-reopen.md) for
+a recorded run.
+
+- [Comparison and capture implementation](../../../tools/generate/visual-oracles/src/document/)
+- [Command implementation](../../../tools/generate/visual-oracles/src/operations/compare/interpreted-document.ts)
+
+## Gates and regression placement
+
+Use package tests for interpretation/export contracts, engine tests for shared editing/session
+behavior, and committed Playwright snapshots for pixel-affecting renderer changes. Update a
+snapshot only with an explained change and rerun without snapshot updates. Isolate both the
+application server and MCP endpoint; reusing another worktree's server invalidates attribution.
+
+```sh
+bun run check
+bun test packages/fig/tests tests/engine/io/fig/session
+```
+
+The complete repository test requirements remain in [AGENTS.md](../../../AGENTS.md).
+
+**Known limitation:** a single automated workflow for full edited/unedited Figma visual
+round trips is not yet complete. Corpus acceptance must cover Gold, shadcn, Material 3, and
+nuxtui, with strictness, performance, and page-loading equivalence tracked separately. Counts
+and timings from individual runs belong in result artifacts or the integration PR.
+
+## Render check
+
+`visual-oracles interpret-instance` renders an interpreted instance through Skia and, with
+`--figma-key`, exports the same node from the open Figma document for comparison:
+
+```sh
+bun open-pencil-visual-oracles interpret-instance \
+ --file tests/fixtures/gold-preview.fig --node 1:3503 \
+ --scale 2 --output /tmp/gold-input-comparison
+```
+
+It verifies the active file key and calls `exportAsync` with an explicit scale rather than
+relying on saved export settings. Outputs are `interpreted.png`, `report.json` with font
+status, unresolved paths and node bounds, and with a key `figma.png` and `figma-bounds.json`.
+
+`visual-oracles compare interpreted-document` does the same for a whole archive against the
+document opened in Figma, reporting property and geometry differences per node.
diff --git a/packages/fig/package.json b/packages/fig/package.json
index dd329bb0d..f5b178537 100644
--- a/packages/fig/package.json
+++ b/packages/fig/package.json
@@ -2,7 +2,24 @@
"name": "@open-pencil/fig",
"version": "0.15.1",
"license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/open-pencil/open-pencil.git",
+ "directory": "packages/fig"
+ },
+ "files": [
+ "dist",
+ "src",
+ "README.md"
+ ],
"type": "module",
+ "sideEffects": false,
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "imports": {
+ "#fig/*": "./src/*.ts",
+ "#fig-tests/*": "./tests/*.ts"
+ },
"exports": {
".": {
"types": "./dist/index.d.ts",
@@ -29,14 +46,10 @@
"default": "./dist/instance-overrides.js"
}
},
- "main": "./dist/index.js",
- "types": "./dist/index.d.ts",
- "sideEffects": false,
- "files": [
- "dist",
- "src",
- "README.md"
- ],
+ "publishConfig": {
+ "access": "public",
+ "provenance": true
+ },
"scripts": {
"build": "bunx tsdown --config tsdown.config.ts",
"check": "bun run typecheck && bun run test && bun run build && bun run smoke:dist",
@@ -45,19 +58,6 @@
"test": "bun test tests",
"typecheck": "bunx tsc --noEmit -p tsconfig.test.json"
},
- "repository": {
- "type": "git",
- "url": "git+https://github.com/open-pencil/open-pencil.git",
- "directory": "packages/fig"
- },
- "publishConfig": {
- "access": "public",
- "provenance": true
- },
- "peerDependencies": {
- "@open-pencil/kiwi": "workspace:*",
- "@open-pencil/scene-graph": "workspace:*"
- },
"dependencies": {
"es-toolkit": "^1.51.0",
"fflate": "^0.8.3",
@@ -67,5 +67,9 @@
"@types/bun": "^1.3.14",
"tsdown": "^0.22.14",
"typescript": "~5.8.3"
+ },
+ "peerDependencies": {
+ "@open-pencil/kiwi": "workspace:*",
+ "@open-pencil/scene-graph": "workspace:*"
}
}
diff --git a/packages/fig/scripts/smoke-dist.ts b/packages/fig/scripts/smoke-dist.ts
index 6c6766fef..2ed3b7da4 100644
--- a/packages/fig/scripts/smoke-dist.ts
+++ b/packages/fig/scripts/smoke-dist.ts
@@ -5,11 +5,11 @@ const instanceOverrides = await import('../dist/instance-overrides.js')
const nodeChange = await import('../dist/node-change.js')
if (
- mod.FIG_PACKAGE_STATUS !== 'archive-api' ||
+ mod.FIG_PACKAGE_STATUS !== 'document-reader' ||
typeof mod.effectiveFigmaRawNodeFields !== 'function' ||
typeof mod.parseFigBuffer !== 'function' ||
typeof mod.writeFigArchive !== 'function' ||
- typeof instanceOverrides.populateAndApplyOverrides !== 'function' ||
+ typeof instanceOverrides.interpretInstance !== 'function' ||
typeof nodeChange.convertLineHeight !== 'function' ||
typeof nodeChange.sceneNodeToKiwi !== 'function'
) {
diff --git a/packages/fig/src/clipboard/import.ts b/packages/fig/src/clipboard/import.ts
index 740092fad..ae29cd6a9 100644
--- a/packages/fig/src/clipboard/import.ts
+++ b/packages/fig/src/clipboard/import.ts
@@ -3,17 +3,9 @@ import { decode as decodeText, toUint8Array, isValid } from 'js-base64'
import type { NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/codec'
import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi/schema-runtime'
-import type { SceneGraph } from '@open-pencil/scene-graph'
-import { populateAndApplyOverrides, type InstanceNodeChange } from '../instance-overrides'
-import {
- nodeChangeToProps,
- linkImportedInstanceChildren,
- shouldImportTextAsAutoSize,
- sortChildren,
- parseFigKiwiChunks,
- decompressFigKiwiDataAsync
-} from '../node-change'
+import { parseFigKiwiChunks, decompressFigKiwiDataAsync } from '../node-change'
+import { isFigClipboardVisualType } from '../node-classification'
interface FigmaClipboardMeta {
fileKey: string
@@ -57,35 +49,12 @@ export async function parseFigmaClipboard(
}
}
-const NON_VISUAL_TYPES = new Set([
- 'DOCUMENT',
- 'CANVAS',
- 'VARIABLE_SET',
- 'VARIABLE',
- 'VARIABLE_COLLECTION',
- 'STYLE',
- 'STYLE_SET',
- 'INTERNAL_ONLY_NODE',
- 'WIDGET',
- 'STAMP',
- 'STICKY',
- 'SHAPE_WITH_TEXT',
- 'CONNECTOR',
- 'CODE_BLOCK',
- 'TABLE_NODE',
- 'TABLE_CELL',
- 'SECTION_OVERLAY',
- 'SLIDE'
-])
-
function isChildOfVisualNode(nc: KiwiNodeChange, parentTypes: Map<string, string>): boolean {
const parentId = nc.parentIndex?.guid
? `${nc.parentIndex.guid.sessionID}:${nc.parentIndex.guid.localID}`
: null
return (
- !!parentId &&
- parentTypes.has(parentId) &&
- !NON_VISUAL_TYPES.has(parentTypes.get(parentId) ?? '')
+ !!parentId && parentTypes.has(parentId) && isFigClipboardVisualType(parentTypes.get(parentId))
)
}
@@ -105,7 +74,7 @@ export function figmaNodesBounds(
}
for (const nc of nodeChanges) {
- if (!nc.type || NON_VISUAL_TYPES.has(nc.type)) continue
+ if (!isFigClipboardVisualType(nc.type)) continue
if (isChildOfVisualNode(nc, parentTypes)) continue
const x = nc.transform?.m02 ?? 0
@@ -121,173 +90,3 @@ export function figmaNodesBounds(
if (minX === Infinity) return null
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }
}
-
-interface ClipboardImportMaps {
- guidMap: Map<string, KiwiNodeChange>
- parentMap: Map<string, string>
- childMap: Map<string, string[]>
-}
-
-function buildClipboardMaps(nodeChanges: KiwiNodeChange[]): ClipboardImportMaps {
- const guidMap = new Map<string, KiwiNodeChange>()
- const parentMap = new Map<string, string>()
- const childMap = new Map<string, string[]>()
- for (const nc of nodeChanges) {
- if (!nc.guid) continue
- const id = `${nc.guid.sessionID}:${nc.guid.localID}`
- guidMap.set(id, nc)
- if (nc.parentIndex?.guid) {
- const parentId = `${nc.parentIndex.guid.sessionID}:${nc.parentIndex.guid.localID}`
- parentMap.set(id, parentId)
- const siblings = childMap.get(parentId)
- if (siblings) siblings.push(id)
- else childMap.set(parentId, [id])
- }
- }
- return { guidMap, parentMap, childMap }
-}
-
-function findInternalNodeIds(
- guidMap: Map<string, KiwiNodeChange>,
- childMap: Map<string, string[]>
-): { internalCanvasIds: Set<string>; internalFigmaIds: Set<string> } {
- const internalCanvasIds = new Set<string>()
- for (const [id, nc] of guidMap) {
- if (nc.type === 'CANVAS' && nc.internalOnly) {
- internalCanvasIds.add(id)
- }
- }
-
- const internalFigmaIds = new Set<string>()
- function markInternal(id: string) {
- internalFigmaIds.add(id)
- for (const childId of childMap.get(id) ?? []) {
- if (!internalFigmaIds.has(childId)) markInternal(childId)
- }
- }
- for (const canvasId of internalCanvasIds) markInternal(canvasId)
-
- return { internalCanvasIds, internalFigmaIds }
-}
-
-function classifyTopLevelNodes(
- guidMap: Map<string, KiwiNodeChange>,
- parentMap: Map<string, string>,
- internalCanvasIds: Set<string>
-): { topLevel: string[]; internalTopLevel: string[] } {
- const topLevel: string[] = []
- const internalTopLevel: string[] = []
- for (const [id, nc] of guidMap) {
- if (NON_VISUAL_TYPES.has(nc.type ?? '')) continue
- const parentId = parentMap.get(id)
- if (
- !parentId ||
- !guidMap.has(parentId) ||
- NON_VISUAL_TYPES.has(guidMap.get(parentId)?.type ?? '')
- ) {
- if (parentId && internalCanvasIds.has(parentId)) {
- internalTopLevel.push(id)
- } else {
- topLevel.push(id)
- }
- }
- }
- return { topLevel, internalTopLevel }
-}
-
-function remapComponentIds(created: Map<string, string>, graph: SceneGraph): void {
- for (const [, ourId] of created) {
- const node = graph.getNode(ourId)
- if (node?.type !== 'INSTANCE' || !node.componentId) continue
- const ourComponentId = created.get(node.componentId)
- if (ourComponentId) graph.updateNode(ourId, { componentId: ourComponentId })
- }
-}
-
-function detachOrphanedInstances(created: Map<string, string>, graph: SceneGraph): void {
- for (const [, ourId] of created) {
- const node = graph.getNode(ourId)
- if (node?.type !== 'INSTANCE') continue
- if (node.childIds.length === 0 && (!node.componentId || !graph.getNode(node.componentId))) {
- graph.updateNode(ourId, { type: 'FRAME', componentId: '' })
- }
- }
-}
-
-export function importClipboardNodes(
- nodeChanges: KiwiNodeChange[],
- graph: SceneGraph,
- targetParentId: string,
- offsetX = 0,
- offsetY = 0,
- blobs: Uint8Array[] = []
-): string[] {
- const { guidMap, parentMap, childMap } = buildClipboardMaps(nodeChanges)
- const { internalCanvasIds, internalFigmaIds } = findInternalNodeIds(guidMap, childMap)
- const { topLevel, internalTopLevel } = classifyTopLevelNodes(
- guidMap,
- parentMap,
- internalCanvasIds
- )
-
- const created = new Map<string, string>()
- const createdIds: string[] = []
-
- function createNode(figmaId: string, ourParentId: string) {
- if (created.has(figmaId)) return
- const nc = guidMap.get(figmaId)
- if (!nc) return
-
- const { nodeType, ...props } = nodeChangeToProps(nc, blobs)
- if (nodeType === 'DOCUMENT' || nodeType === 'VARIABLE') return
- if (shouldImportTextAsAutoSize(nc, guidMap.get(parentMap.get(figmaId) ?? ''))) {
- props.textAutoResize = 'WIDTH_AND_HEIGHT'
- }
-
- if (ourParentId === targetParentId) {
- props.x = (props.x ?? 0) + offsetX
- props.y = (props.y ?? 0) + offsetY
- }
-
- const node = graph.createNode(nodeType, ourParentId, props)
-
- created.set(figmaId, node.id)
- if (ourParentId === targetParentId && !internalFigmaIds.has(figmaId)) createdIds.push(node.id)
-
- const children = (childMap.get(figmaId) ?? []).filter(
- (childId) => !NON_VISUAL_TYPES.has(guidMap.get(childId)?.type ?? '')
- )
- sortChildren(children, nc, guidMap)
- for (const childId of children) {
- createNode(childId, node.id)
- }
- }
-
- for (const id of internalTopLevel) {
- createNode(id, targetParentId)
- }
- for (const id of topLevel) {
- createNode(id, targetParentId)
- }
-
- remapComponentIds(created, graph)
-
- graph.preserveSourceMetadataDuring(() => {
- populateAndApplyOverrides(graph, guidMap as Map<string, InstanceNodeChange>, created, blobs)
- })
-
- for (const figmaId of internalTopLevel) {
- const ourId = created.get(figmaId)
- if (ourId) graph.deleteNode(ourId)
- }
-
- detachOrphanedInstances(created, graph)
-
- const pastedInstanceIds = new Set<string>()
- for (const ourId of created.values()) {
- if (graph.getNode(ourId)?.type === 'INSTANCE') pastedInstanceIds.add(ourId)
- }
- if (pastedInstanceIds.size > 0) linkImportedInstanceChildren(graph, pastedInstanceIds)
-
- return createdIds
-}
diff --git a/packages/fig/src/clipboard/index.ts b/packages/fig/src/clipboard/index.ts
index a84fdac3f..90d145a33 100644
--- a/packages/fig/src/clipboard/index.ts
+++ b/packages/fig/src/clipboard/index.ts
@@ -1,3 +1,3 @@
-export { parseFigmaClipboard, importClipboardNodes, figmaNodesBounds } from './import'
+export { parseFigmaClipboard, figmaNodesBounds } from './import'
export { encodeFigmaClipboard } from './encode'
export { embedClipboardImages } from './images'
diff --git a/packages/fig/src/document/bindings/layout.ts b/packages/fig/src/document/bindings/layout.ts
new file mode 100644
index 000000000..f4e025211
--- /dev/null
+++ b/packages/fig/src/document/bindings/layout.ts
@@ -0,0 +1,50 @@
+import {
+ resolvedNumericBindingUpdate,
+ numericVariableBindingScales
+} from '#fig/node-change/variable-bindings'
+
+import { forEachInstanceOverride } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+/** Apply resolved scalar layout values after hierarchy and explicit modes exist. */
+export function applyDocumentLayoutBindings(
+ graph: SceneGraph,
+ savedSizeNodes: ReadonlySet<string>,
+ materialized: readonly SceneNode[],
+ layoutScales: ReadonlyMap<string, number> = new Map()
+): void {
+ // An instance and the descendants its overrides name materialize together, so the owners
+ // that matter for these nodes are among them.
+ const sizesOverridden = new Map<string, Set<string>>()
+ for (const owner of materialized) {
+ if (owner.type !== 'INSTANCE') continue
+ forEachInstanceOverride(owner.instanceOverrides, (id, field) => {
+ if (field !== 'width' && field !== 'height') return
+ const target = id || owner.id
+ const fields = sizesOverridden.get(target) ?? new Set<string>()
+ fields.add(field)
+ sizesOverridden.set(target, fields)
+ })
+ }
+ for (const node of materialized) {
+ const scales = numericVariableBindingScales(
+ node.boundVariables,
+ layoutScales.get(node.id) ?? 1,
+ node.variableBindingScales
+ )
+ graph.updateNode(node.id, { variableBindingScales: scales })
+ for (const field in node.boundVariables) {
+ if ((field === 'width' || field === 'height') && savedSizeNodes.has(node.id)) continue
+ if (sizesOverridden.get(node.id)?.has(field)) continue
+ const variableId = node.boundVariables[field]
+ const variable = graph.variables.get(variableId)
+ if (!variable) continue
+ const modeId = graph.getNodeVariableModeId(node.id, variable.collectionId)
+ const value = graph.resolveVariable(variableId, modeId)
+ if (typeof value !== 'number') continue
+ const effectiveValue = field === 'opacity' ? value : value * (scales[field] ?? 1)
+ const updates = resolvedNumericBindingUpdate(field, effectiveValue)
+ if (updates) graph.updateNode(node.id, updates)
+ }
+ }
+}
diff --git a/packages/fig/src/document/bindings/paint.ts b/packages/fig/src/document/bindings/paint.ts
new file mode 100644
index 000000000..d97c4c830
--- /dev/null
+++ b/packages/fig/src/document/bindings/paint.ts
@@ -0,0 +1,49 @@
+import {
+ copyFills,
+ copyStrokes,
+ type Color,
+ type Fill,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+/**
+ * A bound paint takes its whole color from the variable, alpha included. Drawing reads
+ * that alpha from the paint's opacity rather than the color, so the variable owns both
+ * and any opacity the record carried is a stale literal Figma would not apply either.
+ */
+function applyBoundColor(paint: Pick<Fill, 'color' | 'opacity'>, color: Color): void {
+ paint.color = { ...color, a: 1 }
+ paint.opacity = color.a
+}
+
+/** Resolve bound paint colors only after occurrence hierarchy and modes are available. */
+export function applyDocumentPaintBindings(
+ graph: SceneGraph,
+ materialized: readonly SceneNode[]
+): void {
+ for (const node of materialized) {
+ // Most nodes bind nothing, so neither the entry array nor the change object is built
+ // until a paint binding is actually found.
+ let changes: Partial<SceneNode> | undefined
+ for (const field in node.boundVariables) {
+ if (!field.endsWith('/color')) continue
+ const match = /^(fills|strokes)\/(\d+)\/color$/.exec(field)
+ if (!match) continue
+ const id = node.boundVariables[field]
+ const kind = match[1] === 'fills' ? 'fills' : 'strokes'
+ const index = Number(match[2])
+ const color = graph.resolveColorVariableForNode(node.id, id)
+ if (!color || !node[kind][index]) continue
+ changes ??= {}
+ if (kind === 'fills') {
+ changes.fills ??= copyFills(node.fills)
+ applyBoundColor(changes.fills[index], color)
+ } else {
+ changes.strokes ??= copyStrokes(node.strokes)
+ applyBoundColor(changes.strokes[index], color)
+ }
+ }
+ if (changes) graph.updateNode(node.id, changes)
+ }
+}
diff --git a/packages/fig/src/document/bindings/references.ts b/packages/fig/src/document/bindings/references.ts
new file mode 100644
index 000000000..a18ab613a
--- /dev/null
+++ b/packages/fig/src/document/bindings/references.ts
@@ -0,0 +1,84 @@
+import { symbolOverridesOf, type SymbolOverride } from '#fig/instance-overrides/types'
+import { variableConsumptionEntries } from '#fig/node-change/variable-bindings'
+import { visitVariableReferences } from '#fig/node-change/variable-expression'
+
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'
+
+import { normalizeComponentPropertyRecords } from '../property-records'
+import { createResourceResolver } from '../resource-reference'
+import { STYLE_REFERENCE_FIELDS } from '../style-dependencies'
+
+export interface BindingReferenceDiagnostic {
+ sourceId: string
+ field: string
+ key: string
+ path: readonly GUID[]
+}
+
+function visitChildren(
+ node: NodeChange,
+ path: readonly GUID[],
+ visit: (node: NodeChange, path: readonly GUID[]) => void
+): void {
+ for (const override of symbolOverridesOf(node)) {
+ visit(override as NodeChange, [...path, ...(override.guidPath?.guids ?? [])])
+ }
+ for (const derived of (node.derivedSymbolData as SymbolOverride[] | undefined) ?? []) {
+ visit(derived as NodeChange, [...path, ...(derived.guidPath?.guids ?? [])])
+ }
+}
+
+/** Normalize supported binding references without mutating archive records or effective values. */
+export function resolveDocumentBindingReferences(
+ changes: readonly NodeChange[],
+ report: (diagnostic: BindingReferenceDiagnostic) => void,
+ ownership: 'copy' | 'transfer' = 'copy'
+): NodeChange[] {
+ const resolve = createResourceResolver(changes)
+ return changes.map((source) => {
+ const node = ownership === 'transfer' ? source : structuredClone(source)
+ const sourceId = source.guid ? guidToString(source.guid) : 'unknown'
+ const normalize = (
+ reference: NodeChange['variableSetID'],
+ field: string,
+ path: readonly GUID[]
+ ): void => {
+ if (!reference?.assetRef || reference.guid) return
+ const id = resolve(reference)
+ if (!id) {
+ report({ sourceId, field, key: reference.assetRef.key, path: structuredClone(path) })
+ return
+ }
+ reference.guid = stringToGuid(id)
+ }
+ const visit = (node: NodeChange, path: readonly GUID[]): void => {
+ normalizeComponentPropertyRecords(node)
+ for (const entry of variableConsumptionEntries(node)) {
+ visitVariableReferences(entry.variableData, (reference) =>
+ normalize(reference, entry.variableField ?? 'unknown', path)
+ )
+ }
+ for (const [field, paints] of [
+ ['fillPaints', node.fillPaints],
+ ['strokePaints', node.strokePaints]
+ ] as const) {
+ for (const paint of paints ?? []) normalize(paint.colorVar?.value?.alias, field, path)
+ }
+ const modeMap = node.variableModeBySetMap as
+ | {
+ entries?: Array<{ variableSetID?: NodeChange['variableSetID']; variableModeID?: GUID }>
+ }
+ | undefined
+ for (const entry of modeMap?.entries ?? []) {
+ normalize(entry.variableSetID, 'variableModeBySetMap', path)
+ }
+ for (const field of STYLE_REFERENCE_FIELDS) {
+ normalize(node[field] as NodeChange['variableSetID'], field, path)
+ }
+ visitChildren(node, path, visit)
+ }
+ visit(node, [])
+ return node
+ })
+}
diff --git a/packages/fig/src/document/bindings/text.ts b/packages/fig/src/document/bindings/text.ts
new file mode 100644
index 000000000..da147be34
--- /dev/null
+++ b/packages/fig/src/document/bindings/text.ts
@@ -0,0 +1,23 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+/**
+ * Resolve text bound to a string variable once occurrence hierarchy and modes exist. Read
+ * time is the only time: unlike a numeric binding, nothing re-resolves a string one when the
+ * variable or the node's mode changes later, so edited text goes stale until the next read.
+ * Figma stores a bound layer's resolved characters, but an instance override carries the
+ * binding alone, and a literal override of a bound layer is retired rather than applied —
+ * so the binding, not the claim, decides what a bound layer reads.
+ */
+export function applyDocumentTextBindings(
+ graph: SceneGraph,
+ materialized: readonly SceneNode[]
+): void {
+ for (const node of materialized) {
+ if (node.type !== 'TEXT') continue
+ const variableId = node.boundVariables.text
+ if (!variableId) continue
+ const text = graph.resolveStringVariableForNode(node.id, variableId)
+ if (text === undefined || text === node.text) continue
+ graph.updateNode(node.id, { text })
+ }
+}
diff --git a/packages/fig/src/document/component/checkpoint.ts b/packages/fig/src/document/component/checkpoint.ts
new file mode 100644
index 000000000..7955d340c
--- /dev/null
+++ b/packages/fig/src/document/component/checkpoint.ts
@@ -0,0 +1,70 @@
+import type { InstanceOccurrence } from '#fig/instance-overrides/interpret'
+import type { MaterializedComponentOccurrence } from '#fig/instance-overrides/source-children'
+
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+export interface ComponentCheckpoint {
+ rootId: string
+ nodes: Array<{ path: string[]; nodeId: string; mainComponentId: string | null }>
+}
+
+/** Paths use source identities at every hierarchy level, never names or child indexes. */
+export function checkpointComponent(
+ component: MaterializedComponentOccurrence
+): ComponentCheckpoint {
+ const nodes: ComponentCheckpoint['nodes'] = []
+ const visit = (occurrence: InstanceOccurrence, path: string[]): void => {
+ const node = component.materialized.nodes.get(occurrence)
+ if (!node) throw new Error('Missing checkpoint occurrence')
+ nodes.push({ path, nodeId: node.id, mainComponentId: occurrence.mainComponentId })
+ const ids = new Set<string>()
+ for (const child of occurrence.children) {
+ if (ids.has(child.sourceId)) throw new Error(`Ambiguous checkpoint child ${child.sourceId}`)
+ ids.add(child.sourceId)
+ visit(child, [...path, child.sourceId])
+ }
+ }
+ visit(component.occurrence, [])
+ return { rootId: component.materialized.root.id, nodes }
+}
+
+export function restoreComponentCheckpoint(
+ graph: SceneGraph,
+ occurrence: InstanceOccurrence,
+ checkpoint: ComponentCheckpoint
+): MaterializedComponentOccurrence {
+ const root = graph.getNode(checkpoint.rootId)
+ if (!root) throw new Error(`Missing resumed component ${checkpoint.rootId}`)
+ const currentlyMaterialized = new Map<string, SceneNode>()
+ const visitCurrent = (node: SceneNode, path: string[]): void => {
+ currentlyMaterialized.set(path.join('/'), node)
+ for (const child of graph.getChildren(node.id)) {
+ const source = child.source.id
+ if (source) visitCurrent(child, [...path, source])
+ }
+ }
+ visitCurrent(root, [])
+ const nodes = new Map<InstanceOccurrence, SceneNode>()
+ for (const entry of checkpoint.nodes) {
+ let target = occurrence
+ for (const id of entry.path) {
+ const matches = target.children.filter((child) => child.sourceId === id)
+ if (matches.length !== 1) throw new Error(`Invalid checkpoint source path ${id}`)
+ target = matches[0]
+ }
+ const node = graph.getNode(entry.nodeId) ?? currentlyMaterialized.get(entry.path.join('/'))
+ if (!node) continue
+ if (nodes.has(target) || target.mainComponentId !== entry.mainComponentId) {
+ throw new Error(`Invalid checkpoint occurrence ${entry.nodeId}`)
+ }
+ nodes.set(target, node)
+ }
+ const validate = (target: InstanceOccurrence): void => {
+ // Deleted loaded descendants are deliberate live structure, not checkpoint corruption.
+ if (!nodes.has(target)) return
+ for (const child of target.children) validate(child)
+ }
+ validate(occurrence)
+ if (nodes.get(occurrence) !== root) throw new Error('Invalid checkpoint root')
+ return { occurrence, materialized: { root, nodes } }
+}
diff --git a/packages/fig/src/document/component/dependencies.ts b/packages/fig/src/document/component/dependencies.ts
new file mode 100644
index 000000000..97a548ab6
--- /dev/null
+++ b/packages/fig/src/document/component/dependencies.ts
@@ -0,0 +1,59 @@
+import {
+ forEachOverrideRecord,
+ symbolDataOf,
+ type ComponentPropAssignment
+} from '#fig/instance-overrides/types'
+
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+interface DependencyDefinition {
+ type?: string
+ initialValue?: ComponentPropAssignment['value']
+ varValue?: ComponentPropAssignment['varValue']
+ preferredValues?: { instanceSwapValues?: Array<{ key?: string; version?: string }> }
+}
+
+/** Source dependencies, including inactive defaults needed for later edits. No value/name guessing. */
+export function componentDependencies(
+ node: NodeChange,
+ resolveReference?: (reference: NodeChange['variableSetID']) => string | undefined,
+ reportExternalPreferred?: (key: string) => void
+): ReadonlySet<string> {
+ const dependencies = new Set<string>()
+ const add = (guid: GUID | undefined): void => {
+ if (guid) dependencies.add(guidToString(guid))
+ }
+ const assignment = (value: ComponentPropAssignment): void => {
+ add(value.value?.guidValue)
+ add(value.varValue?.value?.symbolIdValue?.guid)
+ }
+ forEachOverrideRecord(node, (source, override) => {
+ add(symbolDataOf(source)?.symbolID)
+ add(override?.overriddenSymbolID)
+ for (const definition of (source.componentPropDefs as DependencyDefinition[] | undefined) ??
+ []) {
+ if (definition.type === 'INSTANCE_SWAP') {
+ assignment({ value: definition.initialValue, varValue: definition.varValue })
+ for (const preferred of definition.preferredValues?.instanceSwapValues ?? []) {
+ if (!preferred.key) continue
+ const id = resolveReference?.({
+ assetRef: { key: preferred.key, version: preferred.version }
+ })
+ if (!id) {
+ if (!reportExternalPreferred)
+ throw new Error(`Unresolved preferred component ${preferred.key}`)
+ reportExternalPreferred(preferred.key)
+ continue
+ }
+ dependencies.add(id)
+ }
+ }
+ }
+ for (const value of (source.componentPropAssignments as
+ | ComponentPropAssignment[]
+ | undefined) ?? [])
+ assignment(value)
+ })
+ return dependencies
+}
diff --git a/packages/fig/src/document/component/values.ts b/packages/fig/src/document/component/values.ts
new file mode 100644
index 000000000..f5fea9346
--- /dev/null
+++ b/packages/fig/src/document/component/values.ts
@@ -0,0 +1,58 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+/**
+ * Convert source component references to canonical destination node identities.
+ *
+ * Only the nodes just materialized are rewritten. Definition types are remembered across
+ * page loads, because an assignment on a new node can name a definition an earlier page
+ * introduced; seeding that cache is the only pass that reads the whole graph.
+ */
+export function linkComponentPropertyValues(
+ graph: SceneGraph,
+ sources: ReadonlyMap<string, string>,
+ materialized: readonly SceneNode[],
+ definitionTypes?: Map<string, string>
+): void {
+ const definitions = definitionTypes ?? new Map<string, string>()
+ if (!definitionTypes)
+ for (const node of graph.getAllNodes())
+ for (const definition of node.componentPropertyDefinitions)
+ definitions.set(definition.id, definition.type)
+ for (const node of materialized) {
+ for (const definition of node.componentPropertyDefinitions) {
+ definitions.set(definition.id, definition.type)
+ if (definition.type !== 'INSTANCE_SWAP') continue
+ const target = sources.get(definition.defaultValue)
+ if (target) definition.defaultValue = target
+ }
+ }
+ for (const node of materialized) {
+ // for-in skips the entry array that most nodes, which assign nothing, never need.
+ for (const propertyId in node.componentPropertyAssignments) {
+ if (definitions.get(propertyId) !== 'INSTANCE_SWAP') continue
+ const target = sources.get(node.componentPropertyAssignments[propertyId])
+ if (target) node.componentPropertyAssignments[propertyId] = target
+ }
+ }
+}
+
+/**
+ * A variant's saved specs name the component set's variant definitions by id. Its own
+ * definitions never include those, so the names resolve only once the set is materialized.
+ */
+export function resolveVariantPropertyValues(
+ graph: SceneGraph,
+ materialized: readonly SceneNode[]
+): void {
+ for (const node of materialized) {
+ if (node.type !== 'COMPONENT' || !node.parentId) continue
+ if (node.variantPropSpecs.length === 0) continue
+ const parent = graph.getNode(node.parentId)
+ if (parent?.type !== 'COMPONENT_SET') continue
+ const names = new Map(parent.componentPropertyDefinitions.map((def) => [def.id, def.name]))
+ const values: Record<string, string> = {}
+ for (const spec of node.variantPropSpecs)
+ values[names.get(spec.propDefId) ?? spec.propDefId] = spec.value
+ graph.updateNode(node.id, { componentPropertyValues: values })
+ }
+}
diff --git a/packages/fig/src/document/components.ts b/packages/fig/src/document/components.ts
new file mode 100644
index 000000000..26b88b7cb
--- /dev/null
+++ b/packages/fig/src/document/components.ts
@@ -0,0 +1,73 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import type { InstanceOccurrence } from '../instance-overrides/interpret'
+import { occurrences } from '../instance-overrides/occurrence-path'
+import { parentIdOf } from '../instance-overrides/source-index'
+
+export interface ComponentConstruction {
+ sourceId: string
+ parentSourceId: string
+ pageSourceId: string
+ occurrence: InstanceOccurrence
+}
+
+/** Resolve source ownership and dependency order without mutating a destination graph. */
+export function planComponentConstruction(
+ changes: readonly NodeChange[],
+ roots: readonly InstanceOccurrence[],
+ readComponent: (id: string) => InstanceOccurrence,
+ index: ReadonlyMap<string, NodeChange>
+): ComponentConstruction[] {
+ const sources = index
+ const pageComponents = new Map<string, InstanceOccurrence>()
+ const indexPageComponents = (node: InstanceOccurrence): void => {
+ if (node.mainComponentId !== null) return
+ if (node.properties.type === 'SYMBOL') pageComponents.set(node.sourceId, node)
+ for (const child of node.children) indexPageComponents(child)
+ }
+ for (const root of roots) indexPageComponents(root)
+ const ordered: ComponentConstruction[] = []
+ const complete = new Set<string>()
+ const pending = new Set<string>()
+ const ownerPage = (id: string): string => {
+ const visited = new Set<string>()
+ let current: string | undefined = id
+ while (current) {
+ if (visited.has(current)) throw new Error(`Cyclic source hierarchy at ${current}`)
+ visited.add(current)
+ const source = sources.get(current)
+ if (!source) throw new Error(`Missing source ancestor ${current}`)
+ if (source.type === 'CANVAS') return current
+ current = parentIdOf(source)
+ }
+ throw new Error(`Component ${id} has no source page`)
+ }
+ const visit = (root: InstanceOccurrence): void => {
+ for (const node of occurrences(root)) {
+ if (node.mainComponentId !== null) ensure(node.mainComponentId)
+ if (node.properties.type === 'SYMBOL') ensure(node.sourceId)
+ }
+ }
+ const ensure = (id: string): void => {
+ if (complete.has(id)) return
+ if (pending.has(id)) throw new Error(`Cyclic component dependency ${id}`)
+ pending.add(id)
+ const source = sources.get(id)
+ if (!source?.parentIndex?.guid) throw new Error(`Missing component parent ${id}`)
+ const pageSourceId = ownerPage(id)
+ const occurrence = pageComponents.get(id) ?? readComponent(id)
+ // The definition itself is being built; only descend into its dependencies.
+ for (const child of occurrence.children) visit(child)
+ ordered.push({
+ sourceId: id,
+ parentSourceId: guidToString(source.parentIndex.guid),
+ pageSourceId,
+ occurrence
+ })
+ complete.add(id)
+ pending.delete(id)
+ }
+ for (const root of roots) visit(root)
+ return ordered
+}
diff --git a/packages/fig/src/document/dependency-closure.ts b/packages/fig/src/document/dependency-closure.ts
new file mode 100644
index 000000000..958cea7a6
--- /dev/null
+++ b/packages/fig/src/document/dependency-closure.ts
@@ -0,0 +1,100 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import { idOf, parentIdOf, type SourceIndex } from '../instance-overrides/source-index'
+import { componentDependencies } from './component/dependencies'
+import { createResourceResolver } from './resource-reference'
+import { styleDependencies } from './style-dependencies'
+
+export interface SceneDependencyClosure {
+ /** Live page trees plus explicitly referenced component trees. */
+ contentIds: ReadonlySet<string>
+ /** Required ownership containers, without automatically including their siblings. */
+ ancestorIds: ReadonlySet<string>
+ /** Referenced records the archive lacks: broken hierarchy or style references. */
+ missingIds: ReadonlySet<string>
+ /** Components instances or defaults reference that Figma has since deleted. */
+ missingComponentIds: ReadonlySet<string>
+ externalPreferredKeys: ReadonlySet<string>
+}
+
+function validatePageSelection(
+ sources: ReadonlyMap<string, NodeChange>,
+ pageIds?: ReadonlySet<string>
+): void {
+ if (!pageIds) return
+ for (const id of pageIds)
+ if (sources.get(id)?.type !== 'CANVAS') throw new Error(`Unknown page ${id}`)
+}
+
+/** Ownership chains above content, stopping where an earlier chain already continues. */
+function collectAncestors(
+ sources: ReadonlyMap<string, NodeChange>,
+ contentIds: ReadonlySet<string>,
+ ancestorIds: Set<string>,
+ missingIds: Set<string>
+): void {
+ for (const id of contentIds) {
+ const visited = new Set<string>([id])
+ let node = sources.get(id)
+ let parent = node ? parentIdOf(node) : undefined
+ while (parent !== undefined) {
+ if (visited.has(parent)) throw new Error(`Cyclic source hierarchy at ${parent}`)
+ visited.add(parent)
+ if (ancestorIds.has(parent)) break
+ ancestorIds.add(parent)
+ node = sources.get(parent)
+ if (!node) {
+ missingIds.add(parent)
+ break
+ }
+ parent = parentIdOf(node)
+ }
+ }
+}
+
+/** Plan reachability without deleting records or expanding unrelated internal siblings. */
+export function collectSceneDependencies(
+ changes: readonly NodeChange[],
+ pageIds: ReadonlySet<string> | undefined,
+ index: SourceIndex
+): SceneDependencyClosure {
+ const resolveReference = createResourceResolver(changes)
+ const { sources, children } = index
+ const availableIds = new Set(sources.keys())
+ const contentIds = new Set<string>()
+ const ancestorIds = new Set<string>()
+ const externalPreferredKeys = new Set<string>()
+ const missingIds = new Set<string>()
+ const missingComponentIds = new Set<string>()
+ const componentReferences = new Set<string>()
+ validatePageSelection(sources, pageIds)
+ const pending = changes
+ .filter(
+ (node) =>
+ node.type === 'CANVAS' &&
+ (pageIds ? pageIds.has(idOf(node) ?? '') : node.internalOnly !== true)
+ )
+ .flatMap((node) => idOf(node) ?? [])
+ while (pending.length) {
+ const id = pending.pop()
+ if (!id || contentIds.has(id)) continue
+ const node = sources.get(id)
+ if (!node) {
+ if (componentReferences.has(id)) missingComponentIds.add(id)
+ else missingIds.add(id)
+ continue
+ }
+ contentIds.add(id)
+ const components = componentDependencies(node, resolveReference, (key) =>
+ externalPreferredKeys.add(key)
+ )
+ for (const component of components) componentReferences.add(component)
+ pending.push(
+ ...(children.get(id) ?? []).flatMap((child) => idOf(child) ?? []),
+ ...styleDependencies(node, resolveReference, availableIds),
+ ...components
+ )
+ }
+ collectAncestors(sources, contentIds, ancestorIds, missingIds)
+ return { contentIds, ancestorIds, missingIds, missingComponentIds, externalPreferredKeys }
+}
diff --git a/packages/fig/src/document/fragment.ts b/packages/fig/src/document/fragment.ts
new file mode 100644
index 000000000..705ed09d2
--- /dev/null
+++ b/packages/fig/src/document/fragment.ts
@@ -0,0 +1,131 @@
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import { isUnsupportedFigFragmentType } from '../node-classification'
+import { materializeDocument, type DocumentAssemblyOptions } from './materialize'
+
+export interface FragmentOptions {
+ /** Only empty instances with no saved claims may lose an unavailable component. */
+ missingComponent?: 'error' | 'detach-empty'
+}
+
+export interface FragmentMaterializationOptions extends FragmentOptions {
+ images?: DocumentAssemblyOptions['images']
+}
+
+/** Interpret a partial document in isolation; retain internal resources separately from pasted roots. */
+export function materializeFigFragment(
+ source: readonly NodeChange[],
+ blobs: Uint8Array[] = [],
+ options: FragmentMaterializationOptions = {}
+) {
+ const changes = normalizeFigFragment(source, options)
+ const result = materializeDocument(changes, blobs, {
+ derivedBounds: true,
+ images: options.images
+ })
+ const rootIds: string[] = []
+ const dependencyPageIds: string[] = []
+ for (const page of changes) {
+ if (page.type !== 'CANVAS' || !page.guid) continue
+ const id = result.sources.get(guidToString(page.guid))
+ if (!id) continue
+ if (page.internalOnly) dependencyPageIds.push(id)
+ else rootIds.push(...result.graph.getChildren(id).map((node) => node.id))
+ }
+ return { ...result, rootIds, dependencyPageIds }
+}
+
+function indexFragment(changes: readonly NodeChange[]) {
+ const ids = new Set<string>()
+ const reserved = new Set<string>()
+ const children = new Set<string>()
+ for (const node of changes) {
+ if (!node.guid) throw new Error('Clipboard fragment node has no GUID')
+ const id = guidToString(node.guid)
+ if (ids.has(id)) throw new Error(`Duplicate fragment source ${id}`)
+ ids.add(id)
+ reserved.add(id)
+ if (node.parentIndex) {
+ const parent = guidToString(node.parentIndex.guid)
+ reserved.add(parent)
+ children.add(parent)
+ }
+ if (node.symbolData?.symbolID) reserved.add(guidToString(node.symbolData.symbolID))
+ }
+ let localID = 0
+ const allocate = (): GUID => {
+ while (reserved.has(`0:${localID}`)) localID++
+ const guid = { sessionID: 0, localID: localID++ }
+ reserved.add(guidToString(guid))
+ return guid
+ }
+ return { ids, children, allocate }
+}
+
+function normalizeMissingComponent(
+ node: NodeChange,
+ ids: Set<string>,
+ children: Set<string>,
+ options: FragmentOptions
+): void {
+ if (
+ node.type !== 'INSTANCE' ||
+ !node.symbolData ||
+ ids.has(guidToString(node.symbolData.symbolID))
+ )
+ return
+ const hasClaims =
+ Object.keys(node.symbolData).some((key) => key !== 'symbolID') ||
+ node.componentPropAssignments !== undefined ||
+ node.derivedSymbolData
+ if (
+ options.missingComponent !== 'detach-empty' ||
+ !node.guid ||
+ children.has(guidToString(node.guid)) ||
+ hasClaims
+ ) {
+ throw new Error(`Missing fragment component ${guidToString(node.symbolData.symbolID)}`)
+ }
+ node.type = 'FRAME'
+ Reflect.deleteProperty(node, 'symbolData')
+}
+
+/** Normalize fragment containers only; semantics remain the document reader's responsibility. */
+export function normalizeFigFragment(
+ source: readonly NodeChange[],
+ options: FragmentOptions = {}
+): NodeChange[] {
+ const changes = source
+ .filter((node) => !isUnsupportedFigFragmentType(node.type))
+ .map((node) => structuredClone(node))
+ const { ids, children, allocate } = indexFragment(changes)
+ const documents = changes.filter((node) => node.type === 'DOCUMENT')
+ if (documents.length > 1) throw new Error('Multiple fragment documents')
+ const documentGuid = documents[0]?.guid ?? allocate()
+ if (!documents.length) changes.unshift({ type: 'DOCUMENT', guid: documentGuid })
+ let fragmentPage: GUID | undefined
+ for (const node of changes) {
+ if (node.type === 'DOCUMENT') continue
+ const parent = node.parentIndex?.guid
+ if (node.type === 'CANVAS') {
+ node.parentIndex = { guid: documentGuid, position: node.parentIndex?.position ?? '!' }
+ } else if (
+ !parent ||
+ !ids.has(guidToString(parent)) ||
+ guidToString(parent) === guidToString(documentGuid)
+ ) {
+ fragmentPage ??= allocate()
+ node.parentIndex = { guid: fragmentPage, position: node.parentIndex?.position ?? '!' }
+ }
+ normalizeMissingComponent(node, ids, children, options)
+ }
+ if (fragmentPage)
+ changes.push({
+ type: 'CANVAS',
+ guid: fragmentPage,
+ name: 'Clipboard',
+ parentIndex: { guid: documentGuid, position: '!' }
+ })
+ return changes
+}
diff --git a/packages/fig/src/document/load-transaction.ts b/packages/fig/src/document/load-transaction.ts
new file mode 100644
index 000000000..31ffb39f5
--- /dev/null
+++ b/packages/fig/src/document/load-transaction.ts
@@ -0,0 +1,56 @@
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import type { SceneDependencyClosure } from './dependency-closure'
+import type { AssemblyState } from './materialize'
+
+/** Roll back selected-page mutations without cloning unrelated document payloads. */
+export function loadPageTransaction(
+ state: AssemblyState,
+ closure: SceneDependencyClosure,
+ action: () => void
+): void {
+ const { graph } = state
+ const existingIds = new Set(graph.nodes.keys())
+ const snapshots = new Map<SceneNode, SceneNode>()
+ const candidateIds = new Set([graph.rootId, ...graph.getPages(true).map((page) => page.id)])
+ for (const source of [...closure.contentIds, ...closure.ancestorIds]) {
+ const id = state.sources.get(source)
+ if (id) candidateIds.add(id)
+ }
+ for (const id of candidateIds) {
+ const node = graph.getNode(id)
+ if (node) snapshots.set(node, structuredClone(node))
+ }
+ const sources = new Map(state.sources)
+ const components = new Map(state.components)
+ const componentIds = new Map(state.componentIds)
+ const sizes = new Set(state.savedSizeNodes)
+ graph.withBufferedEvents(() => {
+ try {
+ action()
+ } catch (error) {
+ for (const [id, node] of graph.nodes) {
+ if (existingIds.has(id)) continue
+ if (node.componentId) graph.instanceIndex.get(node.componentId)?.delete(id)
+ graph.nodes.delete(id)
+ }
+ for (const [node, snapshot] of snapshots) {
+ if (node.componentId) graph.instanceIndex.get(node.componentId)?.delete(node.id)
+ Object.assign(node, snapshot)
+ if (node.type === 'INSTANCE' && node.componentId) {
+ const entries = graph.instanceIndex.get(node.componentId) ?? new Set<string>()
+ entries.add(node.id)
+ graph.instanceIndex.set(node.componentId, entries)
+ }
+ }
+ state.sources = sources
+ state.components = components
+ state.componentIds = componentIds
+ state.savedSizeNodes = sizes
+ for (const [id, entries] of graph.instanceIndex)
+ if (!entries.size) graph.instanceIndex.delete(id)
+ graph.clearAbsPosCache()
+ throw error
+ }
+ })
+}
diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.ts
new file mode 100644
index 000000000..0732c80c3
--- /dev/null
+++ b/packages/fig/src/document/materialize.ts
@@ -0,0 +1,292 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+import type { InstanceOccurrence, InterpretInstanceOptions } from '../instance-overrides/interpret'
+import { reconcileLiveComponentEdits } from '../instance-overrides/live-component-edits'
+import { materializeInstance } from '../instance-overrides/materialize-instance'
+import {
+ reconcileOccurrenceStructure,
+ linkInstanceSourceChildren,
+ mapInstanceSourceChildren,
+ type MaterializedComponentOccurrence
+} from '../instance-overrides/source-children'
+import { nodeChangeToProps } from '../node-change'
+import { applyDocumentLayoutBindings } from './bindings/layout'
+import { applyDocumentPaintBindings } from './bindings/paint'
+import type { BindingReferenceDiagnostic } from './bindings/references'
+import { applyDocumentTextBindings } from './bindings/text'
+import {
+ checkpointComponent,
+ restoreComponentCheckpoint,
+ type ComponentCheckpoint
+} from './component/checkpoint'
+import { linkComponentPropertyValues, resolveVariantPropertyValues } from './component/values'
+import { loadPageTransaction } from './load-transaction'
+import { applyDocumentMetadata } from './metadata'
+import { createArchiveDocumentReader, createDocumentReader } from './read'
+import { materializeVariableResources } from './variables'
+
+export interface DocumentAssemblyOptions extends InterpretInstanceOptions {
+ /** Restrict scene population to these source pages plus required component ownership. */
+ pageIds?: ReadonlySet<string>
+ images?: ReadonlyMap<string, Uint8Array>
+ /** A resource record the materializer does not convert; acknowledged rather than dropped. */
+ onUnsupportedResource?: (resource: NodeChange) => void
+ onUnresolvedBinding?: (diagnostic: BindingReferenceDiagnostic) => void
+}
+
+/** Assemble every page of an archive into one graph. */
+export function materializeDocument(
+ changes: readonly NodeChange[],
+ blobs: Uint8Array[] = [],
+ options: DocumentAssemblyOptions = {}
+) {
+ return materializeReader(createDocumentReader(changes, options.pageIds), blobs, options)
+}
+
+/** Own parsed archive records; do not create a second full source tree. */
+export function materializeFigArchive(bytes: ArrayBuffer, options: DocumentAssemblyOptions = {}) {
+ const { reader, blobs, images } = createArchiveDocumentReader(bytes, options.pageIds)
+ return materializeReader(reader, blobs, { ...options, images: options.images ?? new Map(images) })
+}
+
+export interface AssemblyState {
+ graph: SceneGraph
+ sources: Map<string, string>
+ components: Map<string, MaterializedComponentOccurrence>
+ componentIds: Map<string, string>
+ savedSizeNodes: Set<string>
+ /** Component property types by definition id, carried across page loads. */
+ definitionTypes?: Map<string, string>
+}
+
+export interface FigSessionCheckpoint {
+ sources: Array<[string, string]>
+ componentIds: Array<[string, string]>
+ savedSizeNodeIds: string[]
+ loadedPageIds: string[]
+ components: Array<[string, ComponentCheckpoint]>
+}
+
+export interface FigSessionResume {
+ graph: SceneGraph
+ checkpoint: FigSessionCheckpoint
+}
+
+function restoreAssemblyState(
+ resume: FigSessionResume,
+ reader: ReturnType<typeof createDocumentReader>,
+ options: DocumentAssemblyOptions
+): AssemblyState {
+ const { graph, checkpoint } = resume
+ const components = new Map<string, MaterializedComponentOccurrence>()
+ for (const [id, entry] of checkpoint.components) {
+ components.set(id, restoreComponentCheckpoint(graph, reader.readComponent(id, options), entry))
+ }
+ return {
+ graph,
+ components,
+ sources: new Map(checkpoint.sources),
+ componentIds: new Map(checkpoint.componentIds),
+ savedSizeNodes: new Set(checkpoint.savedSizeNodeIds)
+ }
+}
+
+export function createFigDocumentSession(
+ bytes: ArrayBuffer,
+ options: DocumentAssemblyOptions = {},
+ resume?: FigSessionResume
+) {
+ const archive = createArchiveDocumentReader(bytes, new Set())
+ const sessionOptions = { ...options, images: options.images ?? new Map(archive.images) }
+ const state = resume
+ ? restoreAssemblyState(resume, archive.reader, sessionOptions)
+ : materializeReader(archive.reader, archive.blobs, sessionOptions)
+ state.graph.figKiwiVersion = archive.figKiwiVersion
+ state.graph.figSchemaDeflated = archive.figSchemaDeflated
+ const loaded = new Set<string>(resume?.checkpoint.loadedPageIds)
+ return {
+ checkpoint(): FigSessionCheckpoint {
+ return structuredClone({
+ sources: [...state.sources],
+ componentIds: [...state.componentIds],
+ savedSizeNodeIds: [...state.savedSizeNodes],
+ loadedPageIds: [...loaded],
+ components: [...state.components].map(([id, component]) => [
+ id,
+ checkpointComponent(component)
+ ])
+ } satisfies FigSessionCheckpoint)
+ },
+ graph: state.graph,
+ graphPageId(sourcePageId: string): string | undefined {
+ return archive.reader.pages.some((page) => page.id === sourcePageId)
+ ? state.sources.get(sourcePageId)
+ : undefined
+ },
+ pages: archive.reader.pages,
+ loadPage(id: string): void {
+ if (loaded.has(id)) return
+ const reader = archive.reader.selectPages(new Set([id]))
+ loadPageTransaction(state, reader.dependencyClosure, () => {
+ materializeReader(reader, archive.blobs, sessionOptions, state)
+ loaded.add(id)
+ })
+ },
+ get loadedPageIds(): ReadonlySet<string> {
+ return new Set(loaded)
+ }
+ }
+}
+
+/** Definition types already in the graph; only needed once, or after a resume. */
+function seedDefinitionTypes(graph: SceneGraph): Map<string, string> {
+ const types = new Map<string, string>()
+ for (const node of graph.getAllNodes())
+ for (const definition of node.componentPropertyDefinitions)
+ types.set(definition.id, definition.type)
+ return types
+}
+
+function createAssemblyState(
+ reader: ReturnType<typeof createDocumentReader>,
+ options: DocumentAssemblyOptions
+): AssemblyState {
+ const graph = new SceneGraph()
+ applyDocumentMetadata(graph, reader.documentRecord)
+ for (const [hash, bytes] of options.images ?? []) graph.images.set(hash, bytes.slice())
+ materializeVariableResources(graph, reader.resources, options.onUnsupportedResource)
+ for (const page of graph.getPages()) graph.deleteNode(page.id)
+ return {
+ graph,
+ sources: new Map(),
+ components: new Map(),
+ componentIds: new Map(),
+ savedSizeNodes: new Set()
+ }
+}
+
+function materializeReader(
+ reader: ReturnType<typeof createDocumentReader>,
+ blobs: Uint8Array[],
+ options: DocumentAssemblyOptions,
+ previous?: AssemblyState
+) {
+ for (const diagnostic of reader.bindingDiagnostics) {
+ if (!options.onUnresolvedBinding)
+ throw new Error(`Unresolved binding ${diagnostic.sourceId}: ${diagnostic.field}`)
+ options.onUnresolvedBinding(diagnostic)
+ }
+ const pages = reader.pages.map((page) => reader.readPage(page.id, options))
+ const plan = reader.planComponents(pages, options)
+ const state = previous ?? createAssemblyState(reader, options)
+ const { graph, sources, components, savedSizeNodes, componentIds } = state
+ const existingNodeIds = new Set(graph.nodes.keys())
+ const layoutScales = new Map<string, number>()
+ const rememberDerivedSizes = (nodes: ReadonlyMap<InstanceOccurrence, SceneNode>): void => {
+ for (const [occurrence, node] of nodes) {
+ if (occurrence.derivedSize) savedSizeNodes.add(node.id)
+ if (occurrence.layoutScale !== undefined) layoutScales.set(node.id, occurrence.layoutScale)
+ }
+ }
+ const createShells = (occurrence: InstanceOccurrence, parentId: string): void => {
+ if (occurrence.mainComponentId !== null) return
+ const existingId = sources.get(occurrence.sourceId)
+ if (existingId) {
+ for (const child of occurrence.children) createShells(child, existingId)
+ return
+ }
+ const { nodeType, ...props } = nodeChangeToProps(occurrence.properties, blobs)
+ if (nodeType === 'DOCUMENT' || nodeType === 'VARIABLE')
+ throw new Error(`Unsupported scene type ${nodeType}`)
+ const node = graph.createNode(nodeType, parentId, props)
+ sources.set(occurrence.sourceId, node.id)
+ if (node.type === 'COMPONENT') componentIds.set(occurrence.sourceId, node.id)
+ for (const child of occurrence.children) createShells(child, node.id)
+ }
+ for (const page of pages) createShells(page, graph.rootId)
+ for (const item of plan) {
+ if (components.has(item.sourceId)) continue
+ const parentId = sources.get(item.parentSourceId)
+ if (!parentId) throw new Error(`Unmaterialized component parent ${item.parentSourceId}`)
+ const existingNodes = new Map<InstanceOccurrence, SceneNode>()
+ const collectExisting = (node: InstanceOccurrence): void => {
+ const id = sources.get(node.sourceId)
+ const existing = id ? graph.getNode(id) : undefined
+ if (existing) existingNodes.set(node, existing)
+ if (node.mainComponentId === null) node.children.forEach(collectExisting)
+ }
+ collectExisting(item.occurrence)
+ const materialized = materializeInstance(graph, parentId, item.occurrence, componentIds, {
+ blobs,
+ sourceChildren: mapInstanceSourceChildren(item.occurrence, components),
+ existingNodes
+ })
+ rememberDerivedSizes(materialized.nodes)
+ linkInstanceSourceChildren(item.occurrence, materialized, components)
+ components.set(item.sourceId, { occurrence: item.occurrence, materialized })
+ componentIds.set(item.sourceId, materialized.root.id)
+ sources.set(item.sourceId, materialized.root.id)
+ }
+ /**
+ * Components whose instances a resumed load must re-sync. Syncing visits every instance
+ * of a component, so a page placing many instances of one component collects it once
+ * and syncs after the page is built rather than per instance.
+ */
+ const resync = new Set<string>()
+ const populateInstances = (occurrence: InstanceOccurrence): void => {
+ if (occurrence.properties.type === 'SYMBOL') return
+ const parentId = sources.get(occurrence.sourceId)
+ if (!parentId) throw new Error(`Missing source container ${occurrence.sourceId}`)
+ const ordered: string[] = []
+ for (const child of occurrence.children) {
+ if (previous) reconcileOccurrenceStructure(child, graph, components)
+ if (child.mainComponentId !== null && !sources.has(child.sourceId)) {
+ const materialized = materializeInstance(graph, parentId, child, componentIds, {
+ blobs,
+ sourceChildren: mapInstanceSourceChildren(child, components)
+ })
+ rememberDerivedSizes(materialized.nodes)
+ linkInstanceSourceChildren(child, materialized, components)
+ if (previous) {
+ reconcileLiveComponentEdits(graph, materialized)
+ if (materialized.root.componentId) resync.add(materialized.root.componentId)
+ }
+ sources.set(child.sourceId, materialized.root.id)
+ } else if (child.mainComponentId === null && child.properties.type !== 'SYMBOL')
+ populateInstances(child)
+ const id = sources.get(child.sourceId)
+ if (!id) throw new Error(`Missing assembled child ${child.sourceId}`)
+ ordered.push(id)
+ }
+ const parent = graph.getNode(parentId)
+ if (parent)
+ parent.childIds = [...ordered, ...parent.childIds.filter((id) => !ordered.includes(id))]
+ }
+ for (const page of pages) populateInstances(page)
+ for (const componentId of resync) graph.syncInstances(componentId)
+ for (const node of graph.getAllNodes()) {
+ if (existingNodeIds.has(node.id)) continue
+ for (const field of [
+ 'fillStyleId',
+ 'strokeStyleId',
+ 'textStyleId',
+ 'effectStyleId',
+ 'gridStyleId'
+ ] as const) {
+ const id = node[field]
+ if (id && sources.has(id)) node[field] = sources.get(id) ?? id
+ }
+ }
+ // These passes apply to the nodes this page added, not to the whole graph.
+ const materialized = [...graph.nodes.values()].filter((node) => !existingNodeIds.has(node.id))
+ state.definitionTypes ??= seedDefinitionTypes(graph)
+ linkComponentPropertyValues(graph, sources, materialized, state.definitionTypes)
+ graph.preserveSourceMetadataDuring(() => {
+ resolveVariantPropertyValues(graph, materialized)
+ applyDocumentLayoutBindings(graph, savedSizeNodes, materialized, layoutScales)
+ applyDocumentPaintBindings(graph, materialized)
+ applyDocumentTextBindings(graph, materialized)
+ })
+ return state
+}
diff --git a/packages/fig/src/document/metadata.ts b/packages/fig/src/document/metadata.ts
new file mode 100644
index 000000000..2aaf11315
--- /dev/null
+++ b/packages/fig/src/document/metadata.ts
@@ -0,0 +1,37 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { ENABLED_LIBRARIES_PLUGIN_KEY, getOpenPencilPluginValue } from '../node-change/plugin-data'
+
+export function applyDocumentMetadata(graph: SceneGraph, document: NodeChange | undefined): void {
+ const root = graph.getNode(graph.rootId)
+ if (!root || !document) return
+ root.source.format = 'fig'
+ root.pluginData =
+ document.pluginData?.map((entry) => ({
+ pluginId: entry.pluginID,
+ key: entry.key,
+ value: entry.value
+ })) ?? []
+ root.source.fig.rawNodeFields.strokeJoin = document.strokeJoin
+ root.source.fig.rawNodeFields.strokeWeight = document.strokeWeight
+ const bindings = getOpenPencilPluginValue(document, ENABLED_LIBRARIES_PLUGIN_KEY)
+ if (!bindings) return
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(bindings)
+ } catch {
+ return
+ }
+ if (!Array.isArray(parsed)) return
+ for (const entry of parsed) {
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
+ if (!('libraryId' in entry) || !('revisionId' in entry)) continue
+ if (typeof entry.libraryId !== 'string' || typeof entry.revisionId !== 'string') continue
+ graph.enabledLibraries.set(entry.libraryId, {
+ libraryId: entry.libraryId,
+ revisionId: entry.revisionId,
+ enabled: 'enabled' in entry && entry.enabled === true
+ })
+ }
+}
diff --git a/packages/fig/src/document/property-inheritance.ts b/packages/fig/src/document/property-inheritance.ts
new file mode 100644
index 000000000..50a1a2b49
--- /dev/null
+++ b/packages/fig/src/document/property-inheritance.ts
@@ -0,0 +1,52 @@
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import { parentIdOf } from '../instance-overrides/source-index'
+
+interface LinkedPropertyDefinition {
+ id?: GUID
+ parentPropDefId?: GUID
+ [field: string]: unknown
+}
+
+/** Resolve definition inheritance only within the source node's ancestry. */
+export function inheritComponentPropertyDefinitions(
+ changes: readonly NodeChange[],
+ index: ReadonlyMap<string, NodeChange>
+): void {
+ const sources = index
+ const pending = new Set<NodeChange>()
+ const complete = new Set<NodeChange>()
+ const resolve = (node: NodeChange): void => {
+ if (complete.has(node)) return
+ if (pending.has(node)) throw new Error('Cyclic component-property ancestry')
+ pending.add(node)
+ const ancestors: NodeChange[] = []
+ let parent = sources.get(parentIdOf(node) ?? '')
+ const visited = new Set<NodeChange>([node])
+ while (parent) {
+ if (visited.has(parent)) throw new Error('Cyclic component-property ancestry')
+ visited.add(parent)
+ resolve(parent)
+ ancestors.push(parent)
+ parent = sources.get(parentIdOf(parent) ?? '')
+ }
+ const definitions = node.componentPropDefs as LinkedPropertyDefinition[] | undefined
+ if (definitions)
+ node.componentPropDefs = definitions.map((definition) => {
+ if (!definition.parentPropDefId) return definition
+ const id = guidToString(definition.parentPropDefId)
+ for (const ancestor of ancestors) {
+ const matches = (
+ (ancestor.componentPropDefs as LinkedPropertyDefinition[] | undefined) ?? []
+ ).filter((candidate) => candidate.id && guidToString(candidate.id) === id)
+ if (matches.length > 1) throw new Error(`Ambiguous parent property ${id}`)
+ if (matches.length === 1) return { ...structuredClone(matches[0]), ...definition }
+ }
+ throw new Error(`Missing parent property ${id}`)
+ })
+ pending.delete(node)
+ complete.add(node)
+ }
+ for (const node of changes) resolve(node)
+}
diff --git a/packages/fig/src/document/property-records.ts b/packages/fig/src/document/property-records.ts
new file mode 100644
index 000000000..cd34ee7af
--- /dev/null
+++ b/packages/fig/src/document/property-records.ts
@@ -0,0 +1,37 @@
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import type { ComponentPropAssignment, ComponentPropRef } from '../instance-overrides/types'
+
+interface PropertyDefinition {
+ initialValue?: ComponentPropAssignment['value']
+ varValue?: ComponentPropAssignment['varValue']
+}
+
+/** Adapt current typed property values to the interpreter's common representation. */
+function normalizeDefaults(node: NodeChange): void {
+ for (const definition of (node.componentPropDefs as PropertyDefinition[] | undefined) ?? []) {
+ const value = definition.varValue?.value
+ if (definition.initialValue || !value) continue
+ definition.initialValue = value.symbolIdValue?.guid
+ ? { guidValue: structuredClone(value.symbolIdValue.guid) }
+ : structuredClone(value)
+ }
+}
+
+export function normalizeComponentPropertyRecords(node: NodeChange): void {
+ normalizeDefaults(node)
+ const parameters = node.parameterConsumptionMap
+ const refs = structuredClone((node.componentPropRefs as ComponentPropRef[] | undefined) ?? [])
+ for (const entry of parameters?.entries ?? []) {
+ const id = entry.variableData?.value?.propRefValue?.defId
+ if (entry.variableData?.dataType !== 'PROP_REF' || !id || !entry.variableField) continue
+ if (!['VISIBLE', 'TEXT_DATA', 'OVERRIDDEN_SYMBOL_ID'].includes(entry.variableField)) continue
+ const ref = { defID: structuredClone(id), componentPropNodeField: entry.variableField }
+ const index = refs.findIndex(
+ (candidate) => candidate.componentPropNodeField === entry.variableField
+ )
+ if (index === -1) refs.push(ref)
+ else refs[index] = ref
+ }
+ if (refs.length) node.componentPropRefs = refs
+}
diff --git a/packages/fig/src/document/read.ts b/packages/fig/src/document/read.ts
new file mode 100644
index 000000000..dc40f8c95
--- /dev/null
+++ b/packages/fig/src/document/read.ts
@@ -0,0 +1,170 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import { parseFigBuffer } from '../archive'
+import {
+ createOccurrenceInterpreter,
+ type InterpretInstanceOptions
+} from '../instance-overrides/interpret'
+import {
+ bySavedPosition,
+ createSourceIndex,
+ type SourceIndex
+} from '../instance-overrides/source-index'
+import { symbolOverridesOf } from '../instance-overrides/types'
+import { applyStyleRefsToFields } from '../node-change/style-refs'
+import {
+ resolveDocumentBindingReferences,
+ type BindingReferenceDiagnostic
+} from './bindings/references'
+import { planComponentConstruction } from './components'
+import { collectSceneDependencies } from './dependency-closure'
+import { inheritComponentPropertyDefinitions } from './property-inheritance'
+
+/** Indexed source document. Resources remain separate from scene occurrences. */
+export function createDocumentReader(source: readonly NodeChange[], pageIds?: ReadonlySet<string>) {
+ return createReader(source, 'copy', pageIds)
+}
+
+/** Parse into exclusively owned records; callers never receive the mutable source index. */
+export function createArchiveDocumentReader(bytes: ArrayBuffer, pageIds?: ReadonlySet<string>) {
+ const parsed = parseFigBuffer(bytes)
+ return {
+ figKiwiVersion: parsed.figKiwiVersion,
+ figSchemaDeflated: parsed.figSchemaDeflated,
+ reader: createReader(parsed.nodeChanges, 'transfer', pageIds),
+ blobs: parsed.blobs,
+ images: parsed.images
+ }
+}
+
+function createReader(
+ source: readonly NodeChange[],
+ ownership: 'copy' | 'transfer',
+ pageIds?: ReadonlySet<string>
+) {
+ const bindingDiagnostics: BindingReferenceDiagnostic[] = []
+ const liveSource = source.filter((node) => node.phase !== 'REMOVED')
+ const changes = resolveDocumentBindingReferences(
+ liveSource,
+ (diagnostic) => bindingDiagnostics.push(diagnostic),
+ ownership
+ )
+ // One index over these records serves inheritance, style lookup, the dependency closure
+ // and component planning.
+ const index = createSourceIndex(changes)
+ inheritComponentPropertyDefinitions(changes, index.sources)
+ const styles = index.sources
+ const assets = new Map<string, string>()
+ for (const node of changes)
+ if (node.guid && typeof node.key === 'string') {
+ const id = guidToString(node.guid)
+ assets.set(node.key, id)
+ if (typeof node.version === 'string') assets.set(`${node.key}@${node.version}`, id)
+ }
+ const resolveStyles = (node: NodeChange): void => {
+ applyStyleRefsToFields(styles, node, assets)
+ for (const override of symbolOverridesOf(node)) resolveStyles(override as NodeChange)
+ }
+ for (const node of changes) resolveStyles(node)
+ return createScopedReader(
+ changes,
+ bindingDiagnostics,
+ pageIds,
+ createSharedReaderState(changes, index)
+ )
+}
+
+/**
+ * Everything a scoped reader needs that does not depend on which pages are selected. Only
+ * the page's own subset varies, so the whole-document work happens once per document.
+ */
+interface SharedReaderState {
+ index: SourceIndex
+ sourceInterpreter: ReturnType<typeof createOccurrenceInterpreter>
+}
+
+function createSharedReaderState(changes: readonly NodeChange[], index: SourceIndex) {
+ let sourceInterpreter: SharedReaderState['sourceInterpreter'] | undefined
+ return {
+ index,
+ get sourceInterpreter() {
+ sourceInterpreter ??= createOccurrenceInterpreter(
+ changes.filter((change) => change.type !== 'VARIABLE' && change.type !== 'VARIABLE_SET')
+ )
+ return sourceInterpreter
+ }
+ }
+}
+
+function createScopedReader(
+ changes: NodeChange[],
+ bindingDiagnostics: BindingReferenceDiagnostic[],
+ pageIds: ReadonlySet<string> | undefined,
+ shared: SharedReaderState
+) {
+ const resources = changes.filter(
+ (change) => change.type === 'VARIABLE' || change.type === 'VARIABLE_SET'
+ )
+ const closure = collectSceneDependencies(changes, pageIds, shared.index)
+ // Deleted components are interpreted per instance; broken hierarchy is not recoverable.
+ if (closure.missingIds.size)
+ throw new Error(`Missing reachable sources: ${[...closure.missingIds].join(', ')}`)
+ const sceneChanges = changes.filter(
+ (change) =>
+ change.type !== 'VARIABLE' &&
+ change.type !== 'VARIABLE_SET' &&
+ (change.type === 'CANVAS' ||
+ (change.guid &&
+ (closure.contentIds.has(guidToString(change.guid)) ||
+ closure.ancestorIds.has(guidToString(change.guid)))))
+ )
+ const sourceInterpreter = shared.sourceInterpreter
+ const interpreter = createOccurrenceInterpreter(sceneChanges)
+ const pages = changes
+ .filter((change) => change.type === 'CANVAS')
+ .toSorted(bySavedPosition)
+ .map((page) => {
+ if (!page.guid) throw new Error('Page has no GUID')
+ return {
+ id: guidToString(page.guid),
+ name: page.name ?? '',
+ position: page.parentIndex?.position ?? null,
+ internalOnly: page.internalOnly === true
+ }
+ })
+ const knownPageIds = new Set(pages.map((page) => page.id))
+ return {
+ selectPages(ids: ReadonlySet<string>) {
+ return createScopedReader(changes, bindingDiagnostics, ids, shared)
+ },
+ get sourceRecords() {
+ return structuredClone(changes)
+ },
+ get documentRecord() {
+ return structuredClone(changes.find((change) => change.type === 'DOCUMENT'))
+ },
+ dependencyClosure: closure,
+ pages,
+ get resources() {
+ return structuredClone(resources)
+ },
+ bindingDiagnostics,
+ readPage(id: string, options: InterpretInstanceOptions = {}) {
+ if (!knownPageIds.has(id)) throw new Error(`Unknown page ${id}`)
+ return interpreter.page(id, options)
+ },
+ planComponents(
+ roots: readonly ReturnType<typeof interpreter.page>[],
+ options: InterpretInstanceOptions = {}
+ ) {
+ return planComponentConstruction(
+ changes,
+ roots,
+ (id) => sourceInterpreter.component(id, options),
+ shared.index.sources
+ )
+ },
+ readComponent: sourceInterpreter.component
+ }
+}
diff --git a/packages/fig/src/document/resource-reference.ts b/packages/fig/src/document/resource-reference.ts
new file mode 100644
index 000000000..8bf457220
--- /dev/null
+++ b/packages/fig/src/document/resource-reference.ts
@@ -0,0 +1,27 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+/** Exact versioned lookup; explicit unversioned records win, otherwise ambiguous keys reject. */
+export function createResourceResolver(resources: readonly NodeChange[]) {
+ const keys = new Map<string, Map<string, string>>()
+ for (const resource of resources) {
+ if (!resource.guid || typeof resource.key !== 'string') continue
+ const versions = keys.get(resource.key) ?? new Map<string, string>()
+ const version = typeof resource.version === 'string' ? resource.version : ''
+ const id = guidToString(resource.guid)
+ if (versions.has(version) && versions.get(version) !== id) {
+ throw new Error(`Ambiguous resource ${resource.key} version ${version}`)
+ }
+ versions.set(version, id)
+ keys.set(resource.key, versions)
+ }
+ return (reference: NodeChange['variableSetID']): string | undefined => {
+ if (reference?.guid) return guidToString(reference.guid)
+ const asset = reference?.assetRef
+ if (!asset) return undefined
+ const versions = keys.get(asset.key)
+ if (asset.version) return versions?.get(asset.version)
+ if (versions?.has('')) return versions.get('')
+ return versions?.size === 1 ? versions.values().next().value : undefined
+ }
+}
diff --git a/packages/fig/src/document/style-dependencies.ts b/packages/fig/src/document/style-dependencies.ts
new file mode 100644
index 000000000..1b7d2e055
--- /dev/null
+++ b/packages/fig/src/document/style-dependencies.ts
@@ -0,0 +1,30 @@
+import type { NodeChange, StyleReference } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import { forEachOverrideRecord } from '../instance-overrides/types'
+
+export const STYLE_REFERENCE_FIELDS = [
+ 'styleIdForFill',
+ 'styleIdForStrokeFill',
+ 'styleIdForText',
+ 'styleIdForEffect',
+ 'styleIdForGrid'
+] as const
+
+/** Include available style definitions, including references declared on override paths. */
+export function styleDependencies(
+ node: NodeChange,
+ resolve: (reference: StyleReference) => string | undefined,
+ available: ReadonlySet<string>
+): Set<string> {
+ const result = new Set<string>()
+ forEachOverrideRecord(node, (source) => {
+ for (const field of STYLE_REFERENCE_FIELDS) {
+ const reference = source[field]
+ if (!reference) continue
+ const id = reference.guid ? guidToString(reference.guid) : resolve(reference)
+ if (id && available.has(id)) result.add(id)
+ }
+ })
+ return result
+}
diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.ts
new file mode 100644
index 000000000..f02e26ec9
--- /dev/null
+++ b/packages/fig/src/document/variables.ts
@@ -0,0 +1,116 @@
+import type { NodeChange, VariableDataValuesEntry } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+import type { SceneGraph, VariableValue } from '@open-pencil/scene-graph'
+
+import { createResourceResolver } from './resource-reference'
+
+function valueOf(
+ entry: VariableDataValuesEntry,
+ resolve: ReturnType<typeof createResourceResolver>
+): VariableValue {
+ const { value, dataType, resolvedDataType } = entry.variableData
+ if (!value) throw new Error('Missing variable value')
+ const type = dataType ?? resolvedDataType
+ if (type === 'ALIAS') {
+ const aliasId = resolve(value.alias)
+ if (!aliasId) throw new Error('Unresolved variable alias')
+ return { aliasId }
+ }
+ if (type === 'COLOR' && value.colorValue) return structuredClone(value.colorValue)
+ if (type === 'BOOLEAN' && value.boolValue !== undefined) return value.boolValue
+ if (type === 'STRING' && value.textValue !== undefined) return value.textValue
+ if (type === 'FLOAT' && value.floatValue !== undefined) return value.floatValue
+ throw new Error(`Unsupported variable value ${type}`)
+}
+
+function modeValues(
+ resource: NodeChange,
+ modes: readonly string[],
+ resolve: ReturnType<typeof createResourceResolver>
+): Record<string, VariableValue> {
+ const entries = resource.variableDataValues?.entries ?? []
+ if (!entries.length) throw new Error('Missing mode values')
+ const values: Record<string, VariableValue> = {}
+ for (const entry of entries) {
+ const modeId = guidToString(entry.modeID)
+ if (!modes.includes(modeId)) throw new Error('Unknown mode')
+ values[modeId] = valueOf(entry, resolve)
+ }
+ return values
+}
+
+/** No invented values or fallback collections: unsupported resources remain explicit. */
+export function materializeVariableResources(
+ graph: SceneGraph,
+ resources: readonly NodeChange[],
+ onUnsupported?: (resource: NodeChange) => void
+): void {
+ const report = (resource: NodeChange, reason: string): void => {
+ if (!onUnsupported) throw new Error(`Unsupported document resource ${resource.type}: ${reason}`)
+ onUnsupported(structuredClone(resource))
+ }
+ for (const resource of resources) {
+ if (resource.type !== 'VARIABLE_SET') continue
+ const modes = resource.variableSetModes ?? []
+ if (!resource.guid || modes.length === 0) {
+ report(resource, 'missing collection identity or modes')
+ continue
+ }
+ graph.addCollection({
+ id: guidToString(resource.guid),
+ name: resource.name ?? 'Variables',
+ modes: modes.map((mode) => ({ modeId: guidToString(mode.id), name: mode.name })),
+ defaultModeId: guidToString(modes[0].id),
+ variableIds: []
+ })
+ }
+ addVariables(graph, resources, report)
+}
+
+function addVariables(
+ graph: SceneGraph,
+ resources: readonly NodeChange[],
+ report: (resource: NodeChange, reason: string) => void
+): void {
+ const resolve = createResourceResolver(resources)
+ for (const resource of resources) {
+ if (resource.type !== 'VARIABLE') continue
+ const type = resource.variableResolvedType
+ const collectionId = resource.variableSetID
+ ? resolve(resource.variableSetID)
+ : resource.parentIndex?.guid && guidToString(resource.parentIndex.guid)
+ const collection = collectionId && graph.variableCollections.get(collectionId)
+ if (
+ !resource.guid ||
+ !collection ||
+ !collectionId ||
+ (type !== 'COLOR' && type !== 'BOOLEAN' && type !== 'STRING' && type !== 'FLOAT')
+ ) {
+ report(resource, 'unresolved collection, identity or type')
+ continue
+ }
+ const valuesByMode: Record<string, VariableValue> = {}
+ try {
+ Object.assign(
+ valuesByMode,
+ modeValues(
+ resource,
+ collection.modes.map((mode) => mode.modeId),
+ resolve
+ )
+ )
+ } catch (error) {
+ report(resource, error instanceof Error ? error.message : 'Invalid mode value')
+ continue
+ }
+ graph.addVariable({
+ id: guidToString(resource.guid),
+ name: resource.name ?? 'Variable',
+ type,
+ collectionId,
+ valuesByMode,
+ description: '',
+ hiddenFromPublishing: false
+ })
+ }
+}
diff --git a/packages/fig/src/index.ts b/packages/fig/src/index.ts
index 8ff1b00f8..fc85f5c95 100644
--- a/packages/fig/src/index.ts
+++ b/packages/fig/src/index.ts
@@ -1,3 +1,12 @@
+export { materializeFigFragment, type FragmentMaterializationOptions } from './document/fragment'
+export {
+ materializeDocument,
+ materializeFigArchive,
+ type FigSessionCheckpoint,
+ type FigSessionResume,
+ createFigDocumentSession,
+ type DocumentAssemblyOptions
+} from './document/materialize'
export {
compressFigDataSync,
parseFigBuffer,
@@ -57,7 +66,7 @@ export interface WriteFigContainerOptions {
readonly version?: number
}
-export const FIG_PACKAGE_STATUS = 'archive-api' as const
+export const FIG_PACKAGE_STATUS = 'document-reader' as const
export function readFigContainer(
bytes: Uint8Array,
@@ -83,9 +92,3 @@ export function writeFigContainer(
options.version ?? FIG_KIWI_DEFAULT_VERSION
)
}
-
-export function assertFigPackageReady(): void {
- throw new Error(
- '@open-pencil/fig currently exposes archive/container APIs; use @open-pencil/core for SceneGraph .fig read/write APIs for now.'
- )
-}
diff --git a/packages/fig/src/instance-overrides/bindings/properties.ts b/packages/fig/src/instance-overrides/bindings/properties.ts
new file mode 100644
index 000000000..31f208c2d
--- /dev/null
+++ b/packages/fig/src/instance-overrides/bindings/properties.ts
@@ -0,0 +1,128 @@
+import { cloneRecord } from '#fig/node-change/clone'
+
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import { sameGuid } from '../source-index'
+import type {
+ ComponentPropAssignment,
+ ComponentPropDef,
+ ComponentPropRef,
+ ComponentPropValue
+} from '../types'
+
+/** Values belong to one component expansion, never a document-wide property map. */
+export interface PropertyBinding {
+ id: GUID
+ value: ComponentPropValue
+ origin: 'default' | 'assignment'
+ /** Expansion depth of the owner that assigned the value; smaller is further out. */
+ rank?: number
+ /** Values this binding replaced, innermost first; claims may still address them. */
+ superseded?: ComponentPropValue[]
+}
+
+function assignmentValue(assignment: ComponentPropAssignment): ComponentPropValue | undefined {
+ const value = assignment.value
+ if (
+ value &&
+ (value.boolValue !== undefined ||
+ value.textValue !== undefined ||
+ value.guidValue !== undefined ||
+ value.textDataValue !== undefined)
+ )
+ return value
+ const variable = assignment.varValue?.value
+ if (variable?.symbolIdValue?.guid) return { guidValue: variable.symbolIdValue.guid }
+ if (variable?.boolValue !== undefined) return { boolValue: variable.boolValue }
+ if (variable?.textValue !== undefined) return { textValue: variable.textValue }
+ if (variable?.textDataValue !== undefined) return { textDataValue: variable.textDataValue }
+ return undefined
+}
+
+export function instanceBindings(
+ defaults: readonly PropertyBinding[],
+ assignments: readonly ComponentPropAssignment[],
+ rank?: number
+): PropertyBinding[] {
+ const result = structuredClone([...defaults])
+ for (const assignment of assignments) {
+ const value = assignmentValue(assignment)
+ if (!assignment.defID || !value) continue
+ const binding: PropertyBinding = {
+ id: assignment.defID,
+ value: structuredClone(value),
+ origin: 'assignment',
+ ...(rank === undefined ? {} : { rank })
+ }
+ const index = result.findIndex((entry) => sameGuid(entry.id, binding.id))
+ if (index === -1) {
+ result.push(binding)
+ continue
+ }
+ const previous = result[index]
+ result[index] = {
+ ...binding,
+ superseded: [...(previous.superseded ?? []), structuredClone(previous.value)]
+ }
+ }
+ return result
+}
+
+export function componentBindings(source: NodeChange): PropertyBinding[] {
+ const definitions = source.componentPropDefs as ComponentPropDef[] | undefined
+ return (definitions ?? []).flatMap((definition) =>
+ definition.id && definition.initialValue
+ ? [
+ {
+ id: definition.id,
+ value: structuredClone(definition.initialValue),
+ origin: 'default'
+ }
+ ]
+ : []
+ )
+}
+
+export interface BoundPropertyClaim {
+ definitionId: GUID
+ field: 'visible' | 'textData' | 'symbolData'
+ origin: PropertyBinding['origin']
+}
+
+export function bindSourceProperties(
+ source: NodeChange,
+ bindings: readonly PropertyBinding[],
+ record?: (claim: BoundPropertyClaim, binding: PropertyBinding) => void
+): NodeChange {
+ const result = cloneRecord(source)
+ const refs = source.componentPropRefs as
+ | (ComponentPropRef & { isDeleted?: boolean })[]
+ | undefined
+ for (const ref of refs ?? []) {
+ if (!ref.defID || ref.isDeleted) continue
+ const binding = bindings.find((entry) => sameGuid(entry.id, ref.defID as GUID))
+ if (!binding) continue
+ const { value, origin } = binding
+ const claim = (field: BoundPropertyClaim['field']): void => {
+ record?.({ definitionId: structuredClone(binding.id), field, origin }, binding)
+ }
+ if (ref.componentPropNodeField === 'VISIBLE' && value.boolValue !== undefined) {
+ result.visible = value.boolValue
+ claim('visible')
+ } else if (ref.componentPropNodeField === 'TEXT_DATA') {
+ const text =
+ typeof value.textValue === 'string'
+ ? value.textValue
+ : (value.textValue?.characters ?? value.textDataValue?.characters)
+ if (text !== undefined) {
+ if (text !== result.textData?.characters) result.derivedTextData = undefined
+ result.textData = { ...result.textData, characters: text }
+ claim('textData')
+ }
+ } else if (ref.componentPropNodeField === 'OVERRIDDEN_SYMBOL_ID' && value.guidValue) {
+ result.symbolData = { ...result.symbolData, symbolID: value.guidValue }
+ claim('symbolData')
+ }
+ }
+ return result
+}
diff --git a/packages/fig/src/instance-overrides/bindings/variables.ts b/packages/fig/src/instance-overrides/bindings/variables.ts
new file mode 100644
index 000000000..f305bd5e8
--- /dev/null
+++ b/packages/fig/src/instance-overrides/bindings/variables.ts
@@ -0,0 +1,71 @@
+import {
+ variableConsumptionEntries,
+ numericVariableAssignmentScales,
+ VARIABLE_BINDING_FIELDS_INVERSE
+} from '#fig/node-change/variable-bindings'
+import { linearVariableExpression } from '#fig/node-change/variable-expression'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { setInstanceOverride, type SceneNode } from '@open-pencil/scene-graph'
+
+import type { InstanceOccurrence } from '../interpret'
+import { uniformScaleOf } from '../types'
+
+export function occurrenceScale(occurrence: InstanceOccurrence): number {
+ return occurrence.layoutScale ?? 1
+}
+
+export function occurrenceAssignmentScales(occurrence: InstanceOccurrence): Record<string, number> {
+ return numericVariableAssignmentScales(
+ occurrence.mainComponentId !== null ? occurrenceScale(occurrence) : 1
+ )
+}
+
+export function recordVariableBindingClaims(
+ owner: SceneNode,
+ target: SceneNode,
+ patch: NodeChange
+): void {
+ for (const entry of variableConsumptionEntries(patch)) {
+ if (entry.variableData && !['ALIAS', 'EXPRESSION'].includes(entry.variableData.dataType ?? ''))
+ continue
+ const field = entry.variableField && VARIABLE_BINDING_FIELDS_INVERSE[entry.variableField]
+ if (!field) continue
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ target.id,
+ `boundVariables/${field}`,
+ target.boundVariables[field] ?? null
+ )
+ setInstanceOverride(owner.instanceOverrides, owner.id, target.id, 'boundVariables')
+ }
+}
+
+/** New declarations enter the current owner's pre-scale space, not the target's old space. */
+export function declareSourceVariableBindingUnits(
+ target: InstanceOccurrence,
+ source: NodeChange
+): void {
+ const scale = uniformScaleOf(source)
+ declareVariableBindingUnits(target, source, scale)
+}
+
+export function declareVariableBindingUnits(
+ target: InstanceOccurrence,
+ patch: NodeChange,
+ ownScale = 1
+): void {
+ for (const entry of variableConsumptionEntries(patch)) {
+ const field = entry.variableField && VARIABLE_BINDING_FIELDS_INVERSE[entry.variableField]
+ if (!field) continue
+ target.variableBindingScales ??= {}
+ const expression = linearVariableExpression(entry.variableData)
+ const multiplier = expression?.reference ? expression.multiplier : 1
+ const unit = field === 'opacity' ? 0.01 : 1
+ const expressionInPlacedUnits =
+ entry.variableData?.value?.expressionValue && field !== 'opacity' && field !== 'rotation'
+ target.variableBindingScales[field] =
+ (multiplier * unit) / (expressionInPlacedUnits ? ownScale : 1)
+ }
+}
diff --git a/packages/fig/src/instance-overrides/clone-index.ts b/packages/fig/src/instance-overrides/clone-index.ts
deleted file mode 100644
index 62db7c246..000000000
--- a/packages/fig/src/instance-overrides/clone-index.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { OverrideContext } from './types'
-
-export function buildCloneIndex(ctx: OverrideContext): Map<string, string[]> {
- const clonesBySource = new Map<string, string[]>()
- for (const [sourceId, nodeIds] of ctx.graph.instanceIndex) {
- for (const nodeId of nodeIds) {
- if (ctx.activeNodeIds && !ctx.activeNodeIds.has(nodeId)) continue
- if (ctx.graph.getNode(nodeId)?.type !== 'INSTANCE') continue
- const clones = clonesBySource.get(sourceId)
- if (clones) clones.push(nodeId)
- else clonesBySource.set(sourceId, [nodeId])
- }
- }
- return clonesBySource
-}
-
-export function instanceAndClones(
- instanceNodeId: string,
- clonesBySource: Map<string, string[]>,
- cache: Map<string, string[]>
-): string[] {
- const cached = cache.get(instanceNodeId)
- if (cached) return cached
- const result: string[] = []
- const seen = new Set<string>()
- const visit = (id: string) => {
- if (seen.has(id)) return
- seen.add(id)
- result.push(id)
- for (const cloneId of clonesBySource.get(id) ?? []) visit(cloneId)
- }
- visit(instanceNodeId)
- cache.set(instanceNodeId, result)
- return result
-}
diff --git a/packages/fig/src/instance-overrides/component-closure.ts b/packages/fig/src/instance-overrides/component-closure.ts
new file mode 100644
index 000000000..cb26341ba
--- /dev/null
+++ b/packages/fig/src/instance-overrides/component-closure.ts
@@ -0,0 +1,78 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { componentDependencies } from '../document/component/dependencies'
+import { linkComponentPropertyValues } from '../document/component/values'
+import { createResourceResolver } from '../document/resource-reference'
+import {
+ createOccurrenceInterpreter,
+ type InstanceOccurrence,
+ type InterpretInstanceOptions
+} from './interpret'
+import { materializeInstance } from './materialize-instance'
+import { occurrences } from './occurrence-path'
+import {
+ linkInstanceSourceChildren,
+ mapInstanceSourceChildren,
+ type MaterializedComponentOccurrence
+} from './source-children'
+
+export interface MaterializedComponentClosure extends ReadonlyMap<
+ string,
+ MaterializedComponentOccurrence
+> {
+ /** Unavailable preferred choices remain external keys, not required source dependencies. */
+ readonly externalPreferredKeys: ReadonlySet<string>
+}
+
+/** Build effective components and inactive property dependencies needed for later edits. */
+export function materializeComponentClosure(
+ graph: SceneGraph,
+ parentId: string,
+ changes: readonly NodeChange[],
+ root: InstanceOccurrence,
+ blobs: Uint8Array[] = [],
+ options: InterpretInstanceOptions = {}
+): MaterializedComponentClosure {
+ const interpreter = createOccurrenceInterpreter(changes)
+ const existingNodeIds = new Set(graph.nodes.keys())
+ const resolveReference = createResourceResolver(changes)
+ const externalPreferredKeys = new Set<string>()
+ const propertyDependencies = new Set<string>()
+ const components = new Map<string, MaterializedComponentOccurrence>()
+ const ids = new Map<string, string>()
+ const pending = new Set<string>()
+ const visit = (root: InstanceOccurrence): void => {
+ for (const occurrence of occurrences(root)) {
+ for (const dependency of componentDependencies(
+ occurrence.properties,
+ resolveReference,
+ (key) => externalPreferredKeys.add(key)
+ ))
+ propertyDependencies.add(dependency)
+ if (occurrence.mainComponentId !== null) ensure(occurrence.mainComponentId)
+ }
+ }
+ const ensure = (id: string): void => {
+ if (components.has(id)) return
+ if (pending.has(id)) throw new Error(`Cyclic component dependency ${id}`)
+ pending.add(id)
+ const occurrence = interpreter.component(id, options)
+ visit(occurrence)
+ const materialized = materializeInstance(graph, parentId, occurrence, ids, {
+ blobs,
+ sourceChildren: mapInstanceSourceChildren(occurrence, components)
+ })
+ linkInstanceSourceChildren(occurrence, materialized, components)
+ components.set(id, { occurrence, materialized })
+ ids.set(id, materialized.root.id)
+ pending.delete(id)
+ }
+ visit(root)
+ // A property default can point back to its own definition without forming a cyclic
+ // occurrence tree. Drain these edges after effective expansion, not on its call stack.
+ for (const dependency of propertyDependencies) ensure(dependency)
+ const materialized = [...graph.nodes.values()].filter((node) => !existingNodeIds.has(node.id))
+ linkComponentPropertyValues(graph, ids, materialized)
+ return Object.assign(components, { externalPreferredKeys })
+}
diff --git a/packages/fig/src/instance-overrides/component-props/apply.ts b/packages/fig/src/instance-overrides/component-props/apply.ts
deleted file mode 100644
index e7aaa6345..000000000
--- a/packages/fig/src/instance-overrides/component-props/apply.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { guidToString } from '@open-pencil/fig/node-change'
-import { copyFills, copyStyleRuns } from '@open-pencil/scene-graph/copy'
-
-import { applyOverridePatch, type OverridePatch } from '../patches'
-import { getComponentRoot } from '../resolve'
-import type { ComponentPropRef, ComponentPropValue, OverrideContext } from '../types'
-import { propTextCharacters } from './values'
-
-function applyPatchAndMark(
- ctx: OverrideContext,
- childId: string,
- patch: OverridePatch,
- modified?: Set<string>
-): void {
- if (applyOverridePatch(ctx, patch)) modified?.add(childId)
-}
-
-function applyVisibleProp(
- ctx: OverrideContext,
- childId: string,
- val: ComponentPropValue,
- modified?: Set<string>
-): void {
- if (val.boolValue === undefined) return
- applyPatchAndMark(
- ctx,
- childId,
- { targetId: childId, source: 'component-prop', props: { visible: val.boolValue } },
- modified
- )
-}
-
-function applyTextProp(
- ctx: OverrideContext,
- childId: string,
- val: ComponentPropValue,
- modified?: Set<string>
-): void {
- const child = ctx.graph.getNode(childId)
- const text = propTextCharacters(val)
- if (text === undefined || child?.type !== 'TEXT') return
- const source = child.componentId ? ctx.graph.getNode(child.componentId) : null
- const props: Parameters<typeof applyPatchAndMark>[2]['props'] = { text }
- if (source?.type === 'TEXT' && source.text === text) {
- props.width = source.width
- props.height = source.height
- props.fills = copyFills(source.fills)
- props.styleRuns = copyStyleRuns(source.styleRuns)
- props.derivedTextGlyphs = source.derivedTextGlyphs
- ? structuredClone(source.derivedTextGlyphs)
- : undefined
- }
- applyPatchAndMark(ctx, childId, { targetId: childId, source: 'component-prop', props }, modified)
-}
-
-function applySwapProp(
- ctx: OverrideContext,
- childId: string,
- val: ComponentPropValue,
- modified?: Set<string>
-): void {
- const swapId =
- propTextCharacters(val) ?? (val.guidValue ? guidToString(val.guidValue) : undefined)
- const newCompId = swapId ? ctx.guidToNodeId.get(swapId) : undefined
- if (!newCompId) return
- const currentCompId = ctx.graph.getNode(childId)?.componentId
- if (currentCompId && getComponentRoot(ctx, currentCompId) === getComponentRoot(ctx, newCompId)) {
- return
- }
- applyPatchAndMark(
- ctx,
- childId,
- {
- targetId: childId,
- source: 'component-prop',
- swapComponentId: getComponentRoot(ctx, newCompId)
- },
- modified
- )
-}
-
-export function applyComponentPropRef(
- ctx: OverrideContext,
- childId: string,
- ref: ComponentPropRef,
- val: ComponentPropValue,
- modified?: Set<string>
-): void {
- switch (ref.componentPropNodeField) {
- case 'VISIBLE':
- applyVisibleProp(ctx, childId, val, modified)
- break
- case 'TEXT_DATA':
- applyTextProp(ctx, childId, val, modified)
- break
- case 'OVERRIDDEN_SYMBOL_ID':
- applySwapProp(ctx, childId, val, modified)
- break
- }
-}
diff --git a/packages/fig/src/instance-overrides/component-props/assignments.ts b/packages/fig/src/instance-overrides/component-props/assignments.ts
deleted file mode 100644
index 177754cdb..000000000
--- a/packages/fig/src/instance-overrides/component-props/assignments.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
-
-import { buildCloneIndex, instanceAndClones } from '../clone-index'
-import { resolveOverrideTarget } from '../resolve'
-import type {
- ComponentPropAssignment,
- ComponentPropRef,
- ComponentPropValue,
- OverrideContext
-} from '../types'
-import { applyComponentPropRef } from './apply'
-import { fallbackRefsForChild, findPropRefs, valueForRef } from './refs'
-import { assignmentsToValueMap } from './values'
-
-function applyChildPropRefs(
- ctx: OverrideContext,
- childId: string,
- refs: ComponentPropRef[] | undefined,
- valueByDef: Map<string, ComponentPropValue>,
- modified?: Set<string>
-): void {
- if (!refs) return
- for (const ref of refs) {
- const val = valueForRef(ref, valueByDef)
- if (val) applyComponentPropRef(ctx, childId, ref, val, modified)
- }
-}
-
-function sourceChildPropRefs(
- ctx: OverrideContext,
- sourceParentId: string | null | undefined,
- child: SceneNode,
- propRefsMap: Map<string, ComponentPropRef[]>
-): ComponentPropRef[] | undefined {
- if (!sourceParentId) return undefined
- const sourceParent = ctx.graph.getNode(sourceParentId)
- if (!sourceParent) return undefined
-
- let fallbackMatchId: string | undefined
- for (const sourceChildId of sourceParent.childIds) {
- const sourceChild = ctx.graph.getNode(sourceChildId)
- if (!sourceChild) continue
- if (
- sourceChild.id === child.componentId ||
- (sourceChild.componentId && sourceChild.componentId === child.componentId)
- ) {
- return findPropRefs(ctx, sourceChild.id, propRefsMap) ?? []
- }
- if (!fallbackMatchId && sourceChild.name === child.name && sourceChild.type === child.type) {
- fallbackMatchId = sourceChild.id
- }
- }
-
- return fallbackMatchId ? findPropRefs(ctx, fallbackMatchId, propRefsMap) : undefined
-}
-
-function applyPropAssignments(
- ctx: OverrideContext,
- parentId: string,
- valueByDef: Map<string, ComponentPropValue>,
- propRefsMap: Map<string, ComponentPropRef[]>,
- modified?: Set<string>
-): void {
- const parent = ctx.graph.getNode(parentId)
- if (!parent) return
-
- for (const childId of parent.childIds) {
- const child = ctx.graph.getNode(childId)
- if (!child?.componentId) {
- applyPropAssignments(ctx, childId, valueByDef, propRefsMap, modified)
- continue
- }
-
- const refs =
- sourceChildPropRefs(ctx, parent.componentId, child, propRefsMap) ??
- findPropRefs(ctx, child.componentId, propRefsMap) ??
- fallbackRefsForChild(ctx, child.name, valueByDef)
- applyChildPropRefs(ctx, childId, refs, valueByDef, modified)
- applyPropAssignments(ctx, childId, valueByDef, propRefsMap, modified)
- }
-}
-
-export function applyInstanceDirectAssignments(
- ctx: OverrideContext,
- assignmentSources: Map<string, ComponentPropAssignment[]>,
- propRefsMap: Map<string, ComponentPropRef[]>,
- modified: Set<string>
-): void {
- for (const [figmaId, assignments] of assignmentSources) {
- const nodeId = ctx.guidToNodeId.get(figmaId)
- if (!nodeId || (ctx.activeNodeIds && !ctx.activeNodeIds.has(nodeId))) continue
- if (ctx.graph.getNode(nodeId)?.type !== 'INSTANCE') continue
- applyPropAssignments(
- ctx,
- nodeId,
- assignmentsToValueMap(ctx, assignments),
- propRefsMap,
- modified
- )
- }
-}
-
-export function applyOverrideAssignments(
- ctx: OverrideContext,
- propRefsMap: Map<string, ComponentPropRef[]>,
- modified: Set<string>
-): void {
- const clonesBySource = buildCloneIndex(ctx)
- const clonesByInstance = new Map<string, string[]>()
- for (const [figmaId, nc] of ctx.changeMap) {
- const instanceNodeId = ctx.guidToNodeId.get(figmaId)
- if (!instanceNodeId || (ctx.activeNodeIds && !ctx.activeNodeIds.has(instanceNodeId))) continue
- if (ctx.graph.getNode(instanceNodeId)?.type !== 'INSTANCE') continue
-
- const overrides = nc.symbolData?.symbolOverrides
- if (!overrides) continue
- for (const ov of overrides) {
- if (!ov.componentPropAssignments?.length) continue
-
- const guids = ov.guidPath?.guids
- if (!guids?.length) continue
-
- const valueByDef = assignmentsToValueMap(ctx, ov.componentPropAssignments, true)
- for (const targetInstanceId of instanceAndClones(
- instanceNodeId,
- clonesBySource,
- clonesByInstance
- )) {
- const targetId = resolveOverrideTarget(ctx, targetInstanceId, guids)
- if (!targetId) continue
-
- applyPropAssignments(ctx, targetId, valueByDef, propRefsMap, modified)
- }
- }
- }
-}
diff --git a/packages/fig/src/instance-overrides/component-props/index.ts b/packages/fig/src/instance-overrides/component-props/index.ts
deleted file mode 100644
index 88de5c16e..000000000
--- a/packages/fig/src/instance-overrides/component-props/index.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import type { OverrideContext } from '../types'
-import { applyInstanceDirectAssignments, applyOverrideAssignments } from './assignments'
-import { collectAssignmentsMap, collectPropRefsMap } from './maps'
-
-/**
- * Apply all component property assignments (visibility toggles, instance swaps).
- *
- * Returns the set of modified node IDs so the caller can run a second
- * transitive sync to propagate the changes to deeper clones.
- */
-export function applyComponentProperties(ctx: OverrideContext): Set<string> {
- const modified = new Set<string>()
- const propRefsMap = collectPropRefsMap(ctx)
- if (propRefsMap.size === 0) return modified
-
- applyInstanceDirectAssignments(ctx, collectAssignmentsMap(ctx), propRefsMap, modified)
- applyOverrideAssignments(ctx, propRefsMap, modified)
-
- return modified
-}
diff --git a/packages/fig/src/instance-overrides/component-props/maps.ts b/packages/fig/src/instance-overrides/component-props/maps.ts
deleted file mode 100644
index befc65416..000000000
--- a/packages/fig/src/instance-overrides/component-props/maps.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import type { ComponentPropAssignment, ComponentPropRef, OverrideContext } from '../types'
-
-export function collectPropRefsMap(ctx: OverrideContext): Map<string, ComponentPropRef[]> {
- if (ctx.componentPropRefsMap) return ctx.componentPropRefsMap
- const result = new Map<string, ComponentPropRef[]>()
- for (const [figmaId, nc] of ctx.changeMap) {
- if (nc.componentPropRefs?.length) result.set(figmaId, nc.componentPropRefs)
- }
- ctx.componentPropRefsMap = result
- return result
-}
-
-export function collectAssignmentsMap(
- ctx: OverrideContext
-): Map<string, ComponentPropAssignment[]> {
- if (ctx.componentPropAssignmentsMap) return ctx.componentPropAssignmentsMap
- const result = new Map<string, ComponentPropAssignment[]>()
- for (const [figmaId, nc] of ctx.changeMap) {
- if (nc.componentPropAssignments?.length) result.set(figmaId, nc.componentPropAssignments)
- }
- ctx.componentPropAssignmentsMap = result
- return result
-}
diff --git a/packages/fig/src/instance-overrides/component-props/refs.ts b/packages/fig/src/instance-overrides/component-props/refs.ts
deleted file mode 100644
index 279c54c13..000000000
--- a/packages/fig/src/instance-overrides/component-props/refs.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { guidToString } from '@open-pencil/fig/node-change'
-
-import type { ComponentPropRef, ComponentPropValue, OverrideContext } from '../types'
-import { normalizePropName, stringToGuidParts } from './values'
-
-export function findPropRefs(
- ctx: OverrideContext,
- nodeId: string,
- propRefsMap: Map<string, ComponentPropRef[]>
-): ComponentPropRef[] | undefined {
- let sourceId: string | undefined = nodeId
- for (let depth = 0; sourceId && depth < 10; depth++) {
- const node = ctx.graph.getNode(sourceId)
- const overrideKey = node?.overrideKey
- ? (ctx.overrideKeyToGuid.get(node.overrideKey) ?? node.overrideKey)
- : undefined
- const figmaId = ctx.nodeIdToGuid.get(sourceId) ?? overrideKey
- if (figmaId) {
- const refs = propRefsMap.get(figmaId)
- if (refs) return refs
- }
- const nextId = node?.componentId ?? undefined
- if (nextId === sourceId) break
- sourceId = nextId
- }
- return undefined
-}
-
-export function fallbackRefsForChild(
- ctx: OverrideContext,
- childName: string,
- valueByDef: Map<string, ComponentPropValue>
-): ComponentPropRef[] | undefined {
- const normalizedChildName = normalizePropName(childName)
- const refs: ComponentPropRef[] = []
- for (const defId of valueByDef.keys()) {
- const propName = ctx.propNames.get(defId)
- if (propName && normalizePropName(propName) === normalizedChildName) {
- refs.push({ defID: stringToGuidParts(defId), componentPropNodeField: 'VISIBLE' })
- }
- }
- return refs.length > 0 ? refs : undefined
-}
-
-export function valueForRef(
- ref: ComponentPropRef,
- valueByDef: Map<string, ComponentPropValue>
-): ComponentPropValue | undefined {
- return ref.defID ? valueByDef.get(guidToString(ref.defID)) : undefined
-}
diff --git a/packages/fig/src/instance-overrides/component-props/values.ts b/packages/fig/src/instance-overrides/component-props/values.ts
deleted file mode 100644
index 0799b4f0d..000000000
--- a/packages/fig/src/instance-overrides/component-props/values.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { guidToString } from '@open-pencil/fig/node-change'
-import type { GUID } from '@open-pencil/kiwi/fig/codec'
-
-import type { ComponentPropAssignment, ComponentPropValue, OverrideContext } from '../types'
-
-export function normalizePropName(value: string): string {
- return value.toLowerCase().replace(/[^a-z0-9]/g, '')
-}
-
-export function stringToGuidParts(value: string): GUID {
- const [sessionID, localID] = value.split(':').map(Number)
- return { sessionID, localID }
-}
-
-export function propTextCharacters(value: ComponentPropValue): string | undefined {
- if (typeof value.textValue === 'string') return value.textValue
- return value.textValue?.characters ?? value.textDataValue?.characters
-}
-
-function isEmptyPropValue(v: ComponentPropValue | undefined): boolean {
- if (!v) return true
- return (
- v.boolValue === undefined &&
- v.textValue === undefined &&
- v.textDataValue === undefined &&
- v.guidValue === undefined
- )
-}
-
-function resolveAssignmentValue(
- ctx: OverrideContext,
- assignment: ComponentPropAssignment,
- key: string,
- resolveDefaults: boolean
-): ComponentPropValue | undefined {
- const value = assignment.value
- if (value && !isEmptyPropValue(value)) return value
-
- const variableValue = assignment.varValue?.value
- if (variableValue?.symbolIdValue?.guid) return { guidValue: variableValue.symbolIdValue.guid }
- if (variableValue?.boolValue !== undefined) return { boolValue: variableValue.boolValue }
- if (variableValue?.textValue !== undefined) return { textValue: variableValue.textValue }
- if (variableValue?.textDataValue !== undefined)
- return { textDataValue: variableValue.textDataValue }
-
- return resolveDefaults ? (ctx.propDefaults.get(key) ?? assignment.value) : assignment.value
-}
-
-export function assignmentsToValueMap(
- ctx: OverrideContext,
- assignments: ComponentPropAssignment[],
- resolveDefaults = false
-): Map<string, ComponentPropValue> {
- const valueByDef = new Map<string, ComponentPropValue>()
- for (const assignment of assignments) {
- if (!assignment.defID) continue
- const key = guidToString(assignment.defID)
- const value = resolveAssignmentValue(ctx, assignment, key, resolveDefaults)
- if (value) valueByDef.set(key, value)
- }
- return valueByDef
-}
diff --git a/packages/fig/src/instance-overrides/constraints.ts b/packages/fig/src/instance-overrides/constraints.ts
deleted file mode 100644
index a32afb7e7..000000000
--- a/packages/fig/src/instance-overrides/constraints.ts
+++ /dev/null
@@ -1,412 +0,0 @@
-import type { SceneGraph, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'
-import { copyGeometryPaths, scaleGeometryPaths } from '@open-pencil/scene-graph/copy'
-import { constrainedChildRect } from '@open-pencil/scene-graph/resize'
-
-import { readEffectiveFigmaRawField } from '../source-metadata'
-import { isFieldProtected } from './patches'
-import { buildClonesMap } from './sync'
-import type { OverrideContext } from './types'
-import { overrideCandidates } from './utils'
-
-const MAX_CLONE_CHAIN_DEPTH = 10
-
-interface ScaleDescendantAxes {
- horizontal: boolean
- vertical: boolean
-}
-
-interface InstanceScale {
- basis: SceneNode
- scaleThroughFixedWrappers: boolean
- sx: number
- sy: number
- useCurrentChildAsSource: boolean
-}
-
-/**
- * Apply SCALE constraint resizing to children of instances whose size
- * differs from their component's original size, then propagate the
- * changes through clone chains.
- */
-export function applyConstraintScaling(ctx: OverrideContext): void {
- const { graph } = ctx
- const scaled = new Set<string>()
-
- for (const node of overrideCandidates(graph, ctx.activeNodeIds)) {
- if (node.type !== 'INSTANCE' || !node.componentId) continue
- const comp = graph.getNode(node.componentId)
- if (!comp || comp.width <= 0 || comp.height <= 0) continue
- const scale = resolveInstanceScale(graph, node, comp)
- if (!scale) continue
-
- positionPinnedAbsoluteChildren(ctx, node, scale.basis)
- if (node.layoutMode !== 'NONE') continue
-
- const { sx, sy } = scale
- if (Math.abs(sx - 1) < 0.001 && Math.abs(sy - 1) < 0.001) continue
-
- const figmaId = ctx.nodeIdToGuid.get(node.id)
- const strokeScale = figmaId ? ctx.changeMap.get(figmaId)?.strokeWeight : undefined
- scaleChildren(
- graph,
- node,
- comp,
- sx,
- sy,
- scaled,
- ctx.geometryOverrideNodes,
- scale.useCurrentChildAsSource,
- strokeScale,
- scale.scaleThroughFixedWrappers
- )
- }
-
- if (scaled.size > 0) propagateScaling(ctx, scaled)
-}
-
-function resolveInstanceScale(
- graph: SceneGraph,
- instance: SceneNode,
- component: SceneNode
-): InstanceScale | null {
- const targetAspectRatio = resolveTargetAspectRatio(instance)
- const resolvedBasis = resolveScaleBasis(graph, instance, component)
- if (!targetAspectRatio && !resolvedBasis) return null
- const basis = resolvedBasis ?? component
- const scaleThroughFixedWrappers = targetAspectRatio !== null
- return {
- basis,
- scaleThroughFixedWrappers,
- sx: instance.width / basis.width,
- sy: instance.height / basis.height,
- useCurrentChildAsSource: basis !== component
- }
-}
-
-function resolveTargetAspectRatio(instance: SceneNode): { width: number; height: number } | null {
- const rawTarget = readEffectiveFigmaRawField(instance, 'targetAspectRatio')
- if (!rawTarget || typeof rawTarget !== 'object' || !('value' in rawTarget)) return null
- const value = rawTarget.value
- if (!value || typeof value !== 'object' || !('x' in value) || !('y' in value)) return null
- const { x, y } = value
- if (
- typeof x !== 'number' ||
- typeof y !== 'number' ||
- !Number.isFinite(x) ||
- !Number.isFinite(y) ||
- x <= 0 ||
- y <= 0
- ) {
- return null
- }
- return { width: x, height: y }
-}
-
-function isCloneOfSource(graph: SceneGraph, child: SceneNode, sourceId: string): boolean {
- let current: SceneNode | undefined = child
- for (let depth = 0; depth < MAX_CLONE_CHAIN_DEPTH && current?.componentId; depth++) {
- if (current.componentId === sourceId) return true
- current = graph.getNode(current.componentId)
- }
- return false
-}
-
-function pinnedPositionUpdates(
- ctx: OverrideContext,
- child: SceneNode,
- resized: ReturnType<typeof constrainedChildRect>
-): Partial<SceneNode> {
- const updates: Partial<SceneNode> = {}
- const horizontalPinned =
- child.horizontalConstraint === 'MAX' || child.horizontalConstraint === 'CENTER'
- const verticalPinned = child.verticalConstraint === 'MAX' || child.verticalConstraint === 'CENTER'
- if (
- horizontalPinned &&
- child.derivedLayout?.x === undefined &&
- !isFieldProtected(ctx.protectedFields, child.id, 'x') &&
- child.x !== resized.x
- ) {
- updates.x = resized.x
- }
- if (
- verticalPinned &&
- child.derivedLayout?.y === undefined &&
- !isFieldProtected(ctx.protectedFields, child.id, 'y') &&
- child.y !== resized.y
- ) {
- updates.y = resized.y
- }
- return updates
-}
-
-function stretchedChildSizeUpdates(
- ctx: OverrideContext,
- child: SceneNode,
- resized: ReturnType<typeof constrainedChildRect>
-): Partial<SceneNode> {
- const updates: Partial<SceneNode> = {}
- if (
- child.horizontalConstraint === 'STRETCH' &&
- child.derivedLayout?.width === undefined &&
- !isFieldProtected(ctx.protectedFields, child.id, 'width') &&
- child.width !== resized.width
- ) {
- updates.width = resized.width
- }
- if (
- child.verticalConstraint === 'STRETCH' &&
- child.derivedLayout?.height === undefined &&
- !isFieldProtected(ctx.protectedFields, child.id, 'height') &&
- child.height !== resized.height
- ) {
- updates.height = resized.height
- }
- return updates
-}
-
-function pinnedChildUpdates(
- ctx: OverrideContext,
- child: SceneNode,
- resized: ReturnType<typeof constrainedChildRect>
-): Partial<SceneNode> {
- return {
- ...pinnedPositionUpdates(ctx, child, resized),
- ...stretchedChildSizeUpdates(ctx, child, resized)
- }
-}
-
-function positionPinnedAbsoluteChildren(
- ctx: OverrideContext,
- instance: SceneNode,
- source: SceneNode
-): void {
- const count = Math.min(instance.childIds.length, source.childIds.length)
- for (let index = 0; index < count; index++) {
- const child = ctx.graph.getNode(instance.childIds[index])
- const sourceChild = ctx.graph.getNode(source.childIds[index])
- if (!child || !sourceChild || child.layoutPositioning !== 'ABSOLUTE') continue
- if (child.componentId && !isCloneOfSource(ctx.graph, child, sourceChild.id)) continue
-
- const resized = constrainedChildRect(
- sourceChild,
- source,
- instance,
- child.horizontalConstraint,
- child.verticalConstraint
- )
- const updates = pinnedChildUpdates(ctx, child, resized)
- if (Object.keys(updates).length > 0) ctx.graph.updateNode(child.id, updates)
- }
-}
-
-function resolveScaleBasis(
- graph: SceneGraph,
- instance: SceneNode,
- component: SceneNode
-): SceneNode | null {
- if (instance.width !== component.width || instance.height !== component.height) return component
-
- let source: SceneNode = component
- for (
- let depth = 0;
- depth < MAX_CLONE_CHAIN_DEPTH && source.type === 'INSTANCE' && source.componentId;
- depth++
- ) {
- const next = graph.getNode(source.componentId)
- if (!next || next.width <= 0 || next.height <= 0) break
- if (instance.width !== next.width || instance.height !== next.height) return next
- source = next
- }
-
- return null
-}
-
-function scaleVectorNetwork(
- network: VectorNetwork | null,
- sx: number,
- sy: number
-): VectorNetwork | null {
- if (!network) return null
- return {
- vertices: network.vertices.map((vertex) => ({ ...vertex, x: vertex.x * sx, y: vertex.y * sy })),
- segments: network.segments.map((segment) => ({
- ...segment,
- tangentStart: { x: segment.tangentStart.x * sx, y: segment.tangentStart.y * sy },
- tangentEnd: { x: segment.tangentEnd.x * sx, y: segment.tangentEnd.y * sy }
- })),
- regions: structuredClone(network.regions)
- }
-}
-
-function scaledStrokes(
- source: SceneNode,
- child: SceneNode,
- shapeScaleX: number,
- shapeScaleY: number,
- strokeScale?: number
-) {
- if (source.strokes.length !== child.strokes.length) return undefined
- if (Math.abs(shapeScaleX - shapeScaleY) >= 0.001) return undefined
- const scale = strokeScale ?? 1
- return child.strokes.map((stroke, strokeIndex) => ({
- ...stroke,
- weight: source.strokes[strokeIndex].weight * scale
- }))
-}
-
-function scaledGeometryUpdates(
- source: SceneNode,
- shapeScaleX: number,
- shapeScaleY: number,
- hasDerivedGeometry: boolean
-): Partial<SceneNode> {
- const updates: Partial<SceneNode> = {}
- if (!hasDerivedGeometry && source.fillGeometry.length > 0) {
- updates.fillGeometry = scaleGeometryPaths(source.fillGeometry, shapeScaleX, shapeScaleY)
- }
- if (!hasDerivedGeometry && source.strokeGeometry.length > 0) {
- updates.strokeGeometry = scaleGeometryPaths(source.strokeGeometry, shapeScaleX, shapeScaleY)
- }
- if (source.vectorNetwork) {
- updates.vectorNetwork = scaleVectorNetwork(source.vectorNetwork, shapeScaleX, shapeScaleY)
- }
- return updates
-}
-
-function scaleDescendantAxes(
- graph: SceneGraph,
- node: SceneNode,
- cache: Map<string, ScaleDescendantAxes>
-): ScaleDescendantAxes {
- const cached = cache.get(node.id)
- if (cached) return cached
- const result: ScaleDescendantAxes = { horizontal: false, vertical: false }
- for (const child of graph.getChildren(node.id)) {
- const nested = scaleDescendantAxes(graph, child, cache)
- result.horizontal ||= child.horizontalConstraint === 'SCALE' || nested.horizontal
- result.vertical ||= child.verticalConstraint === 'SCALE' || nested.vertical
- if (result.horizontal && result.vertical) break
- }
- cache.set(node.id, result)
- return result
-}
-
-function childScaleAxes(
- graph: SceneGraph,
- child: SceneNode,
- scaleThroughFixedWrappers: boolean,
- cache: Map<string, ScaleDescendantAxes>
-): ScaleDescendantAxes {
- const descendantAxes = scaleDescendantAxes(graph, child, cache)
- return {
- horizontal:
- child.horizontalConstraint === 'SCALE' ||
- (scaleThroughFixedWrappers && descendantAxes.horizontal),
- vertical:
- child.verticalConstraint === 'SCALE' || (scaleThroughFixedWrappers && descendantAxes.vertical)
- }
-}
-
-function scaleChildren(
- graph: SceneGraph,
- instance: SceneNode,
- comp: SceneNode,
- sx: number,
- sy: number,
- scaled: Set<string>,
- geometryOverrideNodes: Set<string>,
- useCurrentChildAsSource = false,
- strokeScale?: number,
- scaleThroughFixedWrappers = false,
- descendantScaleCache = new Map<string, ScaleDescendantAxes>()
-): void {
- const len = Math.min(instance.childIds.length, comp.childIds.length)
- for (let i = 0; i < len; i++) {
- const child = graph.getNode(instance.childIds[i])
- const compChild = graph.getNode(comp.childIds[i])
- if (!child || !compChild) continue
-
- const scaleAxes = childScaleAxes(graph, child, scaleThroughFixedWrappers, descendantScaleCache)
- const hScale = scaleAxes.horizontal
- const vScale = scaleAxes.vertical
- if (!hScale && !vScale) continue
-
- const updates: Partial<SceneNode> = {}
- const source = useCurrentChildAsSource ? child : compChild
- if (hScale) {
- updates.x = source.x * sx
- updates.width = source.width * sx
- }
- if (vScale) {
- updates.y = source.y * sy
- updates.height = source.height * sy
- }
- const shapeScaleX = hScale ? sx : 1
- const shapeScaleY = vScale ? sy : 1
- Object.assign(
- updates,
- scaledGeometryUpdates(source, shapeScaleX, shapeScaleY, geometryOverrideNodes.has(child.id))
- )
- updates.strokes = scaledStrokes(source, child, shapeScaleX, shapeScaleY, strokeScale)
- graph.updateNode(child.id, updates)
- scaled.add(child.id)
-
- if (child.childIds.length > 0 && compChild.childIds.length > 0) {
- scaleChildren(
- graph,
- child,
- compChild,
- hScale ? sx : 1,
- vScale ? sy : 1,
- scaled,
- geometryOverrideNodes,
- useCurrentChildAsSource,
- strokeScale,
- scaleThroughFixedWrappers,
- descendantScaleCache
- )
- }
- }
-}
-
-function propagateScaling(ctx: OverrideContext, scaled: Set<string>): void {
- const { graph } = ctx
- const clonesOf = buildClonesMap(graph, ctx.activeNodeIds)
- const queue = [...scaled]
- const visited = new Set<string>()
-
- let index = 0
- while (index < queue.length) {
- const srcId = queue[index]
- index++
- const source = graph.getNode(srcId)
- if (!source) continue
- const clones = clonesOf.get(srcId)
- if (!clones) continue
- for (const cloneId of clones) {
- if (visited.has(cloneId)) continue
- visited.add(cloneId)
- const clone = graph.getNode(cloneId)
- if (!clone) continue
- const cu: Partial<SceneNode> = {}
- if (clone.width !== source.width) cu.width = source.width
- if (clone.height !== source.height) cu.height = source.height
- if (clone.x !== source.x) cu.x = source.x
- if (clone.y !== source.y) cu.y = source.y
- if (!ctx.geometryOverrideNodes.has(cloneId)) {
- if (source.fillGeometry.length > 0) cu.fillGeometry = copyGeometryPaths(source.fillGeometry)
- if (source.strokeGeometry.length > 0)
- cu.strokeGeometry = copyGeometryPaths(source.strokeGeometry)
- if (source.vectorNetwork) cu.vectorNetwork = structuredClone(source.vectorNetwork)
- }
- if (source.strokes.length === clone.strokes.length) {
- cu.strokes = clone.strokes.map((stroke, strokeIndex) => ({
- ...stroke,
- weight: source.strokes[strokeIndex].weight
- }))
- }
- if (Object.keys(cu).length > 0) graph.updateNode(cloneId, cu)
- queue.push(cloneId)
- }
- }
-}
diff --git a/packages/fig/src/instance-overrides/derived-symbol-data.ts b/packages/fig/src/instance-overrides/derived-symbol-data.ts
new file mode 100644
index 000000000..7698fba63
--- /dev/null
+++ b/packages/fig/src/instance-overrides/derived-symbol-data.ts
@@ -0,0 +1,21 @@
+import type { InstanceOccurrence } from './interpret'
+import type { DerivedSymbolOverride } from './types'
+
+/** Copy one saved occurrence-derived record onto its target; a cache, not a claim. */
+export function applyDerivedEntry(target: InstanceOccurrence, entry: DerivedSymbolOverride): void {
+ const props = target.properties
+ if (entry.derivedTextData) props.derivedTextData = structuredClone(entry.derivedTextData)
+ if (entry.fontSize !== undefined) props.fontSize = entry.fontSize
+ if (entry.lineHeight !== undefined) props.lineHeight = structuredClone(entry.lineHeight)
+ if (entry.letterSpacing !== undefined) props.letterSpacing = structuredClone(entry.letterSpacing)
+ if (entry.size) {
+ props.size = structuredClone(entry.size)
+ target.derivedSize = structuredClone(entry.size)
+ }
+ if (entry.transform) props.transform = structuredClone(entry.transform)
+ // These are Kiwi geometry records with blob indexes, not SceneGraph geometry arrays.
+ const { fillGeometry, strokeGeometry, vectorData } = entry
+ if (fillGeometry) props.fillGeometry = structuredClone(fillGeometry)
+ if (strokeGeometry) props.strokeGeometry = structuredClone(strokeGeometry)
+ if (vectorData) props.vectorData = structuredClone(vectorData)
+}
diff --git a/packages/fig/src/instance-overrides/derived-symbol-data/geometry.ts b/packages/fig/src/instance-overrides/derived-symbol-data/geometry.ts
deleted file mode 100644
index c14f8c78f..000000000
--- a/packages/fig/src/instance-overrides/derived-symbol-data/geometry.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import {
- alignGeometryWindingRules,
- resolveGeometryPaths,
- resolveVectorStyleOverrideFills
-} from '@open-pencil/fig/node-change'
-import type { SceneNode } from '@open-pencil/scene-graph'
-import { scaleGeometryPaths } from '@open-pencil/scene-graph/copy'
-import { cloneVectorNetwork } from '@open-pencil/scene-graph/vector-network'
-
-import type { DerivedSymbolOverride } from '../types'
-
-export function resolveDsdGeometry(
- d: DerivedSymbolOverride,
- target: SceneNode,
- blobs: Uint8Array[]
-): Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry' | 'vectorNetwork'> {
- const result: Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry' | 'vectorNetwork'> = {}
- const fg = resolveGeometryPaths(d.fillGeometry, blobs, resolveVectorStyleOverrideFills(d))
- const sg = resolveGeometryPaths(d.strokeGeometry, blobs)
-
- if (fg.length > 0) result.fillGeometry = alignGeometryWindingRules(fg, target.vectorNetwork)
- else if (d.size && target.fillGeometry.length > 0 && target.width > 0 && target.height > 0) {
- result.fillGeometry = scaleGeometryPaths(
- target.fillGeometry,
- d.size.x / target.width,
- d.size.y / target.height
- )
- }
-
- if (sg.length > 0) result.strokeGeometry = sg
- else if (d.size && target.strokeGeometry.length > 0 && target.width > 0 && target.height > 0) {
- result.strokeGeometry = scaleGeometryPaths(
- target.strokeGeometry,
- d.size.x / target.width,
- d.size.y / target.height
- )
- }
-
- if (d.size && target.vectorNetwork?.vertices.length) {
- const network = cloneVectorNetwork(target.vectorNetwork)
- const originX = Math.min(...network.vertices.map(({ x }) => x))
- const originY = Math.min(...network.vertices.map(({ y }) => y))
- const xs = network.vertices.map(({ x }) => x)
- const ys = network.vertices.map(({ y }) => y)
- const networkWidth = Math.max(...xs) - Math.min(...xs)
- const networkHeight = Math.max(...ys) - Math.min(...ys)
- const scaleX = networkWidth === 0 ? 1 : d.size.x / networkWidth
- const scaleY = networkHeight === 0 ? 1 : d.size.y / networkHeight
- for (const vertex of network.vertices) {
- vertex.x = originX + (vertex.x - originX) * scaleX
- vertex.y = originY + (vertex.y - originY) * scaleY
- }
- for (const segment of network.segments) {
- segment.tangentStart.x *= scaleX
- segment.tangentStart.y *= scaleY
- segment.tangentEnd.x *= scaleX
- segment.tangentEnd.y *= scaleY
- }
- result.vectorNetwork = network
- }
-
- return result
-}
diff --git a/packages/fig/src/instance-overrides/derived-symbol-data/index.ts b/packages/fig/src/instance-overrides/derived-symbol-data/index.ts
deleted file mode 100644
index 85db23af7..000000000
--- a/packages/fig/src/instance-overrides/derived-symbol-data/index.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { applyOverridePatch } from '../patches'
-import { resolveOverrideTarget } from '../resolve'
-import type { DerivedSymbolOverride, OverrideContext } from '../types'
-import { buildDsdLayoutUpdates } from './layout'
-import { propagateDsdChanges } from './propagate'
-
-function applyDsdOverride(
- ctx: OverrideContext,
- visibleSiblingCount: Map<string, number>,
- nodeId: string,
- d: DerivedSymbolOverride,
- modified: Set<string>,
- sizeSet: Set<string>
-): void {
- const guids = d.guidPath?.guids
- if (!guids?.length) return
-
- const targetId = resolveOverrideTarget(ctx, nodeId, guids)
- if (!targetId) return
- if (targetId === nodeId) {
- // The instance NodeChange already carries its authoritative root bounds.
- // Keep descendant propagation from replacing them with component bounds.
- sizeSet.add(nodeId)
- return
- }
-
- const target = ctx.graph.getNode(targetId)
- if (!target) return
-
- const { updates, hasSize } = buildDsdLayoutUpdates(ctx, visibleSiblingCount, d, target)
- if (d.fillGeometry?.length || d.strokeGeometry?.length) ctx.geometryOverrideNodes.add(targetId)
- if (Object.keys(updates).length === 0) return
-
- if (applyOverridePatch(ctx, { targetId, source: 'derived-symbol-data', props: updates })) {
- modified.add(targetId)
- }
- if (hasSize) sizeSet.add(targetId)
-}
-
-function resolveDsdUpdates(ctx: OverrideContext): { modified: Set<string>; sizeSet: Set<string> } {
- const modified = new Set<string>()
- const sizeSet = new Set<string>()
- const visibleSiblingCount = new Map<string, number>()
- for (const [ncId, nc] of ctx.changeMap) {
- if (nc.type !== 'INSTANCE') continue
- const derived = nc.derivedSymbolData
- if (!derived?.length) continue
-
- const nodeId = ctx.guidToNodeId.get(ncId)
- if (!nodeId || (ctx.activeNodeIds && !ctx.activeNodeIds.has(nodeId))) continue
-
- for (const d of derived)
- applyDsdOverride(ctx, visibleSiblingCount, nodeId, d, modified, sizeSet)
- }
-
- return { modified, sizeSet }
-}
-
-export function applyDerivedSymbolData(ctx: OverrideContext): void {
- const { modified, sizeSet } = resolveDsdUpdates(ctx)
- propagateDsdChanges(ctx, modified, sizeSet)
-}
diff --git a/packages/fig/src/instance-overrides/derived-symbol-data/layout.ts b/packages/fig/src/instance-overrides/derived-symbol-data/layout.ts
deleted file mode 100644
index cb3a84201..000000000
--- a/packages/fig/src/instance-overrides/derived-symbol-data/layout.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import {
- convertFigmaTransformProps,
- convertFigmaDerivedTextGlyphs,
- convertLetterSpacing,
- convertLineHeight
-} from '@open-pencil/fig/node-change'
-import { getNodeLocalMatrix, type SceneNode } from '@open-pencil/scene-graph'
-
-import type { DerivedSymbolOverride, OverrideContext } from '../types'
-import { resolveDsdGeometry } from './geometry'
-
-function getVisibleSiblingCount(
- ctx: OverrideContext,
- cache: Map<string, number>,
- parentId: string
-): number {
- const cached = cache.get(parentId)
- if (cached !== undefined) return cached
- const count = ctx.graph.getChildren(parentId).filter((child) => child.visible).length
- cache.set(parentId, count)
- return count
-}
-
-function resolveSizeOnlyPosition(
- ctx: OverrideContext,
- visibleSiblingCount: Map<string, number>,
- node: SceneNode
-): Pick<SceneNode, 'x' | 'y'> | null {
- if (
- !node.parentId ||
- getVisibleSiblingCount(ctx, visibleSiblingCount, node.parentId) !== 1 ||
- !node.componentId
- )
- return null
- const source = ctx.graph.getNode(node.componentId)
- const targetParent = ctx.graph.getNode(node.parentId)
- if (!source || !targetParent) return null
- const fitsTargetParent =
- source.x >= 0 &&
- source.y >= 0 &&
- source.x + source.width <= targetParent.width + 0.01 &&
- source.y + source.height <= targetParent.height + 0.01
- return fitsTargetParent ? { x: source.x, y: source.y } : null
-}
-
-function preserveTransformedPositionAfterResize(
- node: SceneNode,
- width: number,
- height: number
-): Pick<SceneNode, 'x' | 'y'> | null {
- if (node.rotation === 0 && !node.flipX && !node.flipY) return null
-
- // Figma's transform is anchored to the node's local coordinate system, while SceneNode
- // rotation/reflection is applied around its center. If derived symbol data changes only the
- // size, retaining x/y moves that center and therefore changes the effective transform. Keep
- // the existing matrix translation and solve x/y again for the new center instead.
- const matrix = getNodeLocalMatrix(node)
- const centerX = width / 2
- const centerY = height / 2
- return {
- x: matrix[2] - centerX + matrix[0] * centerX + matrix[1] * centerY,
- y: matrix[5] - centerY + matrix[3] * centerX + matrix[4] * centerY
- }
-}
-
-function buildDsdTextUpdates(
- d: DerivedSymbolOverride,
- blobs: Uint8Array[],
- target: SceneNode
-): Partial<SceneNode> {
- const updates: Partial<SceneNode> = {}
- if (d.fontSize !== undefined) updates.fontSize = d.fontSize
- if (d.lineHeight !== undefined) updates.lineHeight = convertLineHeight(d.lineHeight, d.fontSize)
- if (d.letterSpacing !== undefined)
- updates.letterSpacing = convertLetterSpacing(d.letterSpacing, d.fontSize)
- if (d.strokeWeight !== undefined && target.strokes.length > 0) {
- updates.strokes = target.strokes.map((stroke) => ({
- ...stroke,
- weight: d.strokeWeight as number
- }))
- }
- const derivedTextGlyphs = convertFigmaDerivedTextGlyphs(d.derivedTextData, blobs)
- if (derivedTextGlyphs.length > 0) updates.derivedTextGlyphs = derivedTextGlyphs
- return updates
-}
-
-export function buildDsdLayoutUpdates(
- ctx: OverrideContext,
- _visibleSiblingCount: Map<string, number>,
- d: DerivedSymbolOverride,
- target: SceneNode
-): { updates: Partial<SceneNode>; hasSize: boolean } {
- const updates: Partial<SceneNode> = buildDsdTextUpdates(d, ctx.blobs, target)
- const derivedLayout: NonNullable<SceneNode['derivedLayout']> = {}
-
- if (d.size) {
- updates.width = d.size.x
- updates.height = d.size.y
- derivedLayout.width = d.size.x
- derivedLayout.height = d.size.y
- }
- if (d.transform) {
- const transformed = convertFigmaTransformProps({
- transform: d.transform,
- size: d.size ?? { x: target.width, y: target.height }
- })
- updates.x = transformed.x
- updates.y = transformed.y
- updates.rotation = transformed.rotation
- updates.flipX = transformed.flipX
- updates.flipY = transformed.flipY
- derivedLayout.x = transformed.x
- derivedLayout.y = transformed.y
- } else if (d.size) {
- const position =
- preserveTransformedPositionAfterResize(target, d.size.x, d.size.y) ??
- resolveSizeOnlyPosition(ctx, _visibleSiblingCount, target)
- if (position) {
- updates.x = position.x
- updates.y = position.y
- derivedLayout.x = position.x
- derivedLayout.y = position.y
- }
- }
- if (Object.keys(derivedLayout).length > 0) updates.derivedLayout = derivedLayout
- Object.assign(updates, resolveDsdGeometry(d, target, ctx.blobs))
- return { updates, hasSize: d.size !== undefined }
-}
diff --git a/packages/fig/src/instance-overrides/derived-symbol-data/propagate.ts b/packages/fig/src/instance-overrides/derived-symbol-data/propagate.ts
deleted file mode 100644
index 00e908fd2..000000000
--- a/packages/fig/src/instance-overrides/derived-symbol-data/propagate.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
-import { copyGeometryPaths } from '@open-pencil/scene-graph/copy'
-
-import { buildClonesMap } from '../sync'
-import type { OverrideContext } from '../types'
-import { overrideCandidates } from '../utils'
-
-function buildSizeOverriddenCloneUpdates(source: SceneNode, clone: SceneNode): Partial<SceneNode> {
- if (clone.type !== 'INSTANCE' || !source.derivedLayout) return {}
- const sourceLayout = source.derivedLayout
- const updates: Partial<SceneNode> = {
- derivedLayout: {
- ...sourceLayout,
- ...clone.derivedLayout,
- x: sourceLayout.x ?? clone.derivedLayout?.x,
- y: sourceLayout.y ?? clone.derivedLayout?.y
- }
- }
- if (sourceLayout.x !== undefined) updates.x = sourceLayout.x
- if (sourceLayout.y !== undefined) updates.y = sourceLayout.y
- return updates
-}
-
-function buildCloneUpdates(
- ctx: OverrideContext,
- source: SceneNode,
- clone: SceneNode,
- cloneId: string,
- sizeSet: Set<string>
-): Partial<SceneNode> {
- const updates: Partial<SceneNode> = {}
- if (sizeSet.has(cloneId)) return buildSizeOverriddenCloneUpdates(source, clone)
- if (source.width !== clone.width) updates.width = source.width
- if (source.height !== clone.height) updates.height = source.height
- if (source.x !== clone.x) updates.x = source.x
- if (source.y !== clone.y) updates.y = source.y
- if (!ctx.geometryOverrideNodes.has(cloneId)) {
- if (source.fillGeometry !== clone.fillGeometry)
- updates.fillGeometry = copyGeometryPaths(source.fillGeometry)
- if (source.strokeGeometry !== clone.strokeGeometry)
- updates.strokeGeometry = copyGeometryPaths(source.strokeGeometry)
- }
- if (source.text === clone.text && source.derivedTextGlyphs) {
- updates.derivedTextGlyphs = structuredClone(source.derivedTextGlyphs)
- }
- if (source.text === clone.text && source.derivedLayout) {
- updates.derivedLayout = { ...source.derivedLayout }
- }
- return updates
-}
-
-export function reconcileEffectiveCloneGeometry(
- ctx: OverrideContext,
- scaledInstanceIds: Set<string>
-): void {
- restoreScaledInstanceLeafBounds(ctx, scaledInstanceIds)
- restoreThinCloneCrossPositions(ctx)
-}
-
-function restoreScaledInstanceLeafBounds(
- ctx: OverrideContext,
- scaledInstanceIds: Set<string>
-): void {
- for (const instanceId of scaledInstanceIds) {
- const instance = ctx.graph.getNode(instanceId)
- if (instance?.layoutMode !== 'NONE' || instance.childIds.length !== 1) continue
- const child = ctx.graph.getNode(instance.childIds[0])
- if (
- !child ||
- child.childIds.length > 0 ||
- child.horizontalConstraint !== 'SCALE' ||
- child.verticalConstraint !== 'SCALE'
- ) {
- continue
- }
- const width = child.derivedLayout?.width
- const height = child.derivedLayout?.height
- const restoresDerivedBounds = width !== undefined && height !== undefined
- const restoresImageBounds =
- !restoresDerivedBounds &&
- child.type === 'ROUNDED_RECTANGLE' &&
- child.fills.some((fill) => fill.type === 'IMAGE')
- if (!restoresDerivedBounds && !restoresImageBounds) continue
- const restoredWidth = width ?? instance.width
- const restoredHeight = height ?? instance.height
- if (child.width === restoredWidth && child.height === restoredHeight) continue
- ctx.graph.updateNode(child.id, { width: restoredWidth, height: restoredHeight })
- }
-}
-
-function isThinCenteredCrossChild(parent: SceneNode, clone: SceneNode): boolean {
- if (parent.counterAxisAlign !== 'CENTER') return false
- if (parent.layoutMode === 'HORIZONTAL') return clone.height <= 1 && clone.width > clone.height
- if (parent.layoutMode === 'VERTICAL') return clone.width <= 1 && clone.height > clone.width
- return false
-}
-
-interface ThinCloneCrossPosition {
- axis: 'x' | 'y'
- position: number
-}
-
-function thinCloneCrossPosition(
- graph: OverrideContext['graph'],
- clone: SceneNode
-): ThinCloneCrossPosition | null {
- if (
- clone.source.format !== null ||
- !clone.componentId ||
- !clone.name.endsWith('Divider') ||
- !clone.parentId ||
- clone.derivedLayout?.x !== undefined ||
- clone.derivedLayout?.y !== undefined
- ) {
- return null
- }
- const parent = graph.getNode(clone.parentId)
- const source = graph.getNode(clone.componentId)
- const sourceLayout = source?.derivedLayout
- if (!parent || !source || sourceLayout?.x === undefined || sourceLayout.y === undefined)
- return null
- if (clone.width !== source.width || clone.height !== source.height) return null
- if (!isThinCenteredCrossChild(parent, clone)) return null
- return parent.layoutMode === 'HORIZONTAL'
- ? { axis: 'y', position: sourceLayout.y }
- : { axis: 'x', position: sourceLayout.x }
-}
-
-function restoreThinCloneCrossPositions(ctx: OverrideContext): void {
- for (const clone of overrideCandidates(ctx.graph, ctx.activeNodeIds)) {
- const crossPosition = thinCloneCrossPosition(ctx.graph, clone)
- if (!crossPosition) continue
- ctx.graph.updateNode(clone.id, {
- derivedLayout: {
- ...clone.derivedLayout,
- [crossPosition.axis]: crossPosition.position
- }
- })
- }
-}
-
-export function applyGeneratedFreeformStretch(ctx: OverrideContext): void {
- for (const node of overrideCandidates(ctx.graph, ctx.activeNodeIds)) {
- if (
- node.source.format === 'fig' ||
- !node.derivedLayout ||
- !node.parentId ||
- node.layoutPositioning === 'ABSOLUTE'
- ) {
- continue
- }
- const parent = ctx.graph.getNode(node.parentId)
- if (
- !parent ||
- parent.source.format === 'fig' ||
- parent.layoutMode !== 'NONE' ||
- !parent.derivedLayout
- ) {
- continue
- }
- const updates: Partial<SceneNode> = {}
- if (
- node.horizontalConstraint === 'STRETCH' &&
- node.derivedLayout.width !== undefined &&
- node.derivedLayout.width === parent.derivedLayout.width
- ) {
- updates.width = node.derivedLayout.width
- }
- if (
- node.verticalConstraint === 'STRETCH' &&
- node.derivedLayout.height !== undefined &&
- node.derivedLayout.height === parent.derivedLayout.height
- ) {
- updates.height = node.derivedLayout.height
- }
- if (Object.keys(updates).length > 0) ctx.graph.updateNode(node.id, updates)
- }
-}
-
-export function propagateDsdChanges(
- ctx: OverrideContext,
- modified: Set<string>,
- sizeSet: Set<string>
-): void {
- if (modified.size === 0) return
-
- const clonesOf = buildClonesMap(ctx.graph, ctx.activeNodeIds)
- const queue = [...modified]
- const visited = new Set<string>()
-
- let index = 0
- while (index < queue.length) {
- const sourceId = queue[index]
- index++
- const source = ctx.graph.getNode(sourceId)
- if (!source) continue
- const clones = clonesOf.get(sourceId)
- if (!clones) continue
- for (const cloneId of clones) {
- if (visited.has(cloneId)) continue
- visited.add(cloneId)
- const clone = ctx.graph.getNode(cloneId)
- if (!clone) continue
- const updates = buildCloneUpdates(ctx, source, clone, cloneId, sizeSet)
- if (Object.keys(updates).length > 0) {
- ctx.graph.preserveSourceMetadataDuring(() => ctx.graph.updateNode(cloneId, updates))
- }
- queue.push(cloneId)
- }
- }
-}
diff --git a/packages/fig/src/instance-overrides/fields.ts b/packages/fig/src/instance-overrides/fields.ts
new file mode 100644
index 000000000..f01092314
--- /dev/null
+++ b/packages/fig/src/instance-overrides/fields.ts
@@ -0,0 +1,74 @@
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+/**
+ * How a claim on a raw Kiwi field maps onto SceneGraph. Materialization records the
+ * mapped scene fields as overridden, uniform scale multiplies `length` values, and
+ * export serializes each `kind` back into the raw field.
+ */
+export interface OverrideField {
+ readonly scene: readonly (keyof SceneNode)[]
+ readonly kind:
+ | 'scalar'
+ | 'visible'
+ | 'text'
+ | 'text-style'
+ | 'paint'
+ | 'size'
+ | 'layout-distance'
+ | 'layout-mode'
+ /** A placed-space distance that an instance's uniform scale multiplies. */
+ readonly length?: true
+}
+
+/** Raw override fields an instance owner may claim, keyed by their Kiwi name. */
+export const OVERRIDE_FIELDS = {
+ name: { scene: ['name'], kind: 'scalar' },
+ opacity: { scene: ['opacity'], kind: 'scalar' },
+ fontSize: { scene: ['fontSize'], kind: 'scalar', length: true },
+ visible: { scene: ['visible'], kind: 'visible' },
+ textData: { scene: ['text'], kind: 'text' },
+ styleIdForText: { scene: ['textStyleId'], kind: 'text-style' },
+ fillPaints: { scene: ['fills'], kind: 'paint' },
+ strokePaints: { scene: ['strokes'], kind: 'paint' },
+ size: { scene: ['width', 'height'], kind: 'size', length: true },
+ stackSpacing: { scene: ['itemSpacing'], kind: 'layout-distance', length: true },
+ stackCounterSpacing: { scene: ['counterAxisSpacing'], kind: 'layout-distance', length: true },
+ stackHorizontalPadding: { scene: ['paddingLeft'], kind: 'layout-distance', length: true },
+ stackVerticalPadding: { scene: ['paddingTop'], kind: 'layout-distance', length: true },
+ stackPaddingRight: { scene: ['paddingRight'], kind: 'layout-distance', length: true },
+ stackPaddingBottom: { scene: ['paddingBottom'], kind: 'layout-distance', length: true },
+ textAutoResize: { scene: ['textAutoResize'], kind: 'layout-mode' },
+ stackChildPrimaryGrow: { scene: ['layoutGrow'], kind: 'layout-mode' },
+ stackPrimarySizing: { scene: ['primaryAxisSizing'], kind: 'layout-mode' },
+ stackCounterSizing: { scene: ['counterAxisSizing'], kind: 'layout-mode' },
+ stackChildAlignSelf: { scene: ['layoutAlignSelf'], kind: 'layout-mode' }
+} as const satisfies Record<string, OverrideField>
+
+export type RawOverrideField = keyof typeof OVERRIDE_FIELDS
+
+type RawFieldOfKind<K extends OverrideField['kind']> = {
+ [R in RawOverrideField]: (typeof OVERRIDE_FIELDS)[R]['kind'] extends K ? R : never
+}[RawOverrideField]
+
+const entries = Object.entries(OVERRIDE_FIELDS) as [RawOverrideField, OverrideField][]
+
+/** Scene fields that carry an instance override, with the raw field each serializes to. */
+export const SCENE_OVERRIDE_FIELDS: ReadonlyMap<
+ keyof SceneNode,
+ { raw: RawOverrideField; field: OverrideField }
+> = new Map(
+ entries.flatMap(([raw, field]) => field.scene.map((scene) => [scene, { raw, field }] as const))
+)
+
+function rawFieldsOfKind<K extends OverrideField['kind']>(kind: K): RawFieldOfKind<K>[] {
+ return entries.flatMap(([raw, field]) => (field.kind === kind ? [raw as RawFieldOfKind<K>] : []))
+}
+
+/** Scalars share one name on both sides and serialize verbatim. */
+export const SCALAR_OVERRIDE_FIELDS: readonly RawFieldOfKind<'scalar'>[] = rawFieldsOfKind('scalar')
+
+/** Layout distances by scene field, mapped to the raw field uniform scale treats as a length. */
+export const LAYOUT_DISTANCE_FIELDS: Readonly<Record<string, RawFieldOfKind<'layout-distance'>>> =
+ Object.fromEntries(
+ rawFieldsOfKind('layout-distance').map((raw) => [OVERRIDE_FIELDS[raw].scene[0], raw])
+ )
diff --git a/packages/fig/src/instance-overrides/index.ts b/packages/fig/src/instance-overrides/index.ts
index 1ec27da79..15b1ae179 100644
--- a/packages/fig/src/instance-overrides/index.ts
+++ b/packages/fig/src/instance-overrides/index.ts
@@ -1,10 +1,16 @@
-export { buildDsdLayoutUpdates } from './derived-symbol-data/layout'
-export { applyGeneratedFreeformStretch, propagateDsdChanges } from './derived-symbol-data/propagate'
-export { protectField, type ProtectionMap } from './patches'
-export { syncChildrenDeep, syncNodeProps } from './sync'
+// Occurrence-scoped interpreter used by production FIG import.
+export { interpretInstance, interpretComponent } from './interpret'
+export type {
+ InstanceOccurrence,
+ InterpretInstanceOptions,
+ InstancePathDiagnostic
+} from './interpret'
+export { materializeInstance } from './materialize-instance'
+export { materializeComponentClosure } from './component-closure'
+export { linkInstanceSourceChildren, mapInstanceSourceChildren } from './source-children'
+export type { MaterializedInstance } from './materialize-instance'
+
export type {
- InstanceNodeChange,
- OverrideContext,
ComponentPropAssignment,
ComponentPropDef,
ComponentPropRef,
@@ -13,387 +19,3 @@ export type {
SymbolData,
SymbolOverride
} from './types'
-
-import { isEqual } from 'es-toolkit/predicate'
-
-import { guidToString, resolvedNumericBindingUpdate } from '@open-pencil/fig/node-change'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { hasInstanceOverride } from '@open-pencil/scene-graph'
-import {
- copyFills,
- copyStyleRuns,
- hasSameCopySource,
- markCopySource
-} from '@open-pencil/scene-graph/copy'
-import type { JSONObject } from '@open-pencil/scene-graph/primitives'
-
-import { applyComponentProperties } from './component-props'
-import { applyConstraintScaling } from './constraints'
-import { applyDerivedSymbolData } from './derived-symbol-data'
-import {
- applyGeneratedFreeformStretch,
- reconcileEffectiveCloneGeometry
-} from './derived-symbol-data/propagate'
-import { populateInstances } from './populate'
-import { preComputeRoots } from './resolve'
-import { applySymbolOverrides } from './symbol/overrides'
-import { propagateNodePropsTransitively, propagateOverridesTransitively } from './sync'
-import { indexCloneNodes } from './sync/sources'
-import type { InstanceNodeChange, OverrideContext, ComponentPropValue } from './types'
-import { overrideCandidates } from './utils'
-
-/**
- * Identify nodes whose kiwi NC has explicit property values that DIFFER
- * from their component source. Only these need protection from sync.
- */
-function* changedNodeEntries(
- changeMap: Map<string, InstanceNodeChange>,
- guidToNodeId: Map<string, string>
-): Generator<[string, InstanceNodeChange]> {
- for (const [figmaId, nodeId] of guidToNodeId) {
- const nc = changeMap.get(figmaId)
- if (nc) yield [nodeId, nc]
- }
-}
-
-function buildKiwiPropertyNodes(
- graph: SceneGraph,
- changeMap: Map<string, InstanceNodeChange>,
- guidToNodeId: Map<string, string>
-): Set<string> {
- const result = new Set<string>()
- for (const [nodeId, change] of changedNodeEntries(changeMap, guidToNodeId)) {
- const nc = change as JSONObject
- const node = graph.getNode(nodeId)
- if (!node?.componentId) continue
- const comp = graph.getNode(node.componentId)
- if (!comp) continue
- const hasDiffRadius =
- (nc.cornerRadius !== undefined || nc.rectangleCornerRadiiIndependent !== undefined) &&
- node.cornerRadius !== comp.cornerRadius
- const hasDiffVisible = nc.visible === false && comp.visible
- const hasDiffFills = nc.fillPaints !== undefined && !isEqual(node.fills, comp.fills)
- const hasDiffStrokes = nc.strokePaints !== undefined && !isEqual(node.strokes, comp.strokes)
- const hasDiffText =
- nc.textData !== undefined &&
- node.type === 'TEXT' &&
- comp.type === 'TEXT' &&
- node.text !== comp.text
- if (hasDiffRadius || hasDiffVisible || hasDiffFills || hasDiffStrokes || hasDiffText) {
- result.add(nodeId)
- }
- }
- return result
-}
-
-function buildKiwiGeometryNodes(
- changeMap: Map<string, InstanceNodeChange>,
- guidToNodeId: Map<string, string>
-): Set<string> {
- const result = new Set<string>()
- for (const [nodeId, nc] of changedNodeEntries(changeMap, guidToNodeId)) {
- if (nc.fillGeometry?.length || nc.strokeGeometry?.length) result.add(nodeId)
- }
- return result
-}
-
-function componentLinkedNodes(graph: SceneGraph): SceneNode[] {
- const nodes: SceneNode[] = []
- for (const node of graph.getAllNodes()) if (node.componentId) nodes.push(node)
- return nodes
-}
-
-function instancePlacementPairs(
- graph: SceneGraph
-): Array<{ sourceChildId: string; childId: string }> {
- const pairs: Array<{ sourceChildId: string; childId: string }> = []
- for (const node of graph.getAllNodes()) {
- if (node.type !== 'INSTANCE' || !node.componentId) continue
- const source = graph.getNode(node.componentId)
- if (!source || source.childIds.length !== node.childIds.length) continue
- for (let index = 0; index < node.childIds.length; index++) {
- pairs.push({ sourceChildId: source.childIds[index], childId: node.childIds[index] })
- }
- }
- return pairs
-}
-
-function propagateResolvedFills(
- graph: SceneGraph,
- protectedNodes: Set<string>,
- candidates = componentLinkedNodes(graph)
-): void {
- for (let pass = 0; pass < 10; pass++) {
- let changed = false
- for (const node of candidates) {
- if (!node.componentId) continue
- const source = graph.getNode(node.componentId)
- if (!source || isEqual(source.fills, node.fills)) continue
- if (protectedNodes.has(node.id) && !protectedNodes.has(source.id)) continue
- if (hasInstanceOverride(graph, node.id, 'fills')) continue
- graph.updateNode(node.id, { fills: copyFills(source.fills) })
- changed = true
- }
- if (!changed) return
- }
-}
-
-function propagateResolvedChildPlacementClones(
- graph: SceneGraph,
- pairs = instancePlacementPairs(graph)
-): void {
- for (let pass = 0; pass < 10; pass++) {
- let changed = false
- for (const pair of pairs) {
- const sourceChild = graph.getNode(pair.sourceChildId)
- const child = graph.getNode(pair.childId)
- if (!sourceChild || !child) continue
- if (
- sourceChild.overrideKey &&
- child.overrideKey &&
- sourceChild.overrideKey !== child.overrideKey
- ) {
- continue
- }
- const updates: Partial<SceneNode> = {}
- if (!sourceChild.visible && child.visible) updates.visible = false
- if (sourceChild.x !== child.x) updates.x = sourceChild.x
- if (sourceChild.y !== child.y) updates.y = sourceChild.y
- if (Object.keys(updates).length === 0) continue
- graph.updateNode(child.id, updates)
- changed = true
- }
- if (!changed) return
- }
-}
-
-function sameDerivedGlyphSource(
- source: SceneNode['derivedTextGlyphs'],
- target: SceneNode['derivedTextGlyphs']
-): boolean {
- if (source === target) return true
- if (!source || !target) return false
- return hasSameCopySource(source, target)
-}
-
-function propagateResolvedTextClones(graph: SceneGraph, activeNodeIds?: Set<string>): void {
- const ordered: SceneNode[] = []
- const visited = new Set<string>()
- const visiting = new Set<string>()
- const visit = (node: SceneNode) => {
- if (visited.has(node.id) || visiting.has(node.id)) return
- visiting.add(node.id)
- const source = node.componentId ? graph.getNode(node.componentId) : undefined
- if (source?.type === 'TEXT') visit(source)
- visiting.delete(node.id)
- visited.add(node.id)
- if (node.type === 'TEXT' && node.componentId) ordered.push(node)
- }
- for (const nodeId of activeNodeIds ?? graph.nodes.keys()) {
- const node = graph.getNode(nodeId)
- if (node?.type === 'TEXT' && node.componentId) visit(node)
- }
-
- for (const node of ordered) {
- const source = node.componentId ? graph.getNode(node.componentId) : undefined
- if (source?.type !== 'TEXT' || source.text !== node.text) continue
- if (
- source.width === node.width &&
- source.height === node.height &&
- isEqual(source.fills, node.fills) &&
- isEqual(source.styleRuns, node.styleRuns) &&
- sameDerivedGlyphSource(source.derivedTextGlyphs, node.derivedTextGlyphs)
- ) {
- continue
- }
- graph.updateNode(node.id, {
- width: source.width,
- height: source.height,
- fills: copyFills(source.fills),
- styleRuns: copyStyleRuns(source.styleRuns),
- derivedTextGlyphs: source.derivedTextGlyphs
- ? markCopySource(source.derivedTextGlyphs, structuredClone(source.derivedTextGlyphs))
- : undefined
- })
- }
-}
-
-function buildOverrideContext(
- graph: SceneGraph,
- changeMap: Map<string, InstanceNodeChange>,
- guidToNodeId: Map<string, string>,
- blobs: Uint8Array[],
- activeNodeIds?: Set<string>
-): OverrideContext {
- const overrideKeyToGuid = new Map<string, string>()
- const assetRefToGuid = new Map<string, string>()
- for (const [id, nc] of changeMap) {
- if (nc.overrideKey) overrideKeyToGuid.set(guidToString(nc.overrideKey), id)
- if (typeof nc.key !== 'string') continue
- assetRefToGuid.set(nc.key, id)
- if (typeof nc.version === 'string') assetRefToGuid.set(`${nc.key}@${nc.version}`, id)
- }
-
- const propDefaults = new Map<string, ComponentPropValue>()
- const propNames = new Map<string, string>()
- for (const [, nc] of changeMap) {
- if (!nc.componentPropDefs?.length) continue
- for (const def of nc.componentPropDefs) {
- if (!def.id) continue
- const id = guidToString(def.id)
- if (def.initialValue) propDefaults.set(id, def.initialValue)
- if (def.name) propNames.set(id, def.name)
- }
- }
-
- const nodeIdToGuid = new Map<string, string>()
- for (const [figmaId, nodeId] of guidToNodeId) {
- nodeIdToGuid.set(nodeId, figmaId)
- }
-
- const kiwiPropertyNodes = buildKiwiPropertyNodes(graph, changeMap, guidToNodeId)
- const geometryOverrideNodes = buildKiwiGeometryNodes(changeMap, guidToNodeId)
-
- return {
- graph,
- changeMap,
- guidToNodeId,
- blobs,
- overrideKeyToGuid,
- assetRefToGuid,
- nodeIdToGuid,
- propDefaults,
- propNames,
- preComputedRoot: new Map(),
- preComputedClones: new Map(),
- componentIdRoot: new Map(),
- swappedInstances: new Set(),
- protectedFields: new Map(),
- kiwiPropertyNodes,
- geometryOverrideNodes,
- activeNodeIds
- }
-}
-
-function applyResolvedNumericBindings(graph: SceneGraph, activeNodeIds?: Set<string>): void {
- for (const node of overrideCandidates(graph, activeNodeIds)) {
- const updates: Partial<SceneNode> = {}
- for (const [field, variableId] of Object.entries(node.boundVariables)) {
- if (Array.isArray(variableId)) continue
- const value = graph.resolveNumberVariableForNode(node.id, variableId)
- if (value === undefined) continue
- Object.assign(updates, resolvedNumericBindingUpdate(field, value))
- }
- if (Object.keys(updates).length > 0) graph.updateNode(node.id, updates)
- }
-}
-
-/**
- *
- * Shared between .fig file import and clipboard paste. Both paths produce
- * a SceneGraph with INSTANCE nodes whose componentId references have been
- * remapped to graph node IDs but whose children may be missing and whose
- * overrides have not yet been applied.
- *
- * Resolution order:
- * 1. Populate — clone component trees into empty instances
- * 2. Symbol overrides — set property values and swap instances
- * 3. Transitive sync — propagate overrides through clone chains
- * 4. Component properties — toggle visibility / swap via prop assignments
- * 5. Second transitive sync — propagate property changes to deeper clones
- * 6. Derived symbol data — apply Figma's pre-computed sizes last
- */
-export function populateAndApplyOverrides(
- graph: SceneGraph,
- changeMap: Map<string, InstanceNodeChange>,
- guidToNodeId: Map<string, string>,
- blobs: Uint8Array[] = [],
- activeRootIds?: Iterable<string>
-): void {
- const activeNodeIds = populateInstances(graph, activeRootIds)
-
- const ctx = buildOverrideContext(graph, changeMap, guidToNodeId, blobs, activeNodeIds)
- preComputeRoots(ctx)
-
- const overriddenNodes = applySymbolOverrides(ctx)
-
- // Nodes with explicit kiwi NC properties are seeds (so their clones get
- // synced with the correct values) AND protected (so sync doesn't overwrite
- // them with component defaults).
- for (const id of ctx.kiwiPropertyNodes) overriddenNodes.add(id)
- propagateOverridesTransitively(
- graph,
- overriddenNodes,
- ctx.swappedInstances,
- ctx.componentIdRoot,
- undefined,
- ctx.activeNodeIds,
- ctx.protectedFields
- )
-
- const propModified = applyComponentProperties(ctx)
- if (propModified.size > 0) {
- propagateOverridesTransitively(
- graph,
- propModified,
- ctx.swappedInstances,
- ctx.componentIdRoot,
- overriddenNodes,
- ctx.activeNodeIds,
- ctx.protectedFields
- )
- }
-
- if (activeRootIds) {
- const populated = populateInstances(graph, activeRootIds)
- if (populated) {
- ctx.activeNodeIds = populated
- indexCloneNodes(graph, populated, ctx.preComputedClones)
- }
- const latePropModified = applyComponentProperties(ctx)
- const lateSeeds = new Set([...overriddenNodes, ...propModified, ...latePropModified])
- if (lateSeeds.size > 0) {
- propagateOverridesTransitively(
- graph,
- lateSeeds,
- ctx.swappedInstances,
- ctx.componentIdRoot,
- overriddenNodes,
- ctx.activeNodeIds,
- ctx.protectedFields
- )
- }
- propagateResolvedChildPlacementClones(graph)
- }
-
- applyDerivedSymbolData(ctx)
- propagateResolvedFills(graph, new Set([...ctx.kiwiPropertyNodes, ...overriddenNodes]))
- propagateResolvedTextClones(graph, ctx.activeNodeIds)
- applyConstraintScaling(ctx)
- const scaledInstances = new Set<string>()
- for (const node of overrideCandidates(graph, ctx.activeNodeIds)) {
- if (node.type !== 'INSTANCE' || !node.componentId) continue
- const component = graph.getNode(node.componentId)
- if (component && (node.width !== component.width || node.height !== component.height)) {
- scaledInstances.add(node.id)
- }
- }
- applyComponentProperties(ctx)
-
- // Final component-property swaps can replace descendants targeted by earlier
- // symbol overrides. Replay property-only overrides against the final clone
- // tree, then propagate those final targets without performing swaps again.
- const replayedOverrides = applySymbolOverrides(ctx, true)
- propagateNodePropsTransitively(
- graph,
- replayedOverrides,
- ctx.activeNodeIds,
- ctx.protectedFields,
- ctx.preComputedClones
- )
- // Final swaps recreate descendants from component defaults. Reconcile only
- // geometry that already had an authoritative effective size or cross-axis position.
- reconcileEffectiveCloneGeometry(ctx, scaledInstances)
- applyResolvedNumericBindings(graph, ctx.activeNodeIds)
- applyGeneratedFreeformStretch(ctx)
-}
diff --git a/packages/fig/src/instance-overrides/interpret.ts b/packages/fig/src/instance-overrides/interpret.ts
new file mode 100644
index 000000000..a7cf31e01
--- /dev/null
+++ b/packages/fig/src/instance-overrides/interpret.ts
@@ -0,0 +1,592 @@
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+import type { Vector } from '@open-pencil/scene-graph'
+
+import { cloneRecord } from '../node-change/clone'
+import { mergeVariableConsumptionMaps } from '../node-change/variable-bindings'
+import {
+ bindSourceProperties,
+ componentBindings,
+ instanceBindings,
+ type BoundPropertyClaim,
+ type PropertyBinding
+} from './bindings/properties'
+import {
+ declareVariableBindingUnits,
+ declareSourceVariableBindingUnits
+} from './bindings/variables'
+import { applyDerivedEntry } from './derived-symbol-data'
+import {
+ ownLayers,
+ type AssignmentGroup,
+ type Owner,
+ type PropertyLayer,
+ type StructuralLayer
+} from './layers'
+import {
+ findSegment,
+ isRootGuid,
+ pathError,
+ resolveOccurrencePath,
+ SegmentError
+} from './occurrence-path'
+import { applyPlacedConstraints } from './resize'
+import { applyInstanceLayoutScale } from './scale/layout'
+import {
+ createSourceIndex,
+ findStaticSegment,
+ readOverrideKey,
+ recordMatches,
+ resolvesInSourceComponent,
+ sameGuid,
+ terminalComponent,
+ type SourceIndex
+} from './source-index'
+import { invalidateInheritedTextData } from './text-provenance'
+import type { ComponentPropAssignment, DerivedSymbolOverride } from './types'
+
+/**
+ * Figma's instance model reduces to three things: an instance expands its component's
+ * subtree; owners contribute layers, each a partial record at a path relative to that
+ * owner; and the outermost owner wins where layers overlap. A swap and a property
+ * assignment are structural layers, everything else is a property layer.
+ *
+ * Structural layers are routed down to the instance they configure before it expands,
+ * so every occurrence expands exactly once with its effective component and complete
+ * assignment list. Property layers are applied by their declaring owner onto the built
+ * subtree, so their values stay in that owner's coordinate space; outer owners apply
+ * after inner ones by construction. Saved derived data is a cache, applied last.
+ */
+
+/** An explicit claim keeps the complete path relative to its owning occurrence. */
+export interface InstancePropertyClaim {
+ /** Source record declaring the claim; preserved when inherited by another occurrence. */
+ declaredBy: string
+ path: readonly GUID[]
+ properties: Record<string, unknown>
+}
+
+/** One occurrence, not a shared source node or a SceneGraph editing clone. */
+export interface InstanceOccurrence {
+ readonly sourceId: string
+ readonly overrideKey: GUID | undefined
+ mainComponentId: string | null
+ mainComponentOverrideKey?: GUID
+ sourceComponentOverrideKey?: GUID
+ sourceComponentId?: GUID
+ properties: NodeChange
+ children: InstanceOccurrence[]
+ /** Explicit property records declared by this occurrence's source. */
+ propertyClaims: InstancePropertyClaim[]
+ bindingClaims: BoundPropertyClaim[]
+ derivedSize?: Vector
+ /** Cumulative scale for unresolved layout-distance variable values. */
+ layoutScale?: number
+ /** Per-field declaration-space multipliers, composed as owners expand. */
+ variableBindingScales?: Record<string, number>
+ /** Whether this expansion supplies a name rather than only inheriting it. */
+ hasOwnName: boolean
+ defaultInstanceName?: string
+}
+
+export interface InstancePathDiagnostic {
+ ownerId: string
+ mainComponentId?: string | null
+ path: readonly GUID[]
+ reason: 'missing-target' | 'ambiguous-target'
+}
+
+export interface InstanceAssignmentDiagnostic extends InstancePathDiagnostic {
+ assignments: readonly ComponentPropAssignment[]
+}
+
+/** An instance whose main component the archive no longer contains. */
+export interface MissingComponentDiagnostic {
+ ownerId: string
+ componentId: string
+}
+
+export { resolveOccurrencePath } from './occurrence-path'
+
+export interface InterpretInstanceOptions {
+ /** Apply explicitly saved effective bounds, geometry and typography; no inferred scaling or layout. */
+ derivedBounds?: boolean
+ /** Unresolved property overrides are skipped only when a diagnostic receiver is supplied. */
+ onUnresolvedProperty?: (diagnostic: InstancePathDiagnostic) => void
+ /** Explicit partial evaluation: report and skip missing assignment targets. Swaps remain fatal. */
+ onUnresolvedAssignment?: (diagnostic: InstanceAssignmentDiagnostic) => void
+ /**
+ * Keep an instance of a deleted component as a childless instance that retains its
+ * saved reference, the way Figma does, instead of rejecting the document.
+ */
+ onMissingComponent?: (diagnostic: MissingComponentDiagnostic) => void
+}
+
+export function interpretInstance(
+ changes: readonly NodeChange[],
+ instanceId: string,
+ options: InterpretInstanceOptions = {}
+): InstanceOccurrence {
+ return createOccurrenceInterpreter(changes).instance(instanceId, options)
+}
+
+export function interpretComponent(
+ changes: readonly NodeChange[],
+ componentId: string,
+ options: InterpretInstanceOptions = {}
+): InstanceOccurrence {
+ return createOccurrenceInterpreter(changes).component(componentId, options)
+}
+
+/** One source index per document; evaluation state remains local to each call. */
+export function createOccurrenceInterpreter(changes: readonly NodeChange[]) {
+ const index = createSourceIndex(changes)
+ return {
+ instance: (id: string, options: InterpretInstanceOptions = {}) =>
+ interpretRoot(index, id, 'INSTANCE', options),
+ component: (id: string, options: InterpretInstanceOptions = {}) =>
+ interpretRoot(index, id, 'SYMBOL', options),
+ page: (id: string, options: InterpretInstanceOptions = {}) =>
+ interpretRoot(index, id, 'CANVAS', options)
+ }
+}
+
+function interpretRoot(
+ index: SourceIndex,
+ rootId: string,
+ expectedType: 'INSTANCE' | 'SYMBOL' | 'CANVAS',
+ options: InterpretInstanceOptions
+): InstanceOccurrence {
+ const { sources, children } = index
+ const expanding = new Set<string>()
+ /** Fields set by an owner's assignment, by the rank of that owner. */
+ const assignedFields = new WeakMap<InstanceOccurrence, Map<string, number>>()
+ /** Components an occurrence expanded before an outer decision replaced them. */
+ const replacedComponents = new WeakMap<InstanceOccurrence, readonly GUID[]>()
+
+ const defaultInstanceName = (occurrence: InstanceOccurrence): string | undefined => {
+ const source = sources.get(occurrence.sourceId)
+ if (source?.type === 'INSTANCE') return occurrence.properties.name
+ const parentGuid = source?.parentIndex?.guid
+ const parent = parentGuid ? sources.get(guidToString(parentGuid)) : undefined
+ return parent?.isStateGroup === true ? parent.name : occurrence.properties.name
+ }
+
+ /** A component and its override key both address the root of an instance's expansion. */
+ const componentKeys = (guid: GUID | undefined): GUID[] => {
+ if (!guid) return []
+ const key = readOverrideKey(sources.get(guidToString(guid))?.overrideKey)
+ return key ? [guid, key] : [guid]
+ }
+
+ /** A layer written against a component that an outer decision replaced is stale, not wrong. */
+ const isStaleLayer = ({ boundary }: StructuralLayer): boolean =>
+ boundary?.replaced.some((component) =>
+ resolvesInSourceComponent(index, component, boundary.path)
+ ) ?? false
+
+ /**
+ * An address that resolves to nothing is a record Figma kept after deleting the node it
+ * named, and a swap is no different: its replacement can be present while the layer it
+ * replaced is gone. An ambiguous address means the path is wrong, which stays fatal.
+ */
+ const unresolvedStructural = (layer: StructuralLayer, cause: SegmentError): void => {
+ if (cause.count === 0 && isStaleLayer(layer)) return
+ const error = pathError(layer.owner.id, layer.owner.mainComponentId, layer.declaredPath, cause)
+ if (cause.count !== 0 || !options.onUnresolvedAssignment) throw error
+ layer.owner.unresolved.push({
+ ...error.diagnostic,
+ assignments: structuredClone(layer.assignments)
+ })
+ }
+
+ /** Dispatch structural layers to the direct child whose static subtree holds their first segment. */
+ const routeToChildren = (
+ id: string,
+ layers: readonly StructuralLayer[]
+ ): Map<string, StructuralLayer[]> => {
+ const routed = new Map<string, StructuralLayer[]>()
+ for (const layer of layers) {
+ const [segment] = layer.path
+ const { count, topChild } = findStaticSegment(index, id, segment)
+ if (!topChild?.guid) {
+ unresolvedStructural(layer, new SegmentError(count, segment))
+ continue
+ }
+ const childId = guidToString(topChild.guid)
+ const direct = recordMatches(topChild, segment)
+ const next = { ...layer, path: direct ? layer.path.slice(1) : layer.path }
+ const bucket = routed.get(childId)
+ if (bucket) bucket.push(next)
+ else routed.set(childId, [next])
+ }
+ return routed
+ }
+
+ interface RootResolution {
+ effective: GUID | undefined
+ /** Components superseded on the way to `effective`, innermost decision first. */
+ replaced: GUID[]
+ groups: AssignmentGroup[]
+ descendant: StructuralLayer[]
+ }
+
+ /** Components an occurrence would have expanded before outer bindings replaced them. */
+ const bindingHistory = (
+ raw: NodeChange,
+ effective: GUID | undefined,
+ superseded: readonly GUID[]
+ ): GUID[] => {
+ const original = raw.symbolData?.symbolID
+ if (!effective) return []
+ return [...(original ? [original] : []), ...superseded].filter(
+ (component) => !sameGuid(component, effective)
+ )
+ }
+
+ /**
+ * Root layers select the effective component and the complete assignment list, in
+ * inner-to-outer order so later entries win. Everything else addresses a descendant.
+ */
+ const resolveRoot = (
+ raw: NodeChange,
+ source: NodeChange,
+ superseded: readonly GUID[],
+ structural: readonly StructuralLayer[],
+ rank: number
+ ): RootResolution => {
+ let effective = source.symbolData?.symbolID
+ const replaced = bindingHistory(raw, effective, superseded)
+ const keys = [...componentKeys(raw.symbolData?.symbolID), ...componentKeys(effective)]
+ const isKey = (guid: GUID): boolean => keys.some((key) => sameGuid(key, guid))
+ const groups: AssignmentGroup[] = [
+ { assignments: (source.componentPropAssignments ?? []) as ComponentPropAssignment[], rank }
+ ]
+ const descendant: StructuralLayer[] = []
+ const swapRoot = (swap: GUID): void => {
+ if (!effective) throw new Error('Swap target is not an instance')
+ if (!sameGuid(effective, swap)) replaced.push(effective)
+ effective = swap
+ // Later layers may address the root through the replacement's identity.
+ for (const key of componentKeys(effective)) if (!isKey(key)) keys.push(key)
+ }
+ for (const layer of structural) {
+ const addressesRoot = layer.path.length === 0 || isKey(layer.path[0])
+ if (!addressesRoot || layer.path.length > 1) {
+ descendant.push(addressesRoot ? { ...layer, path: layer.path.slice(1) } : layer)
+ continue
+ }
+ if (layer.swap) swapRoot(layer.swap)
+ if (layer.assignments.length)
+ groups.push({ assignments: layer.assignments, rank: layer.owner.rank })
+ }
+ return { effective, replaced, groups, descendant }
+ }
+
+ const applyPropertyClaim = (
+ owner: InstanceOccurrence,
+ ownerRank: number,
+ target: InstanceOccurrence,
+ layer: PropertyLayer
+ ): void => {
+ // An outer owner's assignment supersedes this owner's explicit value for the same field.
+ const bound = assignedFields.get(target)
+ const retained = Object.fromEntries(
+ Object.entries(layer.props).filter(([field]) => {
+ const rank = bound?.get(field)
+ return rank === undefined || rank >= ownerRank
+ })
+ )
+ if (Object.keys(retained).length === 0) return
+ declareVariableBindingUnits(target, retained as NodeChange)
+ invalidateInheritedTextData(target.properties, retained)
+ Object.assign(
+ target.properties,
+ cloneRecord(retained),
+ mergeVariableConsumptionMaps(target.properties, retained as NodeChange)
+ )
+ if ('name' in retained) target.hasOwnName = true
+ owner.propertyClaims.push({
+ declaredBy: owner.sourceId,
+ path: structuredClone(layer.path),
+ properties: structuredClone(retained)
+ })
+ }
+
+ /**
+ * A claim that addressed a component an instance on its path no longer expands is
+ * stale, not wrong: some outer decision replaced that subtree after it was written.
+ */
+ const isRemovedTarget = (owner: InstanceOccurrence, path: readonly GUID[]): boolean => {
+ let current = owner
+ for (const [position, segment] of path.entries()) {
+ const rest = path.slice(position)
+ const replaced = replacedComponents.get(current) ?? []
+ if (replaced.some((component) => resolvesInSourceComponent(index, component, rest)))
+ return true
+ if (position === 0 && isRootGuid(current, segment)) continue
+ try {
+ current = findSegment(current, segment)
+ } catch (error) {
+ if (!(error instanceof SegmentError)) throw error
+ return false
+ }
+ }
+ return false
+ }
+
+ /** Resolve an owner's declared path in its built subtree, or decide how to skip it. */
+ const resolveClaimTarget = (
+ owner: InstanceOccurrence,
+ path: readonly GUID[]
+ ): InstanceOccurrence | undefined => {
+ try {
+ return resolveOccurrencePath(owner, path)
+ } catch (cause) {
+ if (!(cause instanceof SegmentError)) throw cause
+ const error = pathError(owner.sourceId, owner.mainComponentId, path, cause)
+ if (error.diagnostic.reason === 'missing-target' && isRemovedTarget(owner, path))
+ return undefined
+ if (!options.onUnresolvedProperty) throw error
+ options.onUnresolvedProperty(error.diagnostic)
+ return undefined
+ }
+ }
+
+ const applyDerivedBounds = (owner: InstanceOccurrence, source: NodeChange): void => {
+ if (!options.derivedBounds) return
+ const derived = source.derivedSymbolData as DerivedSymbolOverride[] | undefined
+ for (const entry of derived ?? []) {
+ const path = entry.guidPath?.guids
+ if (!path?.length) continue
+ const target = resolveClaimTarget(owner, path)
+ if (!target || target === owner) continue // Placed root bounds belong to its NodeChange.
+ applyDerivedEntry(target, entry)
+ }
+ }
+
+ /** Bind the record's fields from the enclosing component scope, recording provenance. */
+ const bindRecord = (
+ raw: NodeChange,
+ bindings: readonly PropertyBinding[]
+ ): {
+ source: NodeChange
+ claims: BoundPropertyClaim[]
+ /** Fields set by an owner's assignment, by that owner's rank. */
+ bound: Map<string, number>
+ /** Swap values earlier owners assigned before a later one replaced them. */
+ superseded: GUID[]
+ } => {
+ const claims: BoundPropertyClaim[] = []
+ const bound = new Map<string, number>()
+ const superseded: GUID[] = []
+ const source = bindSourceProperties(raw, bindings, (claim, binding) => {
+ claims.push(claim)
+ if (binding.origin === 'assignment' && binding.rank !== undefined)
+ bound.set(claim.field, binding.rank)
+ if (claim.field === 'symbolData')
+ for (const value of binding.superseded ?? [])
+ if (value.guidValue) superseded.push(value.guidValue)
+ })
+ return { source, claims, bound, superseded }
+ }
+
+ /**
+ * Expand one source record. `layers` are structural layers addressed relative to this
+ * expansion: an empty path configures this record itself, a longer path a descendant.
+ */
+ const expand = (
+ id: string,
+ bindings: readonly PropertyBinding[],
+ layers: readonly StructuralLayer[],
+ rank: number
+ ): InstanceOccurrence => {
+ if (expanding.has(id)) throw new Error(`Cyclic component expansion at ${id}`)
+ const raw = sources.get(id)
+ if (!raw) throw new Error(`Missing source node ${id}`)
+ const record = bindRecord(raw, bindings)
+ const { source } = record
+ expanding.add(id)
+ try {
+ const owner: Owner = { id, rank, mainComponentId: null, unresolved: [] }
+ const own = ownLayers(source, owner)
+ const structural = [...own.structural, ...layers].sort((a, b) => b.owner.rank - a.owner.rank)
+ const root = resolveRoot(raw, source, record.superseded, structural, rank)
+ const subtree = root.effective
+ ? expandBase(owner, { ...root, effective: root.effective }, rank)
+ : expandChildren(id, source, bindings, root.groups, root.descendant, rank)
+ const occurrence = createOccurrence(id, raw, source, root, subtree, record.claims)
+ assignedFields.set(occurrence, record.bound)
+ if (subtree.base && root.replaced.length) replacedComponents.set(occurrence, root.replaced)
+ declareSourceVariableBindingUnits(occurrence, source)
+ const claims = subtree.dangling
+ ? own.claims.filter(({ path }) => path.length === 1 && isRootGuid(occurrence, path[0]))
+ : own.claims
+ finishOccurrence(occurrence, subtree.base, source, claims, rank, !subtree.dangling)
+ for (const diagnostic of owner.unresolved)
+ options.onUnresolvedAssignment?.({
+ ...diagnostic,
+ mainComponentId: occurrence.mainComponentId
+ })
+ return occurrence
+ } finally {
+ expanding.delete(id)
+ }
+ }
+
+ interface Subtree {
+ base: InstanceOccurrence | null
+ children: InstanceOccurrence[]
+ /** The component is gone; only the record itself remains addressable. */
+ dangling?: true
+ }
+
+ /**
+ * The component expansion receives the assignments as its own root layers and the
+ * descendant layers unchanged: both address the same subtree.
+ */
+ const expandBase = (
+ owner: Owner,
+ { effective, replaced, groups, descendant }: RootResolution & { effective: GUID },
+ rank: number
+ ): Subtree => {
+ const componentId = guidToString(effective)
+ if (!sources.has(componentId)) {
+ // Layers addressed into the missing subtree have nothing to configure.
+ if (!options.onMissingComponent) throw new Error(`Missing source node ${componentId}`)
+ options.onMissingComponent({ ownerId: owner.id, componentId })
+ return { base: null, children: [], dangling: true }
+ }
+ owner.mainComponentId = terminalComponent(index, componentId)
+ const crossing = descendant.map((layer) =>
+ replaced.length ? { ...layer, boundary: { replaced, path: layer.path } } : layer
+ )
+ const rootLayers = groups
+ .filter((group) => group.assignments.length)
+ .map((group): StructuralLayer => ({
+ owner: { ...owner, rank: group.rank },
+ declaredPath: [],
+ path: [],
+ assignments: group.assignments
+ }))
+ const base = expand(guidToString(effective), [], [...rootLayers, ...crossing], rank + 1)
+ return { base, children: base.children }
+ }
+
+ /** A component definition starts a binding scope; ordinary containers pass theirs through. */
+ const expandChildren = (
+ id: string,
+ source: NodeChange,
+ bindings: readonly PropertyBinding[],
+ groups: readonly AssignmentGroup[],
+ descendant: readonly StructuralLayer[],
+ rank: number
+ ): Subtree => {
+ const scoped =
+ source.type === 'SYMBOL'
+ ? groups.reduce(
+ (result, group) => instanceBindings(result, group.assignments, group.rank),
+ componentBindings(source)
+ )
+ : bindings
+ const routed = routeToChildren(id, descendant)
+ const expanded = (children.get(id) ?? []).map((child) => {
+ if (!child.guid) throw new Error('Indexed child has no GUID')
+ const childId = guidToString(child.guid)
+ return expand(childId, scoped, routed.get(childId) ?? [], rank + 1)
+ })
+ return { base: null, children: expanded }
+ }
+
+ /** Identity and provenance an occurrence inherits from the subtree it expands. */
+ const inheritedFromBase = (
+ base: InstanceOccurrence | null
+ ): Pick<
+ InstanceOccurrence,
+ | 'mainComponentId'
+ | 'mainComponentOverrideKey'
+ | 'propertyClaims'
+ | 'variableBindingScales'
+ | 'hasOwnName'
+ > => {
+ if (!base) {
+ return {
+ mainComponentId: null,
+ mainComponentOverrideKey: undefined,
+ propertyClaims: [],
+ variableBindingScales: {},
+ hasOwnName: false
+ }
+ }
+ return {
+ mainComponentId: base.mainComponentId ?? base.sourceId,
+ mainComponentOverrideKey: base.mainComponentOverrideKey ?? base.overrideKey,
+ propertyClaims: structuredClone(base.propertyClaims),
+ variableBindingScales: { ...base.variableBindingScales },
+ hasOwnName: sources.get(base.sourceId)?.type === 'INSTANCE' && base.hasOwnName
+ }
+ }
+
+ const createOccurrence = (
+ id: string,
+ raw: NodeChange,
+ source: NodeChange,
+ { effective, replaced, groups }: RootResolution,
+ { base, children: expanded }: Subtree,
+ bindingClaims: BoundPropertyClaim[]
+ ): InstanceOccurrence => {
+ const original = raw.symbolData?.symbolID
+ const [, sourceComponentOverrideKey] = componentKeys(original)
+ const occurrence: InstanceOccurrence = {
+ sourceId: id,
+ sourceComponentId: original,
+ sourceComponentOverrideKey,
+ ...inheritedFromBase(base),
+ bindingClaims,
+ overrideKey: readOverrideKey(source.overrideKey),
+ // The record is the top layer of its own root: its fields are placed state.
+ properties: {
+ ...base?.properties,
+ ...source,
+ ...(effective && source.symbolData
+ ? { symbolData: { ...source.symbolData, symbolID: effective } }
+ : {}),
+ ...mergeVariableConsumptionMaps(base?.properties ?? {}, source)
+ },
+ children: expanded
+ }
+ if (source.type === 'INSTANCE')
+ occurrence.properties.componentPropAssignments = groups.flatMap((g) => g.assignments)
+ // A swapped instance without a name of its own takes the replacement's default name.
+ if (base && replaced.length && !occurrence.hasOwnName)
+ occurrence.properties.name = base.defaultInstanceName ?? base.properties.name
+ occurrence.defaultInstanceName = defaultInstanceName(occurrence)
+ return occurrence
+ }
+
+ /** Apply this owner's property layers, then its placed geometry and saved caches. */
+ const finishOccurrence = (
+ occurrence: InstanceOccurrence,
+ base: InstanceOccurrence | null,
+ source: NodeChange,
+ claims: readonly PropertyLayer[],
+ rank: number,
+ derived: boolean
+ ): void => {
+ for (const claim of claims) {
+ const target = resolveClaimTarget(occurrence, claim.path)
+ if (target) applyPropertyClaim(occurrence, rank, target, claim)
+ }
+ applyInstanceLayoutScale(occurrence, source)
+ applyPlacedConstraints(occurrence, base, source)
+ if (source.type === 'INSTANCE' && source.size)
+ occurrence.properties.size = structuredClone(source.size)
+ if (derived) applyDerivedBounds(occurrence, source)
+ }
+
+ if (sources.get(rootId)?.type !== expectedType) {
+ const kind = { INSTANCE: 'an instance', SYMBOL: 'a component', CANVAS: 'a page' }[expectedType]
+ throw new Error(`Expected ${kind} source`)
+ }
+ return expand(rootId, [], [], 0)
+}
diff --git a/packages/fig/src/instance-overrides/layers.ts b/packages/fig/src/instance-overrides/layers.ts
new file mode 100644
index 000000000..b843455a3
--- /dev/null
+++ b/packages/fig/src/instance-overrides/layers.ts
@@ -0,0 +1,62 @@
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import type { InstanceAssignmentDiagnostic } from './interpret'
+import { symbolOverridesOf, type ComponentPropAssignment } from './types'
+
+/** Mutable per-owner frame shared by the layers an owner declares. */
+export interface Owner {
+ readonly id: string
+ /** Expansion depth of the owner; smaller is further out and applies later. */
+ readonly rank: number
+ mainComponentId: string | null
+ /** Assignment layers whose target did not exist, reported once the owner is built. */
+ readonly unresolved: InstanceAssignmentDiagnostic[]
+}
+
+/** The last instance boundary a layer crossed whose component was replaced. */
+export interface ReplacedBoundary {
+ readonly replaced: readonly GUID[]
+ /** The layer's path relative to that boundary. */
+ readonly path: readonly GUID[]
+}
+
+/** A swap or assignment addressed relative to the expansion that receives it. */
+export interface StructuralLayer {
+ readonly owner: Owner
+ /** Complete path as declared, for diagnostics. */
+ readonly declaredPath: readonly GUID[]
+ readonly path: readonly GUID[]
+ readonly swap?: GUID
+ readonly assignments: readonly ComponentPropAssignment[]
+ /** Set when an outer decision replaced a component this layer was written against. */
+ readonly boundary?: ReplacedBoundary
+}
+
+export interface PropertyLayer {
+ readonly path: readonly GUID[]
+ readonly props: Record<string, unknown>
+}
+
+export interface AssignmentGroup {
+ readonly assignments: readonly ComponentPropAssignment[]
+ readonly rank: number
+}
+
+/** Split an owner's saved overrides into structural layers and property claims. */
+export function ownLayers(
+ source: NodeChange,
+ owner: Owner
+): { structural: StructuralLayer[]; claims: PropertyLayer[] } {
+ const structural: StructuralLayer[] = []
+ const claims: PropertyLayer[] = []
+ for (const override of symbolOverridesOf(source)) {
+ const { guidPath, overriddenSymbolID: swap, componentPropAssignments, ...props } = override
+ const path = guidPath?.guids ?? []
+ if (!path.length) continue
+ const assignments = componentPropAssignments ?? []
+ if (swap || assignments.length)
+ structural.push({ owner, declaredPath: path, path, swap, assignments })
+ if (Object.keys(props).length) claims.push({ path, props })
+ }
+ return { structural, claims }
+}
diff --git a/packages/fig/src/instance-overrides/live-component-edits.ts b/packages/fig/src/instance-overrides/live-component-edits.ts
new file mode 100644
index 000000000..298d8037d
--- /dev/null
+++ b/packages/fig/src/instance-overrides/live-component-edits.ts
@@ -0,0 +1,51 @@
+import {
+ getInstanceOverride,
+ INSTANCE_SYNC_FIELDS,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import type { MaterializedInstance } from './materialize-instance'
+
+/** Apply live component edits to new occurrences, never repaint or resync existing pages. */
+export function reconcileLiveComponentEdits(
+ graph: SceneGraph,
+ materialized: MaterializedInstance
+): void {
+ graph.preserveSourceMetadataDuring(() => {
+ for (const target of materialized.nodes.values()) {
+ const owners: SceneNode[] = []
+ let parent = target.parentId ? graph.getNode(target.parentId) : undefined
+ while (parent) {
+ if (parent.type === 'INSTANCE') owners.push(parent)
+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
+ }
+ if (target.type === 'INSTANCE') owners.unshift(target)
+ const protectedFields = new Set<string>()
+ for (const owner of owners) {
+ const fields =
+ owner.id === target.id
+ ? owner.instanceOverrides.self
+ : owner.instanceOverrides.descendants.get(target.id)
+ for (const field of fields?.keys() ?? []) protectedFields.add(field)
+ }
+ const updates: Partial<SceneNode> = {}
+ for (const owner of owners) {
+ const mapped = getInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ target.id,
+ 'sourceComponentId'
+ )
+ const sourceId = typeof mapped === 'string' ? mapped : target.componentId
+ const source = sourceId ? graph.getNode(sourceId) : undefined
+ if (!source) continue
+ for (const field of INSTANCE_SYNC_FIELDS) {
+ if (!source.source.editedFields.includes(field) || protectedFields.has(field)) continue
+ Object.assign(updates, { [field]: structuredClone(source[field]) })
+ }
+ }
+ if (Object.keys(updates).length) graph.updateNode(target.id, updates)
+ }
+ })
+}
diff --git a/packages/fig/src/instance-overrides/materialize-instance.ts b/packages/fig/src/instance-overrides/materialize-instance.ts
new file mode 100644
index 000000000..b7b036231
--- /dev/null
+++ b/packages/fig/src/instance-overrides/materialize-instance.ts
@@ -0,0 +1,230 @@
+import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'
+import { setInstanceOverride, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
+
+import { nodeChangeToProps } from '../node-change'
+import { numericVariableBindingScales } from '../node-change/variable-bindings'
+import {
+ recordVariableBindingClaims,
+ occurrenceAssignmentScales,
+ occurrenceScale
+} from './bindings/variables'
+import { OVERRIDE_FIELDS, type OverrideField, type RawOverrideField } from './fields'
+import { resolveOccurrencePath, type InstanceOccurrence } from './interpret'
+import { symbolDataOf } from './types'
+
+function occurrenceMetadata(
+ current: InstanceOccurrence,
+ converted: ReturnType<typeof nodeChangeToProps>
+) {
+ const metadata = createDefaultSourceMetadata()
+ metadata.fig.layout = converted.source?.fig.layout ?? null
+ metadata.fig.uniformScaleFactor = symbolDataOf(current.properties)?.uniformScaleFactor ?? null
+ return metadata
+}
+
+export interface MaterializedInstance {
+ root: SceneNode
+ /** Occurrence object identity distinguishes repeated uses of a source node. */
+ nodes: ReadonlyMap<InstanceOccurrence, SceneNode>
+}
+
+/**
+ * Materialize an interpreted tree. Population, sync and layout are the caller's to run.
+ * Component IDs must refer to existing COMPONENT nodes in the destination graph.
+ * Occurrence provenance stays in the returned map, not in fabricated FIG metadata.
+ */
+/** What an occurrence tree needs beyond the graph it is written into. */
+export interface MaterializeInstanceOptions {
+ blobs?: Uint8Array[]
+ /** Graph ids for occurrences a component definition already materialized. */
+ sourceChildren?: ReadonlyMap<InstanceOccurrence, string>
+ /** Nodes to update in place rather than create, keyed by occurrence. */
+ existingNodes?: ReadonlyMap<InstanceOccurrence, SceneNode>
+}
+
+/** A document or a variable is a resource record, never a node in an expansion. */
+function assertMaterializableType(
+ nodeType: 'DOCUMENT' | 'VARIABLE' | SceneNode['type']
+): asserts nodeType is SceneNode['type'] {
+ if (nodeType === 'DOCUMENT' || nodeType === 'VARIABLE') {
+ throw new Error(`Cannot materialize ${nodeType} as an instance descendant`)
+ }
+}
+
+export function materializeInstance(
+ graph: SceneGraph,
+ parentId: string,
+ occurrence: InstanceOccurrence,
+ components: ReadonlyMap<string, string>,
+ options: MaterializeInstanceOptions = {}
+): MaterializedInstance {
+ const { blobs = [], sourceChildren = new Map(), existingNodes = new Map() } = options
+ if (!graph.getNode(parentId)) throw new Error('Missing materialization parent')
+ const prepared = new Map<InstanceOccurrence, ReturnType<typeof nodeChangeToProps>>()
+ const validate = (current: InstanceOccurrence): void => {
+ if (prepared.has(current)) throw new Error('Repeated or cyclic instance occurrence')
+ const converted = nodeChangeToProps(current.properties, blobs, 'occurrence')
+ if (converted.nodeType === 'TEXT' && current.derivedSize) {
+ converted.derivedLayout = { width: current.derivedSize.x, height: current.derivedSize.y }
+ }
+ assertMaterializableType(converted.nodeType)
+ const existing = existingNodes.get(current)
+ if (
+ existing &&
+ (graph.getNode(existing.id) !== existing || existing.type !== converted.nodeType)
+ ) {
+ throw new Error(`Invalid preallocated occurrence ${current.sourceId}`)
+ }
+ prepared.set(current, converted)
+ const sourceChildId = sourceChildren.get(current)
+ if (sourceChildId && graph.getNode(sourceChildId)?.type !== converted.nodeType) {
+ throw new Error(`Invalid source child for ${current.sourceId}`)
+ }
+ if (current.mainComponentId !== null) {
+ const id = components.get(current.mainComponentId)
+ if (!id || graph.getNode(id)?.type !== 'COMPONENT') {
+ throw new Error(`Missing materialized component ${current.mainComponentId}`)
+ }
+ }
+ for (const child of current.children) validate(child)
+ }
+ validate(occurrence)
+ const nodes = new Map<InstanceOccurrence, SceneNode>(existingNodes)
+ const applyBindingClaims = (
+ current: InstanceOccurrence,
+ node: SceneNode,
+ owner?: SceneNode
+ ): void => {
+ if (!owner) return
+ for (const claim of current.bindingClaims) {
+ if (claim.origin === 'assignment' && claim.field === 'visible') {
+ setInstanceOverride(owner.instanceOverrides, owner.id, node.id, 'visible', node.visible)
+ }
+ }
+ }
+ const create = (current: InstanceOccurrence, parent: string, owner?: SceneNode): SceneNode => {
+ const converted = prepared.get(current)
+ if (!converted) throw new Error('Missing prepared occurrence')
+ const { nodeType, ...props } = converted
+ assertMaterializableType(nodeType)
+ const metadata = occurrenceMetadata(current, converted)
+ const propsWithIdentity = {
+ ...props,
+ variableAssignmentScales: occurrenceAssignmentScales(current),
+ componentScale: occurrenceScale(current),
+ variableBindingScales: numericVariableBindingScales(
+ props.boundVariables ?? {},
+ current.layoutScale ?? 1,
+ current.variableBindingScales
+ ),
+ componentId:
+ current.mainComponentId === null
+ ? (sourceChildren.get(current) ?? null)
+ : components.get(current.mainComponentId),
+ source: metadata
+ }
+ const existing = existingNodes.get(current)
+ if (existing && existing.parentId !== parent) {
+ throw new Error(`Preallocated occurrence has wrong parent ${current.sourceId}`)
+ }
+ const node = existing ?? graph.createNode(nodeType, parent, propsWithIdentity)
+ if (existing) graph.updateNode(existing.id, propsWithIdentity)
+ nodes.set(current, node)
+ if (existing && current !== occurrence && node.type === 'COMPONENT') return node
+ applyBindingClaims(current, node, owner)
+ const sourceChildId = sourceChildren.get(current)
+ if (owner && current.mainComponentId !== null && sourceChildId) {
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ node.id,
+ 'sourceComponentId',
+ sourceChildId
+ )
+ const sourceChild = graph.getNode(sourceChildId)
+ if (sourceChild?.componentId !== node.componentId) {
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ node.id,
+ 'componentId',
+ node.componentId
+ )
+ }
+ }
+ const children = current.children.map(
+ (child) => create(child, node.id, node.type === 'INSTANCE' ? node : owner).id
+ )
+ node.childIds = children
+ return node
+ }
+ const root = create(occurrence, parentId)
+ recordPropertyClaims(nodes)
+ return { root, nodes }
+}
+
+/** Whether a raw claim actually carries the scene value its kind maps to. */
+function claimApplies(field: OverrideField, value: unknown, target: SceneNode): boolean {
+ if (field.kind === 'text')
+ return typeof value === 'object' && value !== null && 'characters' in value
+ if (field.kind === 'text-style') return Boolean(target.textStyleId)
+ return true
+}
+
+/**
+ * A claimed paint carries its colour alias inside the paint, so the binding it declares is
+ * part of the claim too; otherwise a later component sync restores the component's binding.
+ */
+function recordPaintBindingClaims(
+ owner: SceneNode,
+ target: SceneNode,
+ scene: keyof SceneNode,
+ paints: unknown
+): void {
+ if (!Array.isArray(paints)) return
+ let declared = false
+ for (const [index, paint] of paints.entries()) {
+ const alias = (paint as Paint).colorVar?.value?.alias ?? (paint as Paint).colorVariableBinding
+ if (!alias) continue
+ const field = `boundVariables/${scene}/${index}/color`
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ target.id,
+ field,
+ target.boundVariables[`${scene}/${index}/color`] ?? null
+ )
+ declared = true
+ }
+ if (declared) setInstanceOverride(owner.instanceOverrides, owner.id, target.id, 'boundVariables')
+}
+
+function recordPropertyClaims(nodes: ReadonlyMap<InstanceOccurrence, SceneNode>): void {
+ for (const [ownerOccurrence, owner] of nodes) {
+ if (owner.type !== 'INSTANCE') continue
+ for (const claim of ownerOccurrence.propertyClaims) {
+ const targetOccurrence = resolveOccurrencePath(ownerOccurrence, claim.path)
+ const target = nodes.get(targetOccurrence)
+ if (!target) throw new Error('Unmaterialized property claim target')
+ for (const raw of Object.keys(OVERRIDE_FIELDS) as RawOverrideField[]) {
+ if (!(raw in claim.properties)) continue
+ const field = OVERRIDE_FIELDS[raw]
+ if (!claimApplies(field, claim.properties[raw], target)) continue
+ for (const scene of field.scene) {
+ const value = target[scene]
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ target.id,
+ scene,
+ structuredClone(value)
+ )
+ }
+ if (field.kind === 'paint')
+ recordPaintBindingClaims(owner, target, field.scene[0], claim.properties[raw])
+ }
+ recordVariableBindingClaims(owner, target, claim.properties as NodeChange)
+ }
+ }
+}
diff --git a/packages/fig/src/instance-overrides/occurrence-path.ts b/packages/fig/src/instance-overrides/occurrence-path.ts
new file mode 100644
index 000000000..6b78b75bf
--- /dev/null
+++ b/packages/fig/src/instance-overrides/occurrence-path.ts
@@ -0,0 +1,86 @@
+import type { GUID } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import type { InstanceOccurrence, InstancePathDiagnostic } from './interpret'
+import { sameGuid } from './source-index'
+import { descendants, findWithinBoundary, type TreeShape } from './tree'
+
+export const OCCURRENCE_TREE: TreeShape<InstanceOccurrence> = {
+ childrenOf: (node) => node.children,
+ isInstance: (node) => node.mainComponentId !== null
+}
+
+/** Every occurrence below and including `root`, including those inside nested instances. */
+export function occurrences(root: InstanceOccurrence): Generator<InstanceOccurrence> {
+ return descendants(root, (node) => node.children)
+}
+
+export class InstancePathError extends Error {
+ constructor(
+ readonly diagnostic: InstancePathDiagnostic,
+ message: string
+ ) {
+ super(message)
+ this.name = 'InstancePathError'
+ }
+}
+
+export class SegmentError extends Error {
+ constructor(
+ readonly count: number,
+ guid: GUID
+ ) {
+ super(`Expected one instance-path target for ${guidToString(guid)}; found ${count}`)
+ this.name = 'SegmentError'
+ }
+}
+
+export function pathError(
+ ownerId: string,
+ mainComponentId: string | null,
+ path: readonly GUID[],
+ cause: SegmentError
+): InstancePathError {
+ return new InstancePathError(
+ {
+ ownerId,
+ mainComponentId,
+ path: structuredClone(path),
+ reason: cause.count === 0 ? 'missing-target' : 'ambiguous-target'
+ },
+ `Override declared by ${ownerId}, path [${path.map(guidToString).join(', ')}]: ${cause.message}`
+ )
+}
+
+/** Search through ordinary containers, but never cross an instance boundary implicitly. */
+export function findSegment(root: InstanceOccurrence, guid: GUID): InstanceOccurrence {
+ const id = guidToString(guid)
+ const { count, match } = findWithinBoundary(
+ root.children,
+ OCCURRENCE_TREE,
+ (node) => sameGuid(node.overrideKey, guid) || node.sourceId === id
+ )
+ if (!match) throw new SegmentError(count, guid)
+ return match
+}
+
+export function isRootGuid(owner: InstanceOccurrence, guid: GUID): boolean {
+ return (
+ sameGuid(owner.properties.symbolData?.symbolID, guid) ||
+ sameGuid(owner.mainComponentOverrideKey, guid) ||
+ sameGuid(owner.sourceComponentOverrideKey, guid) ||
+ sameGuid(owner.sourceComponentId, guid)
+ )
+}
+
+export function resolveOccurrencePath(
+ owner: InstanceOccurrence,
+ path: readonly GUID[]
+): InstanceOccurrence {
+ let target = owner
+ for (const [index, guid] of path.entries()) {
+ if (index === 0 && isRootGuid(owner, guid)) continue
+ target = findSegment(target, guid)
+ }
+ return target
+}
diff --git a/packages/fig/src/instance-overrides/patches/apply.ts b/packages/fig/src/instance-overrides/patches/apply.ts
deleted file mode 100644
index 4a54211bd..000000000
--- a/packages/fig/src/instance-overrides/patches/apply.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
-
-import { repopulateInstance } from '../resolve'
-import type { OverrideContext } from '../types'
-import { protectField, protectPatchProps } from './protection'
-import type { OverridePatch } from './types'
-
-function preserveStrokeShapeProps(target: SceneNode, updates: Partial<SceneNode>): void {
- if (!updates.strokes) return
- updates.strokes = updates.strokes.map((stroke, index) => {
- if (index >= target.strokes.length) {
- return {
- ...stroke,
- cap: target.strokeCap,
- join: target.strokeJoin,
- dashPattern: target.dashPattern
- }
- }
- const existing = target.strokes[index]
- return {
- ...stroke,
- cap: existing.cap,
- join: existing.join,
- dashPattern: existing.dashPattern
- }
- })
-}
-
-export function applyOverridePatch(ctx: OverrideContext, patch: OverridePatch): boolean {
- let changed = false
- if (patch.swapComponentId) {
- repopulateInstance(ctx, patch.targetId, patch.swapComponentId)
- protectField(ctx.protectedFields, patch.targetId, 'structure')
- changed = true
- }
-
- if (patch.props && Object.keys(patch.props).length > 0) {
- const target = ctx.graph.getNode(patch.targetId)
- if (target) {
- const props = patch.props
- if (props.boundVariables) {
- props.boundVariables = { ...target.boundVariables, ...props.boundVariables }
- }
- preserveStrokeShapeProps(target, props)
- ctx.graph.preserveSourceMetadataDuring(() => ctx.graph.updateNode(patch.targetId, props))
- protectPatchProps(ctx.protectedFields, patch.targetId, props)
- changed = true
- }
- }
- return changed
-}
diff --git a/packages/fig/src/instance-overrides/patches/index.ts b/packages/fig/src/instance-overrides/patches/index.ts
deleted file mode 100644
index b199d7be6..000000000
--- a/packages/fig/src/instance-overrides/patches/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export { applyOverridePatch } from './apply'
-export { protectField, protectPatchProps, isFieldProtected } from './protection'
-export type { ProtectedField, ProtectionMap } from './protection'
-export type { OverridePatch, OverridePatchSource } from './types'
diff --git a/packages/fig/src/instance-overrides/patches/protection.ts b/packages/fig/src/instance-overrides/patches/protection.ts
deleted file mode 100644
index 8a98a2f0f..000000000
--- a/packages/fig/src/instance-overrides/patches/protection.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
-
-export type ProtectedField =
- | 'text'
- | 'visible'
- | 'opacity'
- | 'fills'
- | 'strokes'
- | 'effects'
- | 'styleRuns'
- | 'layoutGrow'
- | 'textAutoResize'
- | 'locked'
- | 'x'
- | 'y'
- | 'width'
- | 'height'
- | 'derivedLayout'
- | 'fontSize'
- | 'lineHeight'
- | 'letterSpacing'
- | 'fillGeometry'
- | 'strokeGeometry'
- | 'structure'
-
-export type ProtectionMap = Map<string, Set<ProtectedField>>
-
-const PROP_TO_PROTECTED_FIELD: Partial<Record<keyof SceneNode, ProtectedField>> = {
- text: 'text',
- visible: 'visible',
- opacity: 'opacity',
- fills: 'fills',
- strokes: 'strokes',
- effects: 'effects',
- styleRuns: 'styleRuns',
- layoutGrow: 'layoutGrow',
- textAutoResize: 'textAutoResize',
- locked: 'locked',
- x: 'x',
- y: 'y',
- width: 'width',
- height: 'height',
- derivedLayout: 'derivedLayout',
- fontSize: 'fontSize',
- lineHeight: 'lineHeight',
- letterSpacing: 'letterSpacing',
- fillGeometry: 'fillGeometry',
- strokeGeometry: 'strokeGeometry'
-}
-
-export function protectField(
- protections: ProtectionMap,
- nodeId: string,
- field: ProtectedField
-): void {
- const fields = protections.get(nodeId)
- if (fields) fields.add(field)
- else protections.set(nodeId, new Set([field]))
-}
-
-export function protectPatchProps(
- protections: ProtectionMap,
- nodeId: string,
- props: Partial<SceneNode>
-): void {
- for (const key of Object.keys(props) as Array<keyof SceneNode>) {
- const field = PROP_TO_PROTECTED_FIELD[key]
- if (field) protectField(protections, nodeId, field)
- }
-}
-
-export function isFieldProtected(
- protections: ProtectionMap | undefined,
- nodeId: string,
- field: ProtectedField
-): boolean {
- return protections?.get(nodeId)?.has(field) === true
-}
diff --git a/packages/fig/src/instance-overrides/patches/types.ts b/packages/fig/src/instance-overrides/patches/types.ts
deleted file mode 100644
index ee54d3fbb..000000000
--- a/packages/fig/src/instance-overrides/patches/types.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
-
-export type OverridePatchSource = 'symbol-override' | 'component-prop' | 'derived-symbol-data'
-
-export interface OverridePatch {
- targetId: string
- source: OverridePatchSource
- props?: Partial<SceneNode>
- swapComponentId?: string
-}
diff --git a/packages/fig/src/instance-overrides/populate.ts b/packages/fig/src/instance-overrides/populate.ts
deleted file mode 100644
index 62ccbb4e0..000000000
--- a/packages/fig/src/instance-overrides/populate.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import type { SceneGraph } from '@open-pencil/scene-graph'
-
-/**
- * Populate empty INSTANCE nodes from their source components.
- *
- * Instances must be populated bottom-up: if an instance's source is
- * itself an unpopulated instance, populate the source first so cloned
- * children are complete.
- */
-function collectSubtreeIds(graph: SceneGraph, rootIds: Iterable<string>): Set<string> {
- const result = new Set<string>()
- const queue = [...rootIds]
- let index = 0
- while (index < queue.length) {
- const id = queue[index]
- index++
- if (result.has(id)) continue
- result.add(id)
- const node = graph.getNode(id)
- if (node) queue.push(...node.childIds)
- }
- return result
-}
-
-export function populateInstances(
- graph: SceneGraph,
- rootIds?: Iterable<string>
-): Set<string> | undefined {
- const visiting = new Set<string>()
-
- function ensurePopulated(nodeId: string): void {
- const node = graph.getNode(nodeId)
- if (node?.type !== 'INSTANCE' || !node.componentId || node.childIds.length > 0) return
- if (visiting.has(nodeId)) return
- visiting.add(nodeId)
-
- const comp = graph.getNode(node.componentId)
- if (!comp) return
-
- if (comp.type === 'INSTANCE' && comp.componentId && comp.childIds.length === 0) {
- ensurePopulated(comp.id)
- }
- for (const childId of comp.childIds) {
- const child = graph.getNode(childId)
- if (child?.type === 'INSTANCE' && child.componentId && child.childIds.length === 0) {
- ensurePopulated(childId)
- }
- }
-
- if (comp.childIds.length > 0 && node.childIds.length === 0) {
- graph.populateInstanceChildren(nodeId, node.componentId, 'fig-import')
- }
- }
-
- if (!rootIds) {
- for (const node of graph.nodes.values()) {
- if (node.type === 'INSTANCE' && node.componentId && node.childIds.length === 0) {
- ensurePopulated(node.id)
- }
- }
- return undefined
- }
-
- const queue = [...rootIds]
- const visited = new Set<string>()
- let index = 0
- while (index < queue.length) {
- const nodeId = queue[index]
- index++
- if (!nodeId || visited.has(nodeId)) continue
- visited.add(nodeId)
- ensurePopulated(nodeId)
- const node = graph.getNode(nodeId)
- if (!node) continue
- queue.push(...node.childIds)
- }
- return collectSubtreeIds(graph, rootIds)
-}
diff --git a/packages/fig/src/instance-overrides/resize.ts b/packages/fig/src/instance-overrides/resize.ts
new file mode 100644
index 000000000..89b3e5103
--- /dev/null
+++ b/packages/fig/src/instance-overrides/resize.ts
@@ -0,0 +1,70 @@
+import type { NodeChange, Vector } from '@open-pencil/kiwi/fig/codec'
+
+import type { InstanceOccurrence } from './interpret'
+import { uniformScaleOf } from './types'
+
+export function applyPlacedConstraints(
+ root: InstanceOccurrence,
+ base: InstanceOccurrence | null,
+ source: NodeChange
+): void {
+ if (!base?.properties.size || !source.size) return
+ const scale = uniformScaleOf(source)
+ resizeFreeformOccurrence(
+ root,
+ { x: base.properties.size.x * scale, y: base.properties.size.y * scale },
+ source.size
+ )
+}
+
+function constrainedAxis(
+ position: number,
+ size: number,
+ before: number,
+ after: number,
+ constraint: string | undefined
+) {
+ const delta = after - before
+ if (constraint === 'SCALE' && before > 0) {
+ const factor = after / before
+ return { position: position * factor, size: size * factor }
+ }
+ if (constraint === 'MAX') return { position: position + delta, size }
+ if (constraint === 'CENTER') return { position: position + delta / 2, size }
+ if (constraint === 'STRETCH') return { position, size: Math.max(0, size + delta) }
+ return { position, size }
+}
+
+/** Apply freeform resize constraints in occurrence coordinates before saved derived bounds. */
+export function resizeFreeformOccurrence(
+ root: InstanceOccurrence,
+ before: Vector,
+ after: Vector
+): void {
+ if (before.x === after.x && before.y === after.y) return
+ const autoLayout = root.properties.stackMode && root.properties.stackMode !== 'NONE'
+ for (const child of root.children) {
+ const props = child.properties
+ if (autoLayout && props.stackPositioning !== 'ABSOLUTE') continue
+ if (!props.size) continue
+ const transform = props.transform ?? { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ const x = constrainedAxis(
+ transform.m02,
+ props.size.x,
+ before.x,
+ after.x,
+ props.horizontalConstraint
+ )
+ const y = constrainedAxis(
+ transform.m12,
+ props.size.y,
+ before.y,
+ after.y,
+ props.verticalConstraint
+ )
+ const size = { x: x.size, y: y.size }
+ resizeFreeformOccurrence(child, props.size, size)
+ props.size = size
+ props.transform = { ...transform, m02: x.position, m12: y.position }
+ }
+}
diff --git a/packages/fig/src/instance-overrides/resolve.ts b/packages/fig/src/instance-overrides/resolve.ts
deleted file mode 100644
index e93c2f5a2..000000000
--- a/packages/fig/src/instance-overrides/resolve.ts
+++ /dev/null
@@ -1,499 +0,0 @@
-import { guidToString } from '@open-pencil/fig/node-change'
-import type { GUID } from '@open-pencil/kiwi/fig/codec'
-import { copyInstanceComponentProps, type SceneNode } from '@open-pencil/scene-graph'
-import { copyStrokes } from '@open-pencil/scene-graph/copy'
-
-import {
- indexCloneSubtree,
- remapRepopulatedChildSources,
- snapshotChildSources
-} from './sync/sources'
-import type { InstanceNodeChange, OverrideContext } from './types'
-import { overrideCandidates } from './utils'
-
-const MAX_CHAIN_DEPTH = 20
-const siblingIndexCache = new WeakMap<OverrideContext, Map<string, number | null>>()
-const siblingGroupCache = new WeakMap<OverrideContext, Map<string, string[]>>()
-const candidateCache = new WeakMap<OverrideContext, Map<string, string[]>>()
-const componentFindCache = new WeakMap<OverrideContext, Map<string, string | null>>()
-const sourcePathCache = new WeakMap<OverrideContext, Map<string, number[] | null>>()
-const overridePathTargetCache = new WeakMap<OverrideContext, Map<string, string>>()
-
-/**
- * Pre-compute componentId root for every node.
- *
- * Must run while all internal-page nodes are still alive. After overrides,
- * instance swaps delete intermediate clones, breaking the chain.
- * DSD resolution uses this to match across clone levels.
- */
-export function preComputeRoots(ctx: OverrideContext): void {
- function resolve(nodeId: string, depth = 0): string {
- const cached = ctx.preComputedRoot.get(nodeId)
- if (cached !== undefined) return cached
- if (depth > MAX_CHAIN_DEPTH) return nodeId
-
- const node = ctx.graph.getNode(nodeId)
- if (node?.componentId && node.componentId !== nodeId) {
- const root = resolve(node.componentId, depth + 1)
- ctx.preComputedRoot.set(nodeId, root)
- return root
- }
- ctx.preComputedRoot.set(nodeId, nodeId)
- return nodeId
- }
-
- for (const node of overrideCandidates(ctx.graph, ctx.activeNodeIds)) {
- if (!node.componentId) continue
- resolve(node.id)
- const clones = ctx.preComputedClones.get(node.componentId)
- if (clones) clones.push(node.id)
- else ctx.preComputedClones.set(node.componentId, [node.id])
- }
-}
-
-/**
- * Walk the componentId chain to the ultimate source COMPONENT.
- * Falls back to kiwi symbolData for deleted internal-page nodes.
- */
-export function getComponentRoot(ctx: OverrideContext, nodeId: string, depth = 0): string {
- const cached = ctx.componentIdRoot.get(nodeId)
- if (cached !== undefined) return cached
- if (depth > MAX_CHAIN_DEPTH) {
- ctx.componentIdRoot.set(nodeId, nodeId)
- return nodeId
- }
-
- const node = ctx.graph.getNode(nodeId)
- if (node?.componentId) {
- const root = getComponentRoot(ctx, node.componentId, depth + 1)
- ctx.componentIdRoot.set(nodeId, root)
- return root
- }
-
- // For deleted nodes (internal page), resolve via kiwi symbolData
- const figmaId = ctx.nodeIdToGuid.get(nodeId)
- if (figmaId) {
- const nc = ctx.changeMap.get(figmaId)
- const symId = nc?.symbolData?.symbolID
- if (symId) {
- const compNodeId = ctx.guidToNodeId.get(guidToString(symId))
- if (compNodeId && compNodeId !== nodeId) {
- const root = getComponentRoot(ctx, compNodeId, depth + 1)
- ctx.componentIdRoot.set(nodeId, root)
- return root
- }
- }
- }
-
- ctx.componentIdRoot.set(nodeId, nodeId)
- return nodeId
-}
-
-/**
- * Find a descendant whose componentId matches, walking recursively.
- *
- * Pass 1: exact componentId on direct children.
- * Pass 2: root match — only if exactly one child shares the root (avoids
- * ambiguity when multiple siblings share the same root).
- * Pass 3: recurse into children.
- */
-function buildSiblingGroups(ctx: OverrideContext): Map<string, string[]> {
- const groups = new Map<string, string[]>()
- for (const [id, sibling] of ctx.changeMap) {
- const siblingParent = sibling.parentIndex?.guid ? guidToString(sibling.parentIndex.guid) : null
- const siblingSymbol = sibling.symbolData?.symbolID
- ? guidToString(sibling.symbolData.symbolID)
- : null
- if (!siblingParent || !siblingSymbol) continue
- const groupKey = `${siblingParent}\0${siblingSymbol}`
- const group = groups.get(groupKey)
- if (group) group.push(id)
- else groups.set(groupKey, [id])
- }
- for (const group of groups.values()) {
- group.sort((aId, bId) => {
- const a = ctx.changeMap.get(aId)
- const b = ctx.changeMap.get(bId)
- return (
- (a?.transform?.m12 ?? 0) - (b?.transform?.m12 ?? 0) ||
- (a?.transform?.m02 ?? 0) - (b?.transform?.m02 ?? 0)
- )
- })
- }
- return groups
-}
-
-function getSiblingGroups(ctx: OverrideContext): Map<string, string[]> {
- const cached = siblingGroupCache.get(ctx)
- if (cached) return cached
- const groups = buildSiblingGroups(ctx)
- siblingGroupCache.set(ctx, groups)
- return groups
-}
-
-function sourceSiblingIndex(ctx: OverrideContext, sourceId: string): number | null {
- let cache = siblingIndexCache.get(ctx)
- if (!cache) {
- cache = new Map()
- siblingIndexCache.set(ctx, cache)
- }
- if (cache.has(sourceId)) return cache.get(sourceId) ?? null
-
- const nc = ctx.changeMap.get(sourceId)
- const parentId = nc?.parentIndex?.guid ? guidToString(nc.parentIndex.guid) : null
- const symbolId = nc?.symbolData?.symbolID ? guidToString(nc.symbolData.symbolID) : null
- if (!nc || !parentId || !symbolId) {
- cache.set(sourceId, null)
- return null
- }
-
- const siblings = getSiblingGroups(ctx).get(`${parentId}\0${symbolId}`) ?? []
- const index = siblings.indexOf(sourceId)
- const result = index !== -1 ? index : null
- cache.set(sourceId, result)
- return result
-}
-
-function sourcePathToNode(
- ctx: OverrideContext,
- sourceRootId: string,
- targetId: string
-): number[] | null {
- let cache = sourcePathCache.get(ctx)
- if (!cache) {
- cache = new Map()
- sourcePathCache.set(ctx, cache)
- }
- const cacheKey = `${sourceRootId}\0${targetId}`
- if (cache.has(cacheKey)) return cache.get(cacheKey) ?? null
-
- const visit = (nodeId: string, path: number[]): number[] | null => {
- const node = ctx.graph.getNode(nodeId)
- if (!node) return null
- if (nodeId === targetId || node.componentId === targetId) return path
- for (let index = 0; index < node.childIds.length; index++) {
- const result = visit(node.childIds[index], [...path, index])
- if (result) return result
- }
- return null
- }
-
- const result = visit(sourceRootId, [])
- cache.set(cacheKey, result)
- return result
-}
-
-function findNodeBySourcePath(
- ctx: OverrideContext,
- currentId: string,
- targetId: string
-): string | null {
- const current = ctx.graph.getNode(currentId)
- if (!current?.componentId) return null
- const path = sourcePathToNode(ctx, current.componentId, targetId)
- if (!path) return null
-
- let target = current
- for (const index of path) {
- const childId = target.childIds[index]
- if (!childId) return null
- const child = ctx.graph.getNode(childId)
- if (!child) return null
- target = child
- }
- return target.id
-}
-
-function findNodeByNameAndType(
- ctx: OverrideContext,
- parentId: string,
- name: string | undefined,
- type: string | undefined
-): string | null {
- if (!name || !type) return null
- let match: string | null = null
- let count = 0
- const visit = (id: string) => {
- if (count > 1) return
- const node = ctx.graph.getNode(id)
- if (!node) return
- if (node.name === name && node.type === type) {
- count++
- match = id
- }
- for (const childId of node.childIds) visit(childId)
- }
- visit(parentId)
- return count === 1 ? match : null
-}
-
-function findNodeBySourceSiblingIndex(
- ctx: OverrideContext,
- parentId: string,
- componentId: string,
- sourceId: string
-): string | null {
- const index = sourceSiblingIndex(ctx, sourceId)
- if (index == null) return null
-
- const targetRoot = ctx.preComputedRoot.get(componentId) ?? getComponentRoot(ctx, componentId)
- let cache = candidateCache.get(ctx)
- if (!cache) {
- cache = new Map()
- candidateCache.set(ctx, cache)
- }
- const cacheKey = `${parentId}\0${targetRoot}`
- let candidates = cache.get(cacheKey)
- if (!candidates) {
- candidates = []
- const collect = (id: string) => {
- const node = ctx.graph.getNode(id)
- if (!node) return
- if (node.componentId) {
- const root =
- ctx.preComputedRoot.get(node.componentId) ?? getComponentRoot(ctx, node.componentId)
- if (root === targetRoot) candidates?.push(id)
- }
- for (const childId of node.childIds) collect(childId)
- }
- collect(parentId)
- candidates.sort((aId, bId) => {
- const a = ctx.graph.getNode(aId)
- const b = ctx.graph.getNode(bId)
- return (a?.y ?? 0) - (b?.y ?? 0) || (a?.x ?? 0) - (b?.x ?? 0)
- })
- cache.set(cacheKey, candidates)
- }
- return candidates[index] ?? null
-}
-
-export function findNodeByComponentId(
- ctx: OverrideContext,
- parentId: string,
- componentId: string
-): string | null {
- let cache = componentFindCache.get(ctx)
- if (!cache) {
- cache = new Map()
- componentFindCache.set(ctx, cache)
- }
- const cacheKey = `${parentId}\0${componentId}`
- if (cache.has(cacheKey)) return cache.get(cacheKey) ?? null
-
- const parent = ctx.graph.getNode(parentId)
- if (!parent) return null
-
- for (const childId of parent.childIds) {
- const child = ctx.graph.getNode(childId)
- if (child?.componentId === componentId) {
- cache.set(cacheKey, childId)
- return childId
- }
- }
-
- const targetRoot = ctx.preComputedRoot.get(componentId) ?? getComponentRoot(ctx, componentId)
- if (targetRoot) {
- let rootMatch: string | null = null
- let ambiguous = false
- for (const childId of parent.childIds) {
- const child = ctx.graph.getNode(childId)
- if (!child?.componentId) continue
- const childRoot =
- ctx.preComputedRoot.get(child.componentId) ?? getComponentRoot(ctx, child.componentId)
- if (childRoot === targetRoot) {
- if (rootMatch) {
- ambiguous = true
- break
- }
- rootMatch = childId
- }
- }
- if (rootMatch && !ambiguous) {
- cache.set(cacheKey, rootMatch)
- return rootMatch
- }
- }
-
- for (const childId of parent.childIds) {
- const deep = findNodeByComponentId(ctx, childId, componentId)
- if (deep) {
- cache.set(cacheKey, deep)
- return deep
- }
- }
- return null
-}
-
-/**
- * Resolve a guidPath to a target node within an instance subtree.
- *
- * Each GUID in the path identifies an overrideKey → source id → graph node.
- * The chain walks from the instance down to the target.
- */
-function resolveOverrideStep(
- ctx: OverrideContext,
- currentId: string,
- sourceId: string,
- remapped: string | undefined,
- targetNc: InstanceNodeChange | undefined
-): string | null {
- if (!remapped) return findNodeByNameAndType(ctx, currentId, targetNc?.name, targetNc?.type)
-
- const current = ctx.graph.getNode(currentId)
- if (current?.componentId === remapped) return currentId
-
- return (
- findNodeBySourcePath(ctx, currentId, remapped) ??
- findNodeByComponentId(ctx, currentId, remapped) ??
- findNodeBySourceSiblingIndex(ctx, currentId, remapped, sourceId) ??
- findNodeByNameAndType(ctx, currentId, targetNc?.name, targetNc?.type)
- )
-}
-
-export function resolveOverrideTarget(
- ctx: OverrideContext,
- instanceId: string,
- guids: GUID[]
-): string | null {
- let pathTargets = overridePathTargetCache.get(ctx)
- if (!pathTargets) {
- pathTargets = new Map()
- overridePathTargetCache.set(ctx, pathTargets)
- }
-
- let currentId = instanceId
- const path: string[] = []
- for (let index = 0; index < guids.length; index++) {
- const key = guidToString(guids[index])
- path.push(key)
- const pathKey = `${instanceId}\0${path.join('/')}`
- const cachedTarget = pathTargets.get(pathKey)
- if (cachedTarget && ctx.graph.getNode(cachedTarget)) {
- currentId = cachedTarget
- continue
- }
- if (cachedTarget) pathTargets.delete(pathKey)
-
- const sourceId = ctx.overrideKeyToGuid.get(key) ?? key
- const targetNc = ctx.changeMap.get(sourceId)
- const symbolGuid = targetNc?.symbolData?.symbolID
- ? guidToString(targetNc.symbolData.symbolID)
- : null
- const remapped =
- ctx.guidToNodeId.get(sourceId) ?? (symbolGuid ? ctx.guidToNodeId.get(symbolGuid) : undefined)
- const resolved = resolveOverrideStep(ctx, currentId, sourceId, remapped, targetNc)
- if (resolved) {
- currentId = resolved
- pathTargets.set(pathKey, resolved)
- continue
- }
-
- const parent = ctx.graph.getNode(currentId)
- if (parent?.childIds.length === 1) {
- currentId = parent.childIds[0]
- index--
- path.pop()
- continue
- }
-
- return null
- }
- return currentId
-}
-
-/**
- * Repopulate an INSTANCE node with children from a new component (instance swap).
- * Only renames when the current name matches the root component name (preserves
- * user-given names). Clears the componentIdRoot cache after changing the tree.
- */
-function collectStyledStrokeDescendants(
- ctx: OverrideContext,
- nodeId: string
-): SceneNode['strokes'][] {
- const result: SceneNode['strokes'][] = []
- const visit = (id: string) => {
- const node = ctx.graph.getNode(id)
- if (!node) return
- if (node.strokes.length > 0) result.push(copyStrokes(node.strokes))
- for (const childId of node.childIds) visit(childId)
- }
- visit(nodeId)
- return result
-}
-
-function applyStrokeDescendants(
- ctx: OverrideContext,
- nodeId: string,
- strokes: SceneNode['strokes'][]
-): void {
- let index = 0
- const visit = (id: string) => {
- const node = ctx.graph.getNode(id)
- if (!node) return
- if (node.strokes.length > 0) {
- if (index < strokes.length) {
- ctx.graph.preserveSourceMetadataDuring(() => {
- ctx.graph.updateNode(id, { strokes: copyStrokes(strokes[index]) })
- })
- }
- index++
- }
- for (const childId of node.childIds) visit(childId)
- }
- visit(nodeId)
-}
-
-function componentInstanceName(ctx: OverrideContext, component: SceneNode | undefined): string {
- if (!component) return ''
- const parent = component.parentId ? ctx.graph.getNode(component.parentId) : undefined
- return parent?.type === 'COMPONENT_SET' ? parent.name : component.name
-}
-
-function swappedRootProps(node: SceneNode, component: SceneNode): Partial<SceneNode> {
- const props = copyInstanceComponentProps(component)
- props.width = node.width
- props.height = node.height
- props.boundVariables = { ...props.boundVariables }
- for (const field of ['width', 'height'] as const) {
- const binding = node.boundVariables[field]
- if (binding) props.boundVariables[field] = binding
- }
- return props
-}
-
-export function repopulateInstance(ctx: OverrideContext, nodeId: string, compId: string): void {
- const node = ctx.graph.getNode(nodeId)
- if (node?.type !== 'INSTANCE') return
-
- const previousStrokes = collectStyledStrokeDescendants(ctx, nodeId)
- const previousSources = snapshotChildSources(ctx.graph, nodeId)
- const rootCompId = node.componentId ? getComponentRoot(ctx, node.componentId) : undefined
- const rootComp = rootCompId ? ctx.graph.getNode(rootCompId) : undefined
- for (const childId of Array.from(node.childIds)) ctx.graph.deleteNode(childId)
- const comp = ctx.graph.getNode(compId)
- const updates: Partial<SceneNode> = comp
- ? { ...swappedRootProps(node, comp), componentId: compId }
- : { componentId: compId }
- const previousName = componentInstanceName(ctx, rootComp)
- const nextName = componentInstanceName(ctx, comp)
- if (nextName && previousName && (node.name === previousName || node.name === rootComp?.name)) {
- updates.name = nextName
- }
- ctx.graph.preserveSourceMetadataDuring(() => ctx.graph.updateNode(nodeId, updates))
- if (comp && comp.childIds.length > 0) {
- ctx.graph.populateInstanceChildren(nodeId, compId, 'fig-import')
- indexCloneSubtree(ctx.graph, nodeId, ctx.preComputedClones)
- applyStrokeDescendants(ctx, nodeId, previousStrokes)
- }
- remapRepopulatedChildSources(
- ctx.graph,
- nodeId,
- previousSources,
- ctx.preComputedClones,
- ctx.activeNodeIds
- )
- ctx.swappedInstances.add(nodeId)
- ctx.componentIdRoot.clear()
- candidateCache.delete(ctx)
- componentFindCache.delete(ctx)
-}
diff --git a/packages/fig/src/instance-overrides/scale/layout.ts b/packages/fig/src/instance-overrides/scale/layout.ts
new file mode 100644
index 000000000..05a25da6e
--- /dev/null
+++ b/packages/fig/src/instance-overrides/scale/layout.ts
@@ -0,0 +1,97 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import { LAYOUT_DISTANCE_FIELDS } from '../fields'
+import type { InstanceOccurrence } from '../interpret'
+import { occurrences } from '../occurrence-path'
+import { uniformScaleOf } from '../types'
+import { scaleTextLayout } from './text'
+
+// Distances only: sizing modes, grow factors, and alignment are dimensionless.
+const LAYOUT_DISTANCES = ['stackPadding', ...Object.values(LAYOUT_DISTANCE_FIELDS)] as const
+const VISUAL_LENGTHS = [
+ 'strokeWeight',
+ 'cornerRadius',
+ 'rectangleTopLeftCornerRadius',
+ 'rectangleTopRightCornerRadius',
+ 'rectangleBottomLeftCornerRadius',
+ 'rectangleBottomRightCornerRadius'
+] as const
+const TEXT_LENGTHS = [
+ 'fontSize',
+ 'lineHeight',
+ 'letterSpacing',
+ 'textData',
+ 'derivedTextData'
+] as const
+
+/**
+ * Every field the scaler touches. An instance record declares these in placed space, so
+ * after its expansion is scaled the record's own values are restored verbatim.
+ */
+const SCALED_FIELDS = [
+ ...LAYOUT_DISTANCES,
+ ...VISUAL_LENGTHS,
+ ...TEXT_LENGTHS,
+ 'dashPattern',
+ 'effects',
+ 'size',
+ 'transform'
+] as const
+
+function scaleRawVisualProps(props: NodeChange, factor: number): void {
+ for (const field of VISUAL_LENGTHS) {
+ const value = props[field]
+ if (typeof value === 'number') props[field] = value * factor
+ }
+ if (props.dashPattern) props.dashPattern = props.dashPattern.map((value) => value * factor)
+ if (props.effects)
+ props.effects = props.effects.map((effect) => ({
+ ...effect,
+ offset: effect.offset
+ ? { x: effect.offset.x * factor, y: effect.offset.y * factor }
+ : effect.offset,
+ radius: typeof effect.radius === 'number' ? effect.radius * factor : effect.radius,
+ spread: typeof effect.spread === 'number' ? effect.spread * factor : effect.spread
+ }))
+}
+
+/**
+ * Expansion is in component space; an instance's own NodeChange distances are
+ * already in placed space. Explicit path claims are applied before this stage,
+ * and saved derived bounds afterwards. Nested expansions are normalized first.
+ */
+export function applyInstanceLayoutScale(root: InstanceOccurrence, source: NodeChange): void {
+ const factor = uniformScaleOf(source)
+ if (!Number.isFinite(factor) || factor <= 0) throw new Error('Invalid instance uniform scale')
+ if (factor === 1) return
+ for (const node of occurrences(root)) {
+ node.layoutScale = (node.layoutScale ?? 1) * factor
+ for (const field of Object.keys(node.variableBindingScales ?? {})) {
+ if (node.variableBindingScales && field !== 'opacity' && field !== 'rotation')
+ node.variableBindingScales[field] *= factor
+ }
+ const props = node.properties
+ scaleTextLayout(props, factor)
+ scaleRawVisualProps(props, factor)
+ for (const field of LAYOUT_DISTANCES) {
+ const value = props[field]
+ if (typeof value === 'number') props[field] = value * factor
+ }
+ if (props.size) props.size = { x: props.size.x * factor, y: props.size.y * factor }
+ if (props.transform)
+ props.transform = {
+ ...props.transform,
+ m02: props.transform.m02 * factor,
+ m12: props.transform.m12 * factor
+ }
+ if (node.derivedSize)
+ node.derivedSize = {
+ x: node.derivedSize.x * factor,
+ y: node.derivedSize.y * factor
+ }
+ }
+ for (const field of SCALED_FIELDS) {
+ const value = source[field]
+ if (value !== undefined) Object.assign(root.properties, { [field]: structuredClone(value) })
+ }
+}
diff --git a/packages/fig/src/instance-overrides/scale/text.ts b/packages/fig/src/instance-overrides/scale/text.ts
new file mode 100644
index 000000000..97bf7a1bd
--- /dev/null
+++ b/packages/fig/src/instance-overrides/scale/text.ts
@@ -0,0 +1,36 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { Vector } from '@open-pencil/scene-graph'
+
+const scaledVector = (value: Vector, factor: number): Vector => ({
+ x: value.x * factor,
+ y: value.y * factor
+})
+
+/** Scale positional text data, not font identity or normalized glyph outlines. */
+export function scaleTextLayout(props: NodeChange, factor: number): void {
+ if (props.fontSize !== undefined) props.fontSize *= factor
+ for (const field of ['lineHeight', 'letterSpacing'] as const) {
+ const value = props[field]
+ if (value?.units === 'PIXELS') props[field] = { ...value, value: value.value * factor }
+ }
+ if (props.textData?.styleOverrideTable) {
+ props.textData = structuredClone(props.textData)
+ for (const style of props.textData.styleOverrideTable ?? []) scaleTextLayout(style, factor)
+ }
+ if (!props.derivedTextData) return
+ const derived = structuredClone(props.derivedTextData)
+ if (derived.layoutSize) derived.layoutSize = scaledVector(derived.layoutSize, factor)
+ if (derived.truncatedHeight !== undefined) derived.truncatedHeight *= factor
+ for (const glyph of derived.glyphs ?? []) {
+ glyph.position = scaledVector(glyph.position, factor)
+ glyph.fontSize *= factor
+ }
+ for (const baseline of derived.baselines ?? []) {
+ baseline.position = scaledVector(baseline.position, factor)
+ baseline.width *= factor
+ baseline.lineHeight *= factor
+ baseline.lineAscent *= factor
+ if (baseline.lineY !== undefined) baseline.lineY *= factor
+ }
+ props.derivedTextData = derived
+}
diff --git a/packages/fig/src/instance-overrides/source-children.ts b/packages/fig/src/instance-overrides/source-children.ts
new file mode 100644
index 000000000..493ba3de4
--- /dev/null
+++ b/packages/fig/src/instance-overrides/source-children.ts
@@ -0,0 +1,154 @@
+import { setInstanceOverride, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+import type { InstanceOccurrence } from './interpret'
+import type { MaterializedInstance } from './materialize-instance'
+import { occurrences } from './occurrence-path'
+
+export interface MaterializedComponentOccurrence {
+ occurrence: InstanceOccurrence
+ materialized: MaterializedInstance
+}
+
+export function reconcileOccurrenceStructure(
+ target: InstanceOccurrence,
+ graph: SceneGraph,
+ components: ReadonlyMap<string, MaterializedComponentOccurrence>
+): void {
+ if (target.mainComponentId !== null) {
+ const component = components.get(target.mainComponentId)
+ if (!component) throw new Error(`Missing component occurrence ${target.mainComponentId}`)
+ const liveOrder = new Map(
+ graph.getChildren(component.materialized.root.id).map((node, index) => [node.id, index])
+ )
+ const sourceChildren = new Map(
+ component.occurrence.children.map((child) => [child.sourceId, child])
+ )
+ target.children = target.children
+ .filter((child) => {
+ const source = sourceChildren.get(child.sourceId)
+ const node = source && component.materialized.nodes.get(source)
+ return !!node && liveOrder.has(node.id)
+ })
+ .toSorted((a, b) => {
+ const sourceA = sourceChildren.get(a.sourceId)
+ const sourceB = sourceChildren.get(b.sourceId)
+ const nodeA = sourceA && component.materialized.nodes.get(sourceA)
+ const nodeB = sourceB && component.materialized.nodes.get(sourceB)
+ return (
+ (nodeA ? (liveOrder.get(nodeA.id) ?? 0) : 0) -
+ (nodeB ? (liveOrder.get(nodeB.id) ?? 0) : 0)
+ )
+ })
+ }
+ for (const child of target.children) reconcileOccurrenceStructure(child, graph, components)
+}
+
+/**
+ * Pair each child of a target occurrence with the child of its source occurrence that has
+ * the same source identity. Both sides describe one component's children, so identities
+ * are unique on the source side and every target child has a counterpart.
+ */
+function* pairSourceChildren(
+ target: InstanceOccurrence,
+ source: InstanceOccurrence
+): Generator<[child: InstanceOccurrence, counterpart: InstanceOccurrence]> {
+ const bySource = new Map<string, InstanceOccurrence>()
+ for (const child of source.children) {
+ if (bySource.has(child.sourceId)) throw new Error(`Ambiguous source child ${child.sourceId}`)
+ bySource.set(child.sourceId, child)
+ }
+ for (const child of target.children) {
+ const counterpart = bySource.get(child.sourceId)
+ if (!counterpart) throw new Error(`Missing source child ${child.sourceId}`)
+ yield [child, counterpart]
+ }
+}
+
+/**
+ * Each instance owner addresses descendants in its own component expansion. A nested
+ * instance therefore has both its own correspondence and the outer owner's; a swap ends
+ * the outer owner's descendant scope.
+ */
+export function linkInstanceSourceChildren(
+ root: InstanceOccurrence,
+ materialized: MaterializedInstance,
+ components: ReadonlyMap<string, MaterializedComponentOccurrence>
+): void {
+ const links: Array<{ owner: SceneNode; target: SceneNode; source: SceneNode }> = []
+ const match = (
+ target: InstanceOccurrence,
+ source: InstanceOccurrence,
+ owner: SceneNode,
+ sourceNodes: ReadonlyMap<InstanceOccurrence, SceneNode>
+ ): void => {
+ for (const [child, counterpart] of pairSourceChildren(target, source)) {
+ const targetNode = materialized.nodes.get(child)
+ const sourceNode = sourceNodes.get(counterpart)
+ if (!targetNode || !sourceNode) {
+ throw new Error(`Missing materialized correspondence for ${child.sourceId}`)
+ }
+ links.push({ owner, target: targetNode, source: sourceNode })
+ if (child.mainComponentId === counterpart.mainComponentId) {
+ match(child, counterpart, owner, sourceNodes)
+ }
+ }
+ }
+ for (const current of occurrences(root)) {
+ if (current.mainComponentId === null) continue
+ const component = components.get(current.mainComponentId)
+ const owner = materialized.nodes.get(current)
+ if (!component || !owner) throw new Error(`Missing component ${current.mainComponentId}`)
+ match(current, component.occurrence, owner, component.materialized.nodes)
+ }
+ for (const { owner, target, source } of links) {
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ target.id,
+ 'sourceComponentId',
+ source.id
+ )
+ if (target.type === 'INSTANCE' && target.componentId !== source.componentId) {
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ target.id,
+ 'componentId',
+ target.componentId
+ )
+ }
+ }
+}
+
+/** Match children within one component occurrence, never across instance boundaries. */
+export function mapInstanceSourceChildren(
+ instance: InstanceOccurrence,
+ components: ReadonlyMap<string, MaterializedComponentOccurrence>
+): ReadonlyMap<InstanceOccurrence, string> {
+ const result = new Map<InstanceOccurrence, string>()
+ const matchChildren = (
+ target: InstanceOccurrence,
+ source: InstanceOccurrence,
+ nodes: ReadonlyMap<InstanceOccurrence, SceneNode>
+ ): void => {
+ for (const [child, counterpart] of pairSourceChildren(target, source)) {
+ const node = nodes.get(counterpart)
+ if (!node) throw new Error(`Unmaterialized source child ${counterpart.sourceId}`)
+ result.set(child, node.id)
+ if (child.mainComponentId !== null) expand(child)
+ else matchChildren(child, counterpart, nodes)
+ }
+ }
+ const expand = (target: InstanceOccurrence): void => {
+ if (target.mainComponentId === null) throw new Error('Expected instance occurrence')
+ const component = components.get(target.mainComponentId)
+ if (!component) throw new Error(`Missing component occurrence ${target.mainComponentId}`)
+ matchChildren(target, component.occurrence, component.materialized.nodes)
+ }
+ const visit = (target: InstanceOccurrence): void => {
+ if (target.mainComponentId !== null) expand(target)
+ else for (const child of target.children) visit(child)
+ }
+ visit(instance)
+ return result
+}
diff --git a/packages/fig/src/instance-overrides/source-index.ts b/packages/fig/src/instance-overrides/source-index.ts
new file mode 100644
index 000000000..70cc6fec6
--- /dev/null
+++ b/packages/fig/src/instance-overrides/source-index.ts
@@ -0,0 +1,133 @@
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import { findWithinBoundary, type TreeShape } from './tree'
+
+/** Archive records indexed by GUID, with children in saved order. */
+export interface SourceIndex {
+ readonly sources: ReadonlyMap<string, NodeChange>
+ readonly children: ReadonlyMap<string, readonly NodeChange[]>
+}
+
+/** A record's archive identity, or undefined for the rare record without a GUID. */
+export function idOf(record: NodeChange): string | undefined {
+ return record.guid ? guidToString(record.guid) : undefined
+}
+
+export function parentIdOf(record: NodeChange): string | undefined {
+ return record.parentIndex?.guid ? guidToString(record.parentIndex.guid) : undefined
+}
+
+/** Records by identity, without the child ordering the full index also builds. */
+export function indexRecords(changes: readonly NodeChange[]): Map<string, NodeChange> {
+ const sources = new Map<string, NodeChange>()
+ for (const change of changes) {
+ const id = idOf(change)
+ if (id !== undefined) sources.set(id, change)
+ }
+ return sources
+}
+
+/** Saved sibling order: the fractional position string, compared as text. */
+export function bySavedPosition(a: NodeChange, b: NodeChange): number {
+ const left = a.parentIndex?.position ?? ''
+ const right = b.parentIndex?.position ?? ''
+ if (left === right) return 0
+ return left < right ? -1 : 1
+}
+
+export function createSourceIndex(changes: readonly NodeChange[]): SourceIndex {
+ const sources = new Map<string, NodeChange>()
+ const children = new Map<string, NodeChange[]>()
+ for (const change of changes) {
+ const id = idOf(change)
+ if (id === undefined) continue
+ if (sources.has(id)) throw new Error(`Duplicate source node ${id}`)
+ sources.set(id, change)
+ const parentId = parentIdOf(change)
+ if (parentId === undefined) continue
+ const siblings = children.get(parentId)
+ if (siblings) siblings.push(change)
+ else children.set(parentId, [change])
+ }
+ for (const siblings of children.values()) siblings.sort(bySavedPosition)
+ return { sources, children }
+}
+
+export function sameGuid(left: GUID | undefined, right: GUID): boolean {
+ return left?.sessionID === right.sessionID && left.localID === right.localID
+}
+
+export function readOverrideKey(value: unknown): GUID | undefined {
+ if (!value || typeof value !== 'object' || !('sessionID' in value) || !('localID' in value))
+ return undefined
+ if (typeof value.sessionID !== 'number' || typeof value.localID !== 'number') return undefined
+ return { sessionID: value.sessionID, localID: value.localID }
+}
+
+/** A path segment addresses a record by GUID or by its stable override key. */
+export function recordMatches(record: NodeChange, guid: GUID): boolean {
+ return sameGuid(record.guid, guid) || sameGuid(readOverrideKey(record.overrideKey), guid)
+}
+
+export interface StaticMatch {
+ count: number
+ /** The single matching record, when exactly one exists. */
+ record?: NodeChange
+ /** The direct child whose subtree holds that record. */
+ topChild?: NodeChange
+}
+
+/** Source records as a tree: children by saved order, instances as boundaries. */
+export function recordTree({ children }: SourceIndex): TreeShape<NodeChange> {
+ return {
+ childrenOf: (record) => children.get(idOf(record) ?? '') ?? [],
+ isInstance: (record) => record.symbolData?.symbolID !== undefined
+ }
+}
+
+/**
+ * Find a segment among a record's static descendants, searching through ordinary
+ * containers but never into an instance.
+ */
+export function findStaticSegment(index: SourceIndex, parentId: string, guid: GUID): StaticMatch {
+ const { count, match, top } = findWithinBoundary(
+ index.children.get(parentId) ?? [],
+ recordTree(index),
+ (record) => recordMatches(record, guid)
+ )
+ return { count, record: match, topChild: top }
+}
+
+/** Whether a path resolves in a component's own source tree, following raw instance links. */
+export function resolvesInSourceComponent(
+ index: SourceIndex,
+ componentId: GUID,
+ path: readonly GUID[]
+): boolean {
+ let sourceId = guidToString(componentId)
+ for (const [position, segment] of path.entries()) {
+ const source = index.sources.get(sourceId)
+ if (!source) return false
+ if (position === 0 && recordMatches(source, segment)) continue
+ const { record } = findStaticSegment(index, sourceId, segment)
+ if (!record) return false
+ if (position === path.length - 1) return true
+ if (!record.symbolData?.symbolID) return false
+ sourceId = guidToString(record.symbolData.symbolID)
+ }
+ return false
+}
+
+/** Follow raw symbol references to the component definition an instance ultimately expands. */
+export function terminalComponent(index: SourceIndex, id: string): string {
+ let current = id
+ const seen = new Set<string>()
+ while (!seen.has(current)) {
+ seen.add(current)
+ const record = index.sources.get(current)
+ if (record?.type !== 'INSTANCE' || !record.symbolData?.symbolID) return current
+ current = guidToString(record.symbolData.symbolID)
+ }
+ return current
+}
diff --git a/packages/fig/src/instance-overrides/symbol/overrides.ts b/packages/fig/src/instance-overrides/symbol/overrides.ts
deleted file mode 100644
index 6226ff4ed..000000000
--- a/packages/fig/src/instance-overrides/symbol/overrides.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { hasInstanceOverride } from '@open-pencil/scene-graph'
-
-import { applyOverridePatch } from '../patches'
-import { resolveOverrideTarget } from '../resolve'
-import type { OverrideContext } from '../types'
-import { patchFromSymbolOverride } from './patches'
-
-/**
- * Strips fields from a stored-override patch that were since live-edited
- * (recordInstanceOverride) — reapplying the stale stored value on every
- * lazy-population pass would otherwise silently discard the edit.
- */
-function dropLiveOverriddenFields(
- ctx: OverrideContext,
- targetId: string,
- patch: ReturnType<typeof patchFromSymbolOverride>
-): void {
- if (!patch?.props) return
- const kept = Object.fromEntries(
- Object.entries(patch.props).filter(
- ([field]) => !hasInstanceOverride(ctx.graph, targetId, field)
- )
- )
- patch.props = Object.keys(kept).length > 0 ? (kept as typeof patch.props) : undefined
-}
-
-function isActiveInstance(ctx: OverrideContext, nodeId: string | undefined): nodeId is string {
- return nodeId !== undefined && (!ctx.activeNodeIds || ctx.activeNodeIds.has(nodeId))
-}
-
-function preserveInstanceRootBounds(
- hasRootSize: boolean,
- instanceId: string,
- targetId: string,
- patch: ReturnType<typeof patchFromSymbolOverride>
-): void {
- if (!hasRootSize || targetId !== instanceId || !patch?.props) return
- // Root bounds belong to the instance NodeChange. Figma may repeat the
- // source component size in a root symbol override, but that must not resize
- // the placed instance.
- delete patch.props.width
- delete patch.props.height
-}
-
-/**
- * Apply symbolOverrides from kiwi data.
- *
- * Handles instance swaps (overriddenSymbolID) and property overrides
- * (fills, text, visibility, etc.). Returns the set of directly
- * overridden node IDs (used as seeds for transitive sync).
- */
-export function applySymbolOverrides(ctx: OverrideContext, propertiesOnly = false): Set<string> {
- const overriddenNodes = new Set<string>()
- ctx.componentIdRoot.clear()
-
- for (const [ncId, nc] of ctx.changeMap) {
- if (nc.type !== 'INSTANCE') continue
- const overrides = nc.symbolData?.symbolOverrides
- if (!overrides?.length) continue
-
- const nodeId = ctx.guidToNodeId.get(ncId)
- if (!isActiveInstance(ctx, nodeId)) continue
-
- for (const ov of overrides) {
- const guids = ov.guidPath?.guids
- if (!guids?.length) continue
-
- const targetId = resolveOverrideTarget(ctx, nodeId, guids)
- if (!targetId) continue
-
- if (targetId === nodeId && ctx.kiwiPropertyNodes.has(nodeId)) continue
-
- const patch = patchFromSymbolOverride(ctx, targetId, ov)
- if (!patch) continue
- dropLiveOverriddenFields(ctx, targetId, patch)
- preserveInstanceRootBounds(nc.size !== undefined, nodeId, targetId, patch)
- if (propertiesOnly) patch.swapComponentId = undefined
- if (!patch.swapComponentId && !patch.props) continue
- overriddenNodes.add(targetId)
- applyOverridePatch(ctx, patch)
- }
- }
- return overriddenNodes
-}
diff --git a/packages/fig/src/instance-overrides/symbol/patches.ts b/packages/fig/src/instance-overrides/symbol/patches.ts
deleted file mode 100644
index ad533b51d..000000000
--- a/packages/fig/src/instance-overrides/symbol/patches.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import {
- applyStyleRefsToFields,
- guidToString,
- VARIABLE_BINDING_FIELDS_INVERSE
-} from '@open-pencil/fig/node-change'
-import type { GUID } from '@open-pencil/kiwi/fig/codec'
-
-import type { OverridePatch } from '../patches'
-import type { OverrideContext, SymbolOverride, SymbolOverrideFields } from '../types'
-import { convertOverrideToProps } from './props'
-
-interface AliasRef {
- guid?: GUID
- assetRef?: { key: string; version?: string }
-}
-
-const VARIABLE_RADIUS_FIELDS = new Set([
- 'RECTANGLE_TOP_LEFT_CORNER_RADIUS',
- 'RECTANGLE_TOP_RIGHT_CORNER_RADIUS',
- 'RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS',
- 'RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS'
-])
-
-function assetRefKey(assetRef: { key: string; version?: string }): string {
- return assetRef.version ? `${assetRef.key}@${assetRef.version}` : assetRef.key
-}
-
-function resolveAliasId(alias: AliasRef, assetRefs: Map<string, string>): string | undefined {
- if (alias.guid) return guidToString(alias.guid)
- const assetRef = alias.assetRef
- if (!assetRef?.key) return undefined
- return assetRefs.get(assetRefKey(assetRef)) ?? assetRefs.get(assetRef.key)
-}
-
-function resolveFloatVariable(
- ctx: OverrideContext,
- id: string,
- assetRefs: Map<string, string>,
- depth = 0
-): number | undefined {
- if (depth > 10) return undefined
- const nc = ctx.changeMap.get(id)
- const entry = nc?.variableDataValues?.entries?.[0]
- if (!entry) return undefined
- const value = entry.variableData.value
- if (!value) return undefined
- if (typeof value.floatValue === 'number') return value.floatValue
- const alias = value.alias as AliasRef | undefined
- const aliasId = alias ? resolveAliasId(alias, assetRefs) : undefined
- return aliasId ? resolveFloatVariable(ctx, aliasId, assetRefs, depth + 1) : undefined
-}
-
-function applyVariableRadiusOverrides(
- ctx: OverrideContext,
- fields: SymbolOverrideFields,
- props: ReturnType<typeof convertOverrideToProps>
-): void {
- const entries = fields.variableConsumptionMap?.entries
- if (!entries?.length) return
- const assetRefs = ctx.assetRefToGuid
- for (const entry of entries) {
- const variableField = entry.variableField
- if (!variableField || !VARIABLE_RADIUS_FIELDS.has(variableField)) continue
- const alias = entry.variableData?.value?.alias
- const id = alias ? resolveAliasId(alias, assetRefs) : undefined
- const value = id ? resolveFloatVariable(ctx, id, assetRefs) : undefined
- if (typeof value !== 'number') continue
- const field = VARIABLE_BINDING_FIELDS_INVERSE[variableField]
- if (field === 'topLeftRadius') props.topLeftRadius = value
- else if (field === 'topRightRadius') props.topRightRadius = value
- else if (field === 'bottomRightRadius') props.bottomRightRadius = value
- else if (field === 'bottomLeftRadius') props.bottomLeftRadius = value
- }
-}
-
-export function patchFromSymbolOverride(
- ctx: OverrideContext,
- targetId: string,
- ov: SymbolOverride
-): OverridePatch | null {
- const patch: OverridePatch = { targetId, source: 'symbol-override' }
- if (ov.overriddenSymbolID) {
- const swapGuid = guidToString(ov.overriddenSymbolID)
- patch.swapComponentId = ctx.guidToNodeId.get(swapGuid)
- }
-
- const fields: SymbolOverrideFields = { ...ov }
- delete fields.guidPath
- delete fields.overriddenSymbolID
- delete fields.componentPropAssignments
- if (Object.keys(fields).length > 0) {
- applyStyleRefsToFields(ctx.changeMap, fields)
- const props = convertOverrideToProps(fields)
- applyVariableRadiusOverrides(ctx, fields, props)
- if (Object.keys(props).length > 0) patch.props = props
- }
-
- return patch.swapComponentId || patch.props ? patch : null
-}
diff --git a/packages/fig/src/instance-overrides/symbol/props.ts b/packages/fig/src/instance-overrides/symbol/props.ts
deleted file mode 100644
index 631644f31..000000000
--- a/packages/fig/src/instance-overrides/symbol/props.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import {
- convertFills,
- mapStackSizing,
- mapStackJustify,
- mapStackCounterAlign,
- mapAlignSelf,
- mapTextDecoration,
- convertLineHeight,
- convertLetterSpacing,
- mapArcData,
- importStyleRuns,
- convertStrokes,
- convertEffects,
- extractBoundVariables
-} from '@open-pencil/fig/node-change'
-import type { NodeChange, Paint, Effect as KiwiEffect } from '@open-pencil/kiwi/fig/codec'
-import type { SceneNode, ArcData, TextAutoResize } from '@open-pencil/scene-graph'
-import { styleToWeight } from '@open-pencil/scene-graph'
-import type { Vector } from '@open-pencil/scene-graph/primitives'
-
-function applyOverridePaints(ov: Record<string, unknown>, updates: Partial<SceneNode>): void {
- if (ov.textData != null) {
- const td = ov.textData as { characters?: string }
- if (td.characters != null) updates.text = td.characters
- const runs = importStyleRuns(ov as NodeChange)
- if (runs.length > 0) updates.styleRuns = runs
- }
- if (ov.fillPaints != null) updates.fills = convertFills(ov.fillPaints as Paint[])
- if (ov.strokePaints != null)
- updates.strokes = convertStrokes(
- ov.strokePaints as Paint[],
- ov.strokeWeight as number | undefined,
- ov.strokeAlign as string | undefined
- )
- if (ov.fillPaints != null || ov.strokePaints != null) {
- const bindings = extractBoundVariables(ov as NodeChange)
- if (Object.keys(bindings).length > 0) updates.boundVariables = bindings
- }
- if (ov.effects != null) updates.effects = convertEffects(ov.effects as KiwiEffect[])
- if (ov.visible != null) updates.visible = ov.visible as boolean
- if (ov.opacity != null) updates.opacity = ov.opacity as number
- if (ov.name != null) updates.name = ov.name as string
- if (ov.locked != null) updates.locked = ov.locked as boolean
-}
-
-function applyOverrideGeometry(ov: Record<string, unknown>, updates: Partial<SceneNode>): void {
- if (ov.size != null) {
- const sz = ov.size as Partial<Vector>
- if (sz.x != null) updates.width = sz.x
- if (sz.y != null) updates.height = sz.y
- }
- if (ov.cornerRadius != null) updates.cornerRadius = ov.cornerRadius as number
- if (ov.rectangleTopLeftCornerRadius != null)
- updates.topLeftRadius = ov.rectangleTopLeftCornerRadius as number
- if (ov.rectangleTopRightCornerRadius != null)
- updates.topRightRadius = ov.rectangleTopRightCornerRadius as number
- if (ov.rectangleBottomRightCornerRadius != null)
- updates.bottomRightRadius = ov.rectangleBottomRightCornerRadius as number
- if (ov.rectangleBottomLeftCornerRadius != null)
- updates.bottomLeftRadius = ov.rectangleBottomLeftCornerRadius as number
- if (ov.rectangleCornerRadiiIndependent != null)
- updates.independentCorners = ov.rectangleCornerRadiiIndependent as boolean
- if (ov.arcData != null) updates.arcData = mapArcData(ov.arcData as Partial<ArcData> | undefined)
- if (ov.frameMaskDisabled != null) updates.clipsContent = ov.frameMaskDisabled === false
-}
-
-function applyOverrideLayout(ov: Record<string, unknown>, updates: Partial<SceneNode>): void {
- if (ov.stackSpacing != null) updates.itemSpacing = ov.stackSpacing as number
- if (ov.stackPrimarySizing != null)
- updates.primaryAxisSizing = mapStackSizing(ov.stackPrimarySizing as string)
- if (ov.stackCounterSizing != null)
- updates.counterAxisSizing = mapStackSizing(ov.stackCounterSizing as string)
- if (ov.stackPrimaryAlignItems != null)
- updates.primaryAxisAlign = mapStackJustify(ov.stackPrimaryAlignItems as string)
- if (ov.stackCounterAlignItems != null)
- updates.counterAxisAlign = mapStackCounterAlign(ov.stackCounterAlignItems as string)
- if (ov.stackChildPrimaryGrow != null) updates.layoutGrow = ov.stackChildPrimaryGrow as number
- if (ov.stackChildAlignSelf != null)
- updates.layoutAlignSelf = mapAlignSelf(ov.stackChildAlignSelf as string)
- if (ov.stackPositioning != null)
- updates.layoutPositioning = (ov.stackPositioning as string) === 'ABSOLUTE' ? 'ABSOLUTE' : 'AUTO'
- if (ov.stackVerticalPadding != null) {
- updates.paddingTop = ov.stackVerticalPadding as number
- if (ov.stackPaddingBottom == null) updates.paddingBottom = ov.stackVerticalPadding as number
- }
- if (ov.stackHorizontalPadding != null) {
- updates.paddingLeft = ov.stackHorizontalPadding as number
- if (ov.stackPaddingRight == null) updates.paddingRight = ov.stackHorizontalPadding as number
- }
- if (ov.stackPaddingBottom != null) updates.paddingBottom = ov.stackPaddingBottom as number
- if (ov.stackPaddingRight != null) updates.paddingRight = ov.stackPaddingRight as number
-}
-
-function applyOverrideStrokes(ov: Record<string, unknown>, updates: Partial<SceneNode>): void {
- if (ov.strokeWeight != null && !ov.strokePaints && updates.strokes) {
- for (const stroke of updates.strokes) stroke.weight = ov.strokeWeight as number
- }
- if (ov.strokeAlign != null && updates.strokes) {
- let align: 'INSIDE' | 'OUTSIDE' | 'CENTER' = 'CENTER'
- if (ov.strokeAlign === 'INSIDE') align = 'INSIDE'
- else if (ov.strokeAlign === 'OUTSIDE') align = 'OUTSIDE'
- for (const s of updates.strokes) s.align = align
- }
- if (ov.borderTopWeight != null) updates.borderTopWeight = ov.borderTopWeight as number
- if (ov.borderRightWeight != null) updates.borderRightWeight = ov.borderRightWeight as number
- if (ov.borderBottomWeight != null) updates.borderBottomWeight = ov.borderBottomWeight as number
- if (ov.borderLeftWeight != null) updates.borderLeftWeight = ov.borderLeftWeight as number
- if (ov.borderStrokeWeightsIndependent != null)
- updates.independentStrokeWeights = ov.borderStrokeWeightsIndependent as boolean
-}
-
-function applyOverrideText(ov: Record<string, unknown>, updates: Partial<SceneNode>): void {
- if (ov.fontName != null) {
- const fn = ov.fontName as { family?: string; style?: string }
- if (fn.family) updates.fontFamily = fn.family
- if (fn.style) {
- updates.fontWeight = styleToWeight(fn.style)
- updates.italic = fn.style.toLowerCase().includes('italic')
- }
- }
- if (ov.fontSize != null) updates.fontSize = ov.fontSize as number
- if (ov.textAlignHorizontal != null)
- updates.textAlignHorizontal = ov.textAlignHorizontal as SceneNode['textAlignHorizontal']
- if (ov.textAutoResize != null) updates.textAutoResize = ov.textAutoResize as TextAutoResize
- if (ov.lineHeight != null)
- updates.lineHeight = convertLineHeight(
- ov.lineHeight as NodeChange['lineHeight'],
- ov.fontSize as number | undefined
- )
- if (ov.letterSpacing != null)
- updates.letterSpacing = convertLetterSpacing(
- ov.letterSpacing as NodeChange['letterSpacing'],
- ov.fontSize as number | undefined
- )
- if (ov.maxLines != null) updates.maxLines = ov.maxLines as number | null
- if (ov.textTruncation != null)
- updates.textTruncation = (ov.textTruncation as string) === 'ENDING' ? 'ENDING' : 'DISABLED'
- if (ov.textDecoration != null)
- updates.textDecoration = mapTextDecoration(ov.textDecoration as string)
-}
-
-export function convertOverrideToProps(ov: Record<string, unknown>): Partial<SceneNode> {
- const updates: Partial<SceneNode> = {}
- applyOverridePaints(ov, updates)
- applyOverrideGeometry(ov, updates)
- applyOverrideLayout(ov, updates)
- applyOverrideStrokes(ov, updates)
- applyOverrideText(ov, updates)
- return updates
-}
diff --git a/packages/fig/src/instance-overrides/sync/clone-update.ts b/packages/fig/src/instance-overrides/sync/clone-update.ts
deleted file mode 100644
index 3eacdaf77..000000000
--- a/packages/fig/src/instance-overrides/sync/clone-update.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { copyInstanceComponentProps, type SceneNode } from '@open-pencil/scene-graph'
-
-export function cloneInstanceUpdate(
- source: SceneNode,
- componentId: string | null,
- extra: Partial<SceneNode> = {}
-): Partial<SceneNode> {
- return {
- ...copyInstanceComponentProps(source),
- componentId,
- derivedLayout: source.derivedLayout ? { ...source.derivedLayout } : null,
- ...extra
- }
-}
diff --git a/packages/fig/src/instance-overrides/sync/clones.ts b/packages/fig/src/instance-overrides/sync/clones.ts
deleted file mode 100644
index c492fcf92..000000000
--- a/packages/fig/src/instance-overrides/sync/clones.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-
-import type { ProtectionMap } from '../patches'
-import { overrideCandidates } from '../utils'
-import { cloneInstanceUpdate } from './clone-update'
-import { syncNodeProps } from './fields'
-import { indexCloneSubtree, remapRepopulatedChildSources, snapshotChildSources } from './sources'
-
-export function recloneChildren(
- graph: SceneGraph,
- srcChildId: string,
- tgtNode: SceneNode,
- swappedInstances: Set<string>,
- protections?: ProtectionMap,
- cloneSources?: Map<string, string[]>,
- activeNodeIds?: Set<string>
-): void {
- const srcChild = graph.getNode(srcChildId)
- if (!srcChild) return
- const effectiveCloneSources = cloneSources ?? buildClonesMap(graph, activeNodeIds)
-
- const previousSources = snapshotChildSources(graph, tgtNode.id)
- for (const childId of Array.from(tgtNode.childIds)) graph.deleteNode(childId)
- graph.updateNode(
- tgtNode.id,
- cloneInstanceUpdate(srcChild, srcChild.componentId, { name: srcChild.name })
- )
- syncNodeProps(graph, srcChild, tgtNode, protections)
- if (srcChild.childIds.length > 0) {
- graph.populateInstanceChildren(tgtNode.id, srcChildId, 'fig-import')
- indexCloneSubtree(graph, tgtNode.id, effectiveCloneSources)
- }
- remapRepopulatedChildSources(
- graph,
- tgtNode.id,
- previousSources,
- effectiveCloneSources,
- activeNodeIds
- )
- swappedInstances.add(tgtNode.id)
-}
-
-export function syncChildrenDeep(
- graph: SceneGraph,
- sourceId: string,
- targetId: string,
- swappedInstances: Set<string>,
- skip?: Set<string>,
- protections?: ProtectionMap,
- cloneSources?: Map<string, string[]>,
- activeNodeIds?: Set<string>
-): void {
- const src = graph.getNode(sourceId)
- const tgt = graph.getNode(targetId)
- if (!src || !tgt) return
- const effectiveCloneSources = cloneSources ?? buildClonesMap(graph, activeNodeIds)
- const len = Math.min(src.childIds.length, tgt.childIds.length)
- for (let i = 0; i < len; i++) {
- if (skip?.has(tgt.childIds[i])) continue
- const srcNode = graph.getNode(src.childIds[i])
- const tgtNode = graph.getNode(tgt.childIds[i])
- if (!srcNode || !tgtNode || srcNode.type !== tgtNode.type) continue
-
- if (srcNode.type === 'INSTANCE' && srcNode.componentId !== tgtNode.componentId) {
- recloneChildren(
- graph,
- src.childIds[i],
- tgtNode,
- swappedInstances,
- protections,
- effectiveCloneSources,
- activeNodeIds
- )
- continue
- }
-
- syncNodeProps(graph, srcNode, tgtNode, protections)
- syncChildrenDeep(
- graph,
- src.childIds[i],
- tgt.childIds[i],
- swappedInstances,
- skip,
- protections,
- effectiveCloneSources,
- activeNodeIds
- )
- }
-}
-
-export function buildClonesMap(
- graph: SceneGraph,
- activeNodeIds?: Set<string>
-): Map<string, string[]> {
- const clonesOf = new Map<string, string[]>()
- for (const node of overrideCandidates(graph, activeNodeIds)) {
- if (!node.componentId) continue
- let arr = clonesOf.get(node.componentId)
- if (!arr) {
- arr = []
- clonesOf.set(node.componentId, arr)
- }
- arr.push(node.id)
- }
- return clonesOf
-}
diff --git a/packages/fig/src/instance-overrides/sync/fields.ts b/packages/fig/src/instance-overrides/sync/fields.ts
deleted file mode 100644
index 2fa2ce2a1..000000000
--- a/packages/fig/src/instance-overrides/sync/fields.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-import { omit } from 'es-toolkit/object'
-
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import {
- copyEffects,
- copyFills,
- copyStrokes,
- copyStyleRuns,
- hasSameCopySource,
- markCopySource
-} from '@open-pencil/scene-graph/copy'
-
-import { isFieldProtected } from '../patches'
-import type { ProtectedField, ProtectionMap } from '../patches'
-
-function canSync(
- protections: ProtectionMap | undefined,
- targetId: string,
- field: ProtectedField
-): boolean {
- return !isFieldProtected(protections, targetId, field)
-}
-
-type SyncFn = (
- source: SceneNode,
- target: SceneNode,
- updates: Partial<SceneNode>,
- protections?: ProtectionMap
-) => void
-
-type DirectSyncKey = 'text' | 'visible' | 'opacity' | 'locked' | 'layoutGrow' | 'textAutoResize'
-type ScalarBindingKey = 'opacity'
-type CopiedSyncKey = 'fills' | 'strokes' | 'effects' | 'styleRuns'
-
-function assignDirectUpdate(
- key: DirectSyncKey,
- source: SceneNode,
- updates: Partial<SceneNode>
-): void {
- switch (key) {
- case 'text':
- updates.text = source.text
- break
- case 'visible':
- updates.visible = source.visible
- break
- case 'opacity':
- updates.opacity = source.opacity
- break
- case 'locked':
- updates.locked = source.locked
- break
- case 'layoutGrow':
- updates.layoutGrow = source.layoutGrow
- break
- case 'textAutoResize':
- updates.textAutoResize = source.textAutoResize
- break
- }
-}
-
-function directSync(key: DirectSyncKey, field: ProtectedField): SyncFn {
- return (source, target, updates, protections) => {
- if (source[key] !== target[key] && canSync(protections, target.id, field)) {
- assignDirectUpdate(key, source, updates)
- }
- }
-}
-
-const DIRECT_SYNCERS: SyncFn[] = [
- directSync('text', 'text'),
- directSync('visible', 'visible'),
- directSync('opacity', 'opacity'),
- directSync('locked', 'locked'),
- directSync('layoutGrow', 'layoutGrow'),
- directSync('textAutoResize', 'textAutoResize')
-]
-
-function assignCopiedUpdate(
- key: CopiedSyncKey,
- source: SceneNode,
- updates: Partial<SceneNode>
-): void {
- switch (key) {
- case 'fills':
- updates.fills = markCopySource(source.fills, copyFills(source.fills))
- break
- case 'strokes':
- updates.strokes = markCopySource(source.strokes, copyStrokes(source.strokes))
- break
- case 'effects':
- updates.effects = markCopySource(source.effects, copyEffects(source.effects))
- break
- case 'styleRuns':
- updates.styleRuns = markCopySource(source.styleRuns, copyStyleRuns(source.styleRuns))
- break
- }
-}
-
-function syncPaintBindings(
- key: 'fills' | 'strokes',
- source: SceneNode,
- target: SceneNode,
- updates: Partial<SceneNode>
-): void {
- const prefix = `${key}/`
- const currentBindings = updates.boundVariables ?? target.boundVariables
- const paintFields = Object.keys(currentBindings).filter((field) => field.startsWith(prefix))
- const bindings: Record<string, string> = omit(currentBindings, paintFields)
- for (const [field, variableId] of Object.entries(source.boundVariables)) {
- if (field.startsWith(prefix)) bindings[field] = variableId
- }
- updates.boundVariables = bindings
-}
-
-function copiedSync(key: CopiedSyncKey, field: ProtectedField): SyncFn {
- return (source, target, updates, protections) => {
- if (!hasSameCopySource(source[key], target[key]) && canSync(protections, target.id, field)) {
- assignCopiedUpdate(key, source, updates)
- if (key === 'fills' || key === 'strokes') syncPaintBindings(key, source, target, updates)
- }
- }
-}
-
-const COPIED_SYNCERS: SyncFn[] = [
- copiedSync('fills', 'fills'),
- copiedSync('strokes', 'strokes'),
- copiedSync('effects', 'effects'),
- copiedSync('styleRuns', 'styleRuns')
-]
-
-function syncScalarBinding(
- key: ScalarBindingKey,
- source: SceneNode,
- target: SceneNode,
- updates: Partial<SceneNode>
-): void {
- const sourceVariableId = source.boundVariables[key]
- const targetVariableId = target.boundVariables[key]
- if (targetVariableId === sourceVariableId) return
- const bindings = { ...(updates.boundVariables ?? target.boundVariables) }
- if (sourceVariableId) bindings[key] = sourceVariableId
- updates.boundVariables = sourceVariableId ? bindings : omit(bindings, [key])
-}
-
-function syncFields(
- source: SceneNode,
- target: SceneNode,
- updates: Partial<SceneNode>,
- protections?: ProtectionMap
-): void {
- for (const sync of DIRECT_SYNCERS) sync(source, target, updates, protections)
- for (const sync of COPIED_SYNCERS) sync(source, target, updates, protections)
- syncScalarBinding('opacity', source, target, updates)
-}
-
-export function syncNodeProps(
- graph: SceneGraph,
- source: SceneNode,
- target: SceneNode,
- protections?: ProtectionMap
-): void {
- const updates: Partial<SceneNode> = {}
- syncFields(source, target, updates, protections)
- if (Object.keys(updates).length > 0) graph.updateNode(target.id, updates)
-}
diff --git a/packages/fig/src/instance-overrides/sync/index.ts b/packages/fig/src/instance-overrides/sync/index.ts
deleted file mode 100644
index ec8325771..000000000
--- a/packages/fig/src/instance-overrides/sync/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export { syncNodeProps } from './fields'
-export { buildClonesMap, recloneChildren, syncChildrenDeep } from './clones'
-export { propagateNodePropsTransitively, propagateOverridesTransitively } from './propagate'
diff --git a/packages/fig/src/instance-overrides/sync/propagate.ts b/packages/fig/src/instance-overrides/sync/propagate.ts
deleted file mode 100644
index fe321cf5e..000000000
--- a/packages/fig/src/instance-overrides/sync/propagate.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-import type { SceneGraph } from '@open-pencil/scene-graph'
-
-import { isFieldProtected, type ProtectionMap } from '../patches'
-import { buildClonesMap, syncChildrenDeep } from './clones'
-import { syncNodeProps } from './fields'
-import { indexCloneSubtree, remapRepopulatedChildSources, snapshotChildSources } from './sources'
-
-function expandSeedsToParents(graph: SceneGraph, seeds: Set<string>): Set<string> {
- const expanded = new Set(seeds)
- for (const seedId of seeds) {
- let cur = graph.getNode(seedId)
- while (cur?.parentId) {
- const parent = graph.getNode(cur.parentId)
- if (!parent) break
- if (parent.type === 'INSTANCE' || parent.type === 'COMPONENT') expanded.add(parent.id)
- cur = parent
- }
- }
- return expanded
-}
-
-function buildNeedsSyncSet(
- expandedSeeds: Set<string>,
- clonesOf: Map<string, string[]>
-): Set<string> {
- const needsSync = new Set<string>()
- const queue = [...expandedSeeds]
- for (let id = queue.pop(); id !== undefined; id = queue.pop()) {
- const clones = clonesOf.get(id)
- if (!clones) continue
- for (const cloneId of clones) {
- if (needsSync.has(cloneId)) continue
- needsSync.add(cloneId)
- queue.push(cloneId)
- }
- }
- return needsSync
-}
-
-interface NodePropPropagationEntry {
- lineageId: string
- sourceId: string
-}
-
-function mergeCloneLineage(
- current: Map<string, string[]>,
- preComputed?: Map<string, string[]>
-): Map<string, string[]> {
- if (!preComputed) return current
- const merged = new Map<string, string[]>()
- for (const source of [preComputed, current]) {
- for (const [sourceId, cloneIds] of source) {
- const existing = merged.get(sourceId)
- if (existing) {
- for (const cloneId of cloneIds) {
- if (!existing.includes(cloneId)) existing.push(cloneId)
- }
- } else {
- merged.set(sourceId, [...cloneIds])
- }
- }
- }
- return merged
-}
-
-export function propagateNodePropsTransitively(
- graph: SceneGraph,
- seeds: Set<string>,
- activeNodeIds?: Set<string>,
- protections?: ProtectionMap,
- preComputedClones?: Map<string, string[]>
-): void {
- if (seeds.size === 0) return
-
- const clonesOf = mergeCloneLineage(buildClonesMap(graph, activeNodeIds), preComputedClones)
- const visited = new Set(seeds)
- const queue: NodePropPropagationEntry[] = [...seeds].map((id) => ({
- lineageId: id,
- sourceId: id
- }))
- let index = 0
- while (index < queue.length) {
- const { lineageId, sourceId } = queue[index]
- index++
- const source = graph.getNode(sourceId)
- if (!source) continue
- for (const cloneId of clonesOf.get(lineageId) ?? []) {
- if (visited.has(cloneId)) continue
- visited.add(cloneId)
- const clone = graph.getNode(cloneId)
- if (clone) syncNodeProps(graph, source, clone, protections)
- queue.push({ lineageId: cloneId, sourceId: clone?.id ?? sourceId })
- }
- }
-}
-
-export function propagateOverridesTransitively(
- graph: SceneGraph,
- seeds: Set<string>,
- swappedInstances: Set<string>,
- componentIdRoot: Map<string, string>,
- protect?: Set<string>,
- activeNodeIds?: Set<string>,
- protections?: ProtectionMap
-): void {
- if (seeds.size === 0) return
-
- componentIdRoot.clear()
- const clonesOf = buildClonesMap(graph, activeNodeIds)
- const expandedSeeds = expandSeedsToParents(graph, seeds)
- const needsSync = buildNeedsSyncSet(expandedSeeds, clonesOf)
- const skip = protect && protect.size > 0 ? new Set([...seeds, ...protect]) : seeds
-
- const visited = new Set<string>()
- const syncQueue = [...expandedSeeds]
- let index = 0
- while (index < syncQueue.length) {
- const sourceId = syncQueue[index]
- index++
- const clones = clonesOf.get(sourceId)
- if (!clones) continue
- const source = graph.getNode(sourceId)
- if (!source) continue
-
- for (const cloneId of clones) {
- if (!needsSync.has(cloneId) || visited.has(cloneId)) continue
- visited.add(cloneId)
- const node = graph.getNode(cloneId)
- if (!node) continue
-
- if (skip.has(cloneId)) {
- // A directly overridden clone may still inherit effective text from an
- // overridden source. Respect its own text override when present.
- if (
- source.type === 'TEXT' &&
- node.type === 'TEXT' &&
- !isFieldProtected(protections, node.id, 'text')
- ) {
- graph.updateNode(node.id, { text: source.text })
- }
- syncQueue.push(cloneId)
- continue
- }
-
- syncNodeProps(graph, source, node, protections)
- if (source.childIds.length !== node.childIds.length) {
- const previousSources = snapshotChildSources(graph, node.id)
- for (const childId of Array.from(node.childIds)) graph.deleteNode(childId)
- if (source.childIds.length > 0) {
- graph.populateInstanceChildren(node.id, sourceId, 'fig-import')
- indexCloneSubtree(graph, node.id, clonesOf)
- }
- remapRepopulatedChildSources(graph, node.id, previousSources, clonesOf, activeNodeIds)
- } else if (source.childIds.length > 0 && node.childIds.length > 0) {
- syncChildrenDeep(
- graph,
- sourceId,
- node.id,
- swappedInstances,
- skip,
- protections,
- clonesOf,
- activeNodeIds
- )
- }
- syncQueue.push(cloneId)
- }
- }
-}
diff --git a/packages/fig/src/instance-overrides/sync/sources.ts b/packages/fig/src/instance-overrides/sync/sources.ts
deleted file mode 100644
index cd2253cc8..000000000
--- a/packages/fig/src/instance-overrides/sync/sources.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-
-import { overrideCandidates } from '../utils'
-import { cloneInstanceUpdate } from './clone-update'
-
-interface ChildSourceSnapshot {
- id: string
- path: number[]
- type: SceneNode['type']
-}
-
-const refreshedCloneSourceMaps = new WeakSet<Map<string, string[]>>()
-const cloneSourceIdCaches = new WeakMap<Map<string, string[]>, Map<string, Set<string>>>()
-
-function cloneSourceIds(cloneSources: Map<string, string[]>): Map<string, Set<string>> {
- let cached = cloneSourceIdCaches.get(cloneSources)
- if (!cached) {
- cached = new Map([...cloneSources].map(([sourceId, cloneIds]) => [sourceId, new Set(cloneIds)]))
- cloneSourceIdCaches.set(cloneSources, cached)
- }
- return cached
-}
-
-// SceneGraph.instanceIndex contains INSTANCE nodes only, while generated text,
-// frame, and vector descendants also use componentId as clone provenance.
-function refreshCloneSources(
- graph: SceneGraph,
- cloneSources: Map<string, string[]>,
- activeNodeIds?: Set<string>
-): void {
- if (refreshedCloneSourceMaps.has(cloneSources)) return
- const knownIds = cloneSourceIds(cloneSources)
- for (const node of overrideCandidates(graph, activeNodeIds)) {
- if (!node.componentId) continue
- let known = knownIds.get(node.componentId)
- if (!known) {
- known = new Set()
- knownIds.set(node.componentId, known)
- cloneSources.set(node.componentId, [])
- }
- if (known.has(node.id)) continue
- known.add(node.id)
- cloneSources.get(node.componentId)?.push(node.id)
- }
- refreshedCloneSourceMaps.add(cloneSources)
-}
-
-export function indexCloneNodes(
- graph: SceneGraph,
- nodeIds: Iterable<string>,
- cloneSources: Map<string, string[]>
-): void {
- const knownIds = cloneSourceIds(cloneSources)
- for (const nodeId of nodeIds) {
- const node = graph.getNode(nodeId)
- if (!node?.componentId) continue
- let known = knownIds.get(node.componentId)
- if (!known) {
- known = new Set()
- knownIds.set(node.componentId, known)
- }
- if (known.has(node.id)) continue
- known.add(node.id)
- const clones = cloneSources.get(node.componentId)
- if (clones) clones.push(node.id)
- else cloneSources.set(node.componentId, [node.id])
- }
-}
-
-export function indexCloneSubtree(
- graph: SceneGraph,
- rootId: string,
- cloneSources: Map<string, string[]>
-): void {
- const nodeIds: string[] = []
- const queue = [rootId]
- let index = 0
- while (index < queue.length) {
- const node = graph.getNode(queue[index])
- index++
- if (!node) continue
- nodeIds.push(node.id)
- queue.push(...node.childIds)
- }
- indexCloneNodes(graph, nodeIds, cloneSources)
-}
-
-/** Capture clone-source identities by path before a populated branch is replaced. */
-export function snapshotChildSources(graph: SceneGraph, parentId: string): ChildSourceSnapshot[] {
- const result: ChildSourceSnapshot[] = []
- const parent = graph.getNode(parentId)
- if (!parent) return result
-
- const visit = (nodeId: string, path: number[]) => {
- const node = graph.getNode(nodeId)
- if (!node) return
- result.push({ id: node.id, path, type: node.type })
- node.childIds.forEach((childId, index) => visit(childId, [...path, index]))
- }
- parent.childIds.forEach((childId, index) => visit(childId, [index]))
- return result
-}
-
-function resolveChildPath(graph: SceneGraph, parentId: string, path: number[]): SceneNode | null {
- let node = graph.getNode(parentId)
- if (!node) return null
- for (const index of path) {
- const childId = node.childIds[index]
- if (!childId) return null
- node = graph.getNode(childId)
- if (!node) return null
- }
- return node
-}
-
-function cloneIdsForReplacement(
- graph: SceneGraph,
- previousId: string,
- replacementId: string,
- cloneSources?: Map<string, string[]>
-): Set<string> {
- return new Set([
- ...(cloneSources?.get(previousId) ?? []),
- ...(cloneSources?.get(replacementId) ?? []),
- ...(graph.instanceIndex.get(previousId) ?? []),
- ...(graph.instanceIndex.get(replacementId) ?? [])
- ])
-}
-
-function indexReplacementClone(
- cloneSources: Map<string, string[]> | undefined,
- replacementId: string,
- cloneId: string
-): void {
- if (!cloneSources) return
- const sourceIds = cloneSourceIds(cloneSources)
- let known = sourceIds.get(replacementId)
- if (!known) {
- known = new Set()
- sourceIds.set(replacementId, known)
- }
- if (known.has(cloneId)) return
- known.add(cloneId)
-
- let replacements = cloneSources.get(replacementId)
- if (!replacements) {
- replacements = []
- cloneSources.set(replacementId, replacements)
- }
- replacements.push(cloneId)
-}
-
-/**
- * Redirect descendants that cloned the removed branch to its structural
- * replacements. Without this, deep instances keep componentId references to
- * deleted nodes and miss later text, visibility, and geometry synchronization.
- */
-export function remapRepopulatedChildSources(
- graph: SceneGraph,
- parentId: string,
- previousSources: ChildSourceSnapshot[],
- cloneSources?: Map<string, string[]>,
- activeNodeIds?: Set<string>
-): void {
- if (cloneSources) refreshCloneSources(graph, cloneSources, activeNodeIds)
- for (const previous of previousSources) {
- const replacement = resolveChildPath(graph, parentId, previous.path)
- if (!replacement || replacement.type !== previous.type) continue
- const cloneIds = cloneIdsForReplacement(graph, previous.id, replacement.id, cloneSources)
- for (const cloneId of cloneIds) {
- const clone = graph.getNode(cloneId)
- if (clone?.componentId !== previous.id && clone?.componentId !== replacement.id) {
- continue
- }
- graph.updateNode(cloneId, cloneInstanceUpdate(replacement, replacement.id))
- indexReplacementClone(cloneSources, replacement.id, cloneId)
- }
- }
-}
diff --git a/packages/fig/src/instance-overrides/text-provenance.ts b/packages/fig/src/instance-overrides/text-provenance.ts
new file mode 100644
index 000000000..8cca3dbc4
--- /dev/null
+++ b/packages/fig/src/instance-overrides/text-provenance.ts
@@ -0,0 +1,39 @@
+import { isEqual } from 'es-toolkit/predicate'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const SHAPING_FIELDS = [
+ 'fontSize',
+ 'fontName',
+ 'fontVariations',
+ 'letterSpacing',
+ 'lineHeight',
+ 'textCase',
+ 'textAlignHorizontal',
+ 'textAlignVertical',
+ 'textAutoResize',
+ 'styleIdForText',
+ 'fontVariantCommonLigatures',
+ 'fontVariantContextualLigatures'
+] as const
+
+/** Drop source glyph caches only when a patch changes shaping and supplies no replacement. */
+export function invalidateInheritedTextData(
+ source: NodeChange,
+ patch: Record<string, unknown>
+): void {
+ if ('derivedTextData' in patch) return
+ const text = patch.textData as NodeChange['textData']
+ const changedText =
+ text !== undefined &&
+ Object.entries(text).some(
+ ([field, value]) =>
+ !isEqual(value, source.textData?.[field as keyof NonNullable<NodeChange['textData']>])
+ )
+ if (
+ changedText ||
+ SHAPING_FIELDS.some((field) => field in patch && !isEqual(source[field], patch[field]))
+ ) {
+ source.derivedTextData = undefined
+ }
+}
diff --git a/packages/fig/src/instance-overrides/tree.ts b/packages/fig/src/instance-overrides/tree.ts
new file mode 100644
index 000000000..825ba45f2
--- /dev/null
+++ b/packages/fig/src/instance-overrides/tree.ts
@@ -0,0 +1,45 @@
+/**
+ * Tree traversal shared by source records and occurrences. Both trees have the same one
+ * rule that matters for addressing: a search may pass through ordinary containers but never
+ * implicitly into an instance, whose contents belong to another owner's scope.
+ */
+export interface TreeShape<T> {
+ childrenOf(node: T): readonly T[]
+ isInstance(node: T): boolean
+}
+
+export interface BoundedMatch<T> {
+ count: number
+ /** The single match, when exactly one exists. */
+ match?: T
+ /** The root-level node whose subtree holds that match. */
+ top?: T
+}
+
+/**
+ * Find nodes below `roots` through ordinary containers, never past an instance boundary.
+ * A matched node ends its branch: what lies inside it is addressed by a further segment.
+ */
+export function findWithinBoundary<T>(
+ roots: readonly T[],
+ shape: TreeShape<T>,
+ matches: (node: T) => boolean
+): BoundedMatch<T> {
+ const found: { match: T; top: T }[] = []
+ const visit = (node: T, top: T): void => {
+ if (matches(node)) {
+ found.push({ match: node, top })
+ return
+ }
+ if (shape.isInstance(node)) return
+ for (const child of shape.childrenOf(node)) visit(child, top)
+ }
+ for (const root of roots) visit(root, root)
+ return found.length === 1 ? { count: 1, ...found[0] } : { count: found.length }
+}
+
+/** Every node below and including `root`, parents before children, in child order. */
+export function* descendants<T>(root: T, childrenOf: (node: T) => readonly T[]): Generator<T> {
+ yield root
+ for (const child of childrenOf(root)) yield* descendants(child, childrenOf)
+}
diff --git a/packages/fig/src/instance-overrides/types.ts b/packages/fig/src/instance-overrides/types.ts
index 1bdcf06d3..54cdd8f68 100644
--- a/packages/fig/src/instance-overrides/types.ts
+++ b/packages/fig/src/instance-overrides/types.ts
@@ -1,9 +1,6 @@
import type { GUID, NodeChange, VariableConsumptionEntry } from '@open-pencil/kiwi/fig/codec'
-import type { SceneGraph } from '@open-pencil/scene-graph'
import type { Matrix, Vector } from '@open-pencil/scene-graph/primitives'
-import type { ProtectionMap } from './patches'
-
export interface VariableConsumptionMapFields {
variableConsumptionMap?: { entries?: VariableConsumptionEntry[] }
[key: string]: unknown
@@ -15,13 +12,36 @@ export interface SymbolOverride extends VariableConsumptionMapFields {
componentPropAssignments?: ComponentPropAssignment[]
}
-export type SymbolOverrideFields = VariableConsumptionMapFields
-
export interface SymbolData {
+ uniformScaleFactor?: number
symbolID?: GUID
symbolOverrides?: SymbolOverride[]
}
+/** The Kiwi codec types only `symbolID`; the remaining symbol fields are read through here. */
+export function symbolDataOf(record: NodeChange): SymbolData | undefined {
+ return record.symbolData as SymbolData | undefined
+}
+
+export function symbolOverridesOf(record: NodeChange): readonly SymbolOverride[] {
+ return symbolDataOf(record)?.symbolOverrides ?? []
+}
+
+export function uniformScaleOf(record: NodeChange): number {
+ return symbolDataOf(record)?.uniformScaleFactor ?? 1
+}
+
+/** A record's saved override payloads are partial records; visit the record and all of them. */
+export function forEachOverrideRecord(
+ record: NodeChange,
+ visit: (record: NodeChange, override?: SymbolOverride) => void,
+ override?: SymbolOverride
+): void {
+ visit(record, override)
+ for (const nested of symbolOverridesOf(record))
+ forEachOverrideRecord(nested as NodeChange, visit, nested)
+}
+
export interface ComponentPropRef {
defID?: GUID
componentPropNodeField: string
@@ -69,61 +89,3 @@ export interface ComponentPropDef {
initialValue?: ComponentPropValue
type?: number
}
-
-export interface InstanceNodeChange {
- type?: string
- name?: string
- guid?: GUID
- parentIndex?: { guid?: GUID }
- transform?: Matrix
- size?: Vector
- overrideKey?: GUID
- symbolData?: SymbolData
- componentPropRefs?: ComponentPropRef[]
- componentPropAssignments?: ComponentPropAssignment[]
- componentPropDefs?: ComponentPropDef[]
- styleType?: string
- fillPaints?: NodeChange['fillPaints']
- strokePaints?: NodeChange['strokePaints']
- fillGeometry?: NodeChange['fillGeometry']
- strokeGeometry?: NodeChange['strokeGeometry']
- strokeWeight?: number
- derivedSymbolData?: DerivedSymbolOverride[]
- key?: string
- version?: string
- userFacingVersion?: string
- variableDataValues?: NodeChange['variableDataValues']
-}
-
-/**
- * Shared state for override resolution.
- *
- * Built once in `populateAndApplyOverrides` and threaded through all
- * sub-functions. Avoids closure-based coupling (a single 700-line
- * function) while keeping the shared maps accessible.
- */
-export interface OverrideContext {
- graph: SceneGraph
- changeMap: Map<string, InstanceNodeChange>
- guidToNodeId: Map<string, string>
- blobs: Uint8Array[]
-
- overrideKeyToGuid: Map<string, string>
- assetRefToGuid: Map<string, string>
- nodeIdToGuid: Map<string, string>
- propDefaults: Map<string, ComponentPropValue>
- propNames: Map<string, string>
- componentPropRefsMap?: Map<string, ComponentPropRef[]>
- componentPropAssignmentsMap?: Map<string, ComponentPropAssignment[]>
- preComputedRoot: Map<string, string>
- preComputedClones: Map<string, string[]>
- componentIdRoot: Map<string, string>
- swappedInstances: Set<string>
- protectedFields: ProtectionMap
- /** Nodes whose kiwi NC has explicit property values (cornerRadius, visibility, etc.) */
- kiwiPropertyNodes: Set<string>
- /** Nodes whose Figma-derived geometry should not be overwritten by clone propagation. */
- geometryOverrideNodes: Set<string>
- /** When set, apply/populate expensive instance work only inside these already-imported nodes. */
- activeNodeIds?: Set<string>
-}
diff --git a/packages/fig/src/instance-overrides/utils.ts b/packages/fig/src/instance-overrides/utils.ts
deleted file mode 100644
index d183c35dd..000000000
--- a/packages/fig/src/instance-overrides/utils.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-
-export function* overrideCandidates(
- graph: SceneGraph,
- activeNodeIds?: Set<string>
-): Iterable<SceneNode> {
- if (!activeNodeIds) {
- yield* graph.getAllNodes()
- return
- }
- for (const id of activeNodeIds) {
- const node = graph.getNode(id)
- if (node) yield node
- }
-}
diff --git a/packages/fig/src/node-change/clone.ts b/packages/fig/src/node-change/clone.ts
new file mode 100644
index 000000000..13cc891f1
--- /dev/null
+++ b/packages/fig/src/node-change/clone.ts
@@ -0,0 +1,24 @@
+/** Plain Kiwi data: an object literal, so its own keys can be copied directly. */
+function isPlainData(value: object): value is Record<string, unknown> {
+ return Object.getPrototypeOf(value) === Object.prototype
+}
+
+function cloneValue(value: unknown): unknown {
+ if (value === null || typeof value !== 'object') return value
+ if (Array.isArray(value)) return value.map((entry) => cloneValue(entry))
+ // Byte buffers and anything else that is not plain data keep the structured algorithm.
+ if (!isPlainData(value)) return structuredClone(value)
+ const copy: Record<string, unknown> = {}
+ for (const key of Object.keys(value)) copy[key] = cloneValue(value[key])
+ return copy
+}
+
+/**
+ * Deep-copy an archive record. The interpreter owes every occurrence a payload that shares
+ * no mutable data with the archive, and records are plain Kiwi data, so copying them
+ * directly is several times quicker than `structuredClone` — which was the largest single
+ * cost of opening a page.
+ */
+export function cloneRecord<T>(value: T): T {
+ return cloneValue(value) as T
+}
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index e7d1acf44..29b004d55 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -4,6 +4,7 @@ import {
DEFAULT_STROKE_MITER_LIMIT,
styleToWeight
} from '@open-pencil/scene-graph'
+import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
import { parseVariantName } from '@open-pencil/scene-graph/variant-name'
/* eslint-disable max-lines -- kiwi↔scene conversion helpers are tightly coupled */
@@ -71,6 +72,7 @@ import type {
import type { GUID } from '@open-pencil/scene-graph/primitives'
export { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'
+import { numericVariableAssignmentScales, sourceVariableBindingScales } from './variable-bindings'
export { VARIABLE_BINDING_FIELDS, VARIABLE_BINDING_FIELDS_INVERSE } from './variable-bindings'
interface FigVariableModeMap {
@@ -452,7 +454,11 @@ function convertLayoutProps(
> &
Partial<Pick<SceneNode, 'derivedLayout'>> {
const layoutMode = mapStackMode(nc.stackMode)
- const primaryAxisSizing = mapStackSizing(nc.stackPrimarySizing)
+ const primaryAxisSizing =
+ nc.stackPrimarySizing === undefined &&
+ (layoutMode === 'HORIZONTAL' || layoutMode === 'VERTICAL')
+ ? 'HUG'
+ : mapStackSizing(nc.stackPrimarySizing)
const counterAxisSizing = mapStackSizing(nc.stackCounterSizing)
const derivedLayout = visibleContainerDerivedLayout(
nc,
@@ -502,6 +508,14 @@ function styleRefId(value: unknown): string | null {
if (!value || typeof value !== 'object' || !('guid' in value)) return null
const guid = value.guid
if (!guid || typeof guid !== 'object') return null
+ // Kiwi's all-ones GUID denotes an explicitly cleared style reference.
+ if (
+ 'sessionID' in guid &&
+ 'localID' in guid &&
+ guid.sessionID === 0xffffffff &&
+ guid.localID === 0xffffffff
+ )
+ return null
return guidToString(guid as GUID)
}
@@ -595,25 +609,10 @@ function resolveNodeType(nc: NodeChange): NodeType | 'DOCUMENT' | 'VARIABLE' {
return nodeType
}
-function nearlyEqualSize(a: number | undefined, b: number | undefined): boolean {
- return Math.abs((a ?? 0) - (b ?? 0)) <= 0.5
-}
-
-export function shouldImportTextAsAutoSize(
- nc: NodeChange,
- parentNc: NodeChange | undefined
-): boolean {
- if (nc.type !== 'TEXT' || nc.textAutoResize !== 'NONE') return false
- if (parentNc?.stackMode !== 'HORIZONTAL' && parentNc?.stackMode !== 'VERTICAL') return false
- if (!nc.textData?.characters) return false
- const layoutSize = nc.derivedTextData?.layoutSize
- if (!layoutSize || !nc.size) return false
- return nearlyEqualSize(layoutSize.x, nc.size.x) && nearlyEqualSize(layoutSize.y, nc.size.y)
-}
-
export function nodeChangeToProps(
nc: NodeChange,
- blobs: Uint8Array[]
+ blobs: Uint8Array[],
+ metadata: 'source' | 'occurrence' = 'source'
): Partial<SceneNode> & { nodeType: NodeType | 'DOCUMENT' | 'VARIABLE' } {
const nodeType = resolveNodeType(nc)
@@ -623,11 +622,13 @@ export function nodeChangeToProps(
const props: Partial<SceneNode> & { nodeType: NodeType | 'DOCUMENT' | 'VARIABLE' } = {
nodeType,
name: nc.name ?? nodeType,
- source: extractSourceMetadata(nc, blobs),
+ source:
+ metadata === 'source' ? extractSourceMetadata(nc, blobs) : extractOccurrenceMetadata(nc),
...convertFigmaTransformProps(nc),
opacity: nc.opacity ?? 1,
visible: nc.visible ?? true,
locked: nc.locked ?? false,
+ internalOnly: nc.internalOnly === true || sharedStyleType(nc.styleType) !== null,
blendMode: (nc.blendMode as Fill['blendMode']) ?? 'PASS_THROUGH',
booleanOperation: mapBooleanOperation(nc),
fills: convertFills(nc.fillPaints),
@@ -664,6 +665,8 @@ export function nodeChangeToProps(
expanded: true,
autoRename: (nc.autoRename ?? true) as boolean,
boundVariables: extractBoundVariables(nc),
+ variableAssignmentScales: numericVariableAssignmentScales(),
+ variableBindingScales: sourceVariableBindingScales(nc),
variableModes: extractVariableModes(nc),
exportSettings: extractExportSettings(nc),
pluginData: extractPluginData(nc),
@@ -671,7 +674,7 @@ export function nodeChangeToProps(
pluginRelaunchData: extractPluginRelaunchData(nc),
clipsContent: nc.frameMaskDisabled === false && nc.resizeToFit !== true,
componentId: extractSymbolId(nc),
- componentPropertyDefinitions: extractComponentPropertyDefs(nc),
+ componentPropertyDefinitions: nodeType === 'INSTANCE' ? [] : extractComponentPropertyDefs(nc),
componentPropertyReferences: extractComponentPropertyRefs(nc),
componentPropertyAssignments: extractComponentPropertyAssignments(nc),
componentPropertyValues: extractComponentPropertyValues(nc),
@@ -942,6 +945,12 @@ function extractFigmaLayoutMetadata(nc: NodeChange): SceneNode['source']['fig'][
}
}
+function extractOccurrenceMetadata(nc: NodeChange): SceneNode['source'] {
+ const source = createDefaultSourceMetadata()
+ source.fig.layout = extractFigmaLayoutMetadata(nc)
+ return source
+}
+
function extractSourceMetadata(nc: NodeChange, blobs: Uint8Array[]): SceneNode['source'] {
return {
format: 'fig',
diff --git a/packages/fig/src/node-change/derived-text-glyphs.ts b/packages/fig/src/node-change/derived-text-glyphs.ts
index 5b000fe14..85a9903e8 100644
--- a/packages/fig/src/node-change/derived-text-glyphs.ts
+++ b/packages/fig/src/node-change/derived-text-glyphs.ts
@@ -18,6 +18,7 @@ export function convertFigmaDerivedTextGlyphs(
x: glyph.position.x,
y: glyph.position.y,
fontSize: glyph.fontSize,
+ firstCharacter: glyph.firstCharacter,
rotation: glyph.rotation
}
})
diff --git a/packages/fig/src/node-change/export/context.ts b/packages/fig/src/node-change/export/context.ts
new file mode 100644
index 000000000..a5e5873fb
--- /dev/null
+++ b/packages/fig/src/node-change/export/context.ts
@@ -0,0 +1,228 @@
+import { effectiveFigmaRawNodeFields } from '#fig/source-metadata'
+
+import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'
+import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
+import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { Color, GUID, Matrix } from '@open-pencil/scene-graph/primitives'
+
+export type KiwiNodeChange = NodeChange & Record<string, unknown>
+
+export interface KiwiSymbolOverridePayload {
+ guidPath?: { guids?: GUID[] }
+ textData?: { characters?: string }
+ fillPaints?: Paint[]
+ [key: string]: unknown
+}
+
+/** How a record names a shared style: a local GUID, or a published library asset. */
+export interface StyleReference {
+ guid?: GUID
+ assetRef?: { key: string; version?: string }
+}
+
+/** Published text styles by source id, built once with the rest of the context. */
+export function buildStyleReferences(graph: SceneGraph): ReadonlyMap<string, StyleReference> {
+ const references = new Map<string, StyleReference>()
+ for (const node of graph.getAllNodes()) {
+ if (node.sharedStyleType !== 'TEXT' || !node.source.id) continue
+ const raw = effectiveFigmaRawNodeFields(node)
+ if (typeof raw.key !== 'string') continue
+ references.set(node.source.id, {
+ assetRef: {
+ key: raw.key,
+ ...(typeof raw.version === 'string' ? { version: raw.version } : {})
+ }
+ })
+ }
+ return references
+}
+
+export interface SceneNodeToKiwiContext {
+ styleReferences?: ReadonlyMap<string, StyleReference>
+ graph: SceneGraph
+ blobs: Uint8Array[]
+ blobIndexByHex?: Map<string, number>
+ nodeIdToGuid?: Map<string, GUID>
+ /** Reverse index of assigned GUID values ("sessionID:localID") for O(1)
+ * collision detection. Populated alongside every nodeIdToGuid.set() call. */
+ assignedGuidValues?: Set<string>
+ fontDigestMap?: Map<string, Uint8Array>
+ glyphBlobMap?: Map<string, number>
+ varIdToGuid?: Map<string, GUID>
+ modeIdToGuid?: Map<string, GUID>
+ /** Variable GUIDs used only where raw effect aliases cannot retain asset refs. */
+ assetRefToVarGuid?: Map<string, GUID>
+ /** GUIDs minted for component property IDs (e.g. "prop:abc123") that aren't
+ * already Figma-GUID-shaped, keyed by the original ID so refs/assignments/
+ * variantPropSpecs pointing at the same property reuse the same GUID. */
+ propertyIdToGuid: Map<string, GUID>
+ componentPropertyDefinitionsById: ReadonlyMap<string, ComponentPropertyDefinition>
+ fractionalPosition: (index: number) => string
+ mapToFigmaType: (type: SceneNode['type']) => string
+ fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paint
+ safeColor: (color: Color) => Color
+ computeExportTransform: (node: SceneNode) => Matrix
+ serializeCornerRadii: (node: SceneNode, nc: KiwiNodeChange) => void
+ serializeTextProps: (
+ node: SceneNode,
+ nc: KiwiNodeChange,
+ graph: SceneGraph,
+ fontDigestMap: Map<string, Uint8Array> | undefined,
+ blobs: Uint8Array[],
+ glyphBlobMap: Map<string, number> | undefined
+ ) => void
+ serializeLayoutProps: (node: SceneNode, nc: KiwiNodeChange) => void
+ serializeGeometry: (node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Array[]) => void
+ serializeVariableBindings: (
+ node: SceneNode,
+ nc: KiwiNodeChange,
+ graph: SceneGraph,
+ varIdToGuid?: Map<string, GUID>
+ ) => void
+ sceneNodeToKiwi: (
+ node: SceneNode,
+ parentGuid: GUID,
+ childIndex: number,
+ localIdCounter: { value: number },
+ context: SceneNodeToKiwiContext
+ ) => KiwiNodeChange[]
+}
+
+export function parseGuidOrNull(value: string) {
+ return /^\d+:\d+$/.test(value) ? stringToGuid(value) : null
+}
+
+export function resolveInstanceComponentId(
+ context: SceneNodeToKiwiContext,
+ componentId: string
+): string {
+ const seen = new Set<string>()
+ let currentId = componentId
+ while (!seen.has(currentId)) {
+ seen.add(currentId)
+ const node = context.graph.getNode(currentId)
+ if (node?.type !== 'INSTANCE' || !node.componentId) return currentId
+ currentId = node.componentId
+ }
+ return componentId
+}
+
+export function getOrCreateNodeGuid(
+ context: SceneNodeToKiwiContext,
+ nodeId: string,
+ localIdCounter: { value: number }
+): GUID | undefined {
+ const node = context.graph.getNode(nodeId)
+ if (!node) return undefined
+ const existing = context.nodeIdToGuid?.get(nodeId)
+ if (existing) return existing
+ const importedGuid = node.source.id ? parseGuidOrNull(node.source.id) : null
+
+ // When source.id maps to a GUID value that is already assigned to a
+ // different node (e.g. two nodes from different canvases with the same
+ // source.id "1:94"), fall back to the counter to avoid collisions.
+ if (importedGuid && context.assignedGuidValues) {
+ const key = `${importedGuid.sessionID}:${importedGuid.localID}`
+ if (context.assignedGuidValues.has(key)) {
+ const guid: GUID = { sessionID: 1, localID: localIdCounter.value++ }
+ context.nodeIdToGuid?.set(nodeId, guid)
+ context.assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)
+ return guid
+ }
+ }
+
+ const guid = importedGuid ?? { sessionID: 1, localID: localIdCounter.value++ }
+ context.nodeIdToGuid?.set(nodeId, guid)
+ context.assignedGuidValues?.add(`${guid.sessionID}:${guid.localID}`)
+ return guid
+}
+
+/**
+ * Component property IDs ("prop:abc123") never match the Figma GUID shape,
+ * so parseGuidOrNull always rejects them — mint a stable synthetic GUID from
+ * the shared node-id counter instead, memoized so every def/ref/assignment/
+ * variantPropSpec pointing at the same property ID round-trips consistently.
+ */
+export function getOrCreatePropertyGuid(
+ context: SceneNodeToKiwiContext,
+ propertyId: string,
+ localIdCounter: { value: number }
+): GUID {
+ const existing = context.propertyIdToGuid.get(propertyId)
+ if (existing) return existing
+ const parsed = parseGuidOrNull(propertyId)
+ if (parsed) return parsed
+ const guid = { sessionID: 1, localID: localIdCounter.value++ }
+ context.propertyIdToGuid.set(propertyId, guid)
+ context.assignedGuidValues?.add(`${guid.sessionID}:${guid.localID}`)
+ return guid
+}
+
+export function isDescendantOf(
+ context: SceneNodeToKiwiContext,
+ nodeId: string,
+ ancestorId: string
+) {
+ let current = context.graph.getNode(nodeId)
+ while (current?.parentId) {
+ if (current.parentId === ancestorId) return true
+ current = context.graph.getNode(current.parentId)
+ }
+ return false
+}
+
+export function applyColorVariableBinding(
+ context: SceneNodeToKiwiContext,
+ node: SceneNode,
+ paint: Paint,
+ field: string
+): Paint {
+ const variableId = node.boundVariables[field]
+ if (!variableId) return paint
+ return {
+ ...paint,
+ colorVar: {
+ dataType: 'ALIAS',
+ resolvedDataType: 'COLOR',
+ value: { alias: { guid: context.varIdToGuid?.get(variableId) ?? stringToGuid(variableId) } }
+ },
+ colorVariableBinding: {
+ variableID: context.varIdToGuid?.get(variableId) ?? stringToGuid(variableId)
+ }
+ }
+}
+
+/** A node's fills with their colour variable aliases, for the record and for override claims alike. */
+export function createFillPaints(context: SceneNodeToKiwiContext, node: SceneNode): Paint[] {
+ return node.fills.map((fill, index) =>
+ applyColorVariableBinding(context, node, context.fillToKiwiPaint(fill), `fills/${index}/color`)
+ )
+}
+
+export function createStrokePaints(context: SceneNodeToKiwiContext, node: SceneNode): Paint[] {
+ return node.strokes.map((stroke, index) =>
+ applyColorVariableBinding(
+ context,
+ node,
+ {
+ type: 'SOLID',
+ color: context.safeColor(stroke.color),
+ opacity: stroke.opacity,
+ visible: stroke.visible,
+ blendMode: 'NORMAL'
+ },
+ `strokes/${index}/color`
+ )
+ )
+}
+
+/** Instances address descendants by override key when one exists, else by node GUID. */
+export function instanceGuidResolver(context: SceneNodeToKiwiContext, counter: { value: number }) {
+ return (id: string): GUID | undefined => {
+ const source = context.graph.getNode(id)
+ return (
+ (source?.overrideKey ? parseGuidOrNull(source.overrideKey) : null) ??
+ getOrCreateNodeGuid(context, id, counter)
+ )
+ }
+}
diff --git a/packages/fig/src/node-change/export-node.ts b/packages/fig/src/node-change/export/node.ts
similarity index 72%
rename from packages/fig/src/node-change/export-node.ts
rename to packages/fig/src/node-change/export/node.ts
index 358f044aa..999163e54 100644
--- a/packages/fig/src/node-change/export-node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -1,4 +1,7 @@
-import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'
+import type { DerivedSymbolOverride } from '#fig/instance-overrides/types'
+import { effectiveFigmaRawNodeFields, effectiveFigmaSourcePayload } from '#fig/source-metadata'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
import type {
ComponentPropertyDefinition,
@@ -6,13 +9,13 @@ import type {
SceneGraph,
SceneNode
} from '@open-pencil/scene-graph'
-import { DEFAULT_STROKE_MITER_LIMIT, forEachInstanceOverride } from '@open-pencil/scene-graph'
-import type { Color, GUID, Matrix, Vector } from '@open-pencil/scene-graph/primitives'
+import { DEFAULT_STROKE_MITER_LIMIT } from '@open-pencil/scene-graph'
+import type { GUID, Matrix, Vector } from '@open-pencil/scene-graph/primitives'
-import { effectiveFigmaRawNodeFields, effectiveFigmaSourcePayload } from '../source-metadata'
/* eslint-disable max-lines */
-import { bytesToHex } from './bytes'
-import { exportCanvasGuides } from './canvas-guides'
+import { bytesToHex } from '../bytes'
+import { exportCanvasGuides } from '../canvas-guides'
+import { snapshotInstanceGeometry } from '../instance-geometry'
import {
applyExportSettingsPluginData,
applyLibrarySourcePluginData,
@@ -21,19 +24,26 @@ import {
NODE_TYPE_PLUGIN_KEY,
serializePluginRelaunchData,
upsertPluginData
-} from './plugin-data'
-
-export type KiwiNodeChange = NodeChange & Record<string, unknown>
+} from '../plugin-data'
+import {
+ applyColorVariableBinding,
+ createFillPaints,
+ createStrokePaints,
+ getOrCreateNodeGuid,
+ instanceGuidResolver,
+ getOrCreatePropertyGuid,
+ parseGuidOrNull,
+ resolveInstanceComponentId,
+ type KiwiNodeChange,
+ type KiwiSymbolOverridePayload,
+ type SceneNodeToKiwiContext
+} from './context'
+import { mergeOverrides, serializeRuntimePropertyOverrides } from './override-claims'
+
+export type { KiwiNodeChange, SceneNodeToKiwiContext } from './context'
type KiwiBooleanOperation = NonNullable<NodeChange['booleanOperation']>
-interface KiwiSymbolOverridePayload {
- guidPath?: { guids?: GUID[] }
- textData?: { characters?: string }
- fillPaints?: Paint[]
- [key: string]: unknown
-}
-
function toKiwiBooleanOperation(operation: SceneNode['booleanOperation']): KiwiBooleanOperation {
return operation === 'EXCLUDE' ? 'XOR' : (operation ?? 'UNION')
}
@@ -53,89 +63,6 @@ export function buildAssetRefToVarGuidMap(
return map
}
-interface SceneNodeToKiwiContext {
- graph: SceneGraph
- blobs: Uint8Array[]
- blobIndexByHex?: Map<string, number>
- nodeIdToGuid?: Map<string, GUID>
- /** Reverse index of assigned GUID values ("sessionID:localID") for O(1)
- * collision detection. Populated alongside every nodeIdToGuid.set() call. */
- assignedGuidValues?: Set<string>
- fontDigestMap?: Map<string, Uint8Array>
- glyphBlobMap?: Map<string, number>
- varIdToGuid?: Map<string, GUID>
- modeIdToGuid?: Map<string, GUID>
- /** Variable GUIDs used only where raw effect aliases cannot retain asset refs. */
- assetRefToVarGuid?: Map<string, GUID>
- /** GUIDs minted for component property IDs (e.g. "prop:abc123") that aren't
- * already Figma-GUID-shaped, keyed by the original ID so refs/assignments/
- * variantPropSpecs pointing at the same property reuse the same GUID. */
- propertyIdToGuid: Map<string, GUID>
- componentPropertyDefinitionsById: ReadonlyMap<string, ComponentPropertyDefinition>
- fractionalPosition: (index: number) => string
- mapToFigmaType: (type: SceneNode['type']) => string
- fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paint
- safeColor: (color: Color) => Color
- computeExportTransform: (node: SceneNode) => Matrix
- serializeCornerRadii: (node: SceneNode, nc: KiwiNodeChange) => void
- serializeTextProps: (
- node: SceneNode,
- nc: KiwiNodeChange,
- graph: SceneGraph,
- fontDigestMap: Map<string, Uint8Array> | undefined,
- blobs: Uint8Array[],
- glyphBlobMap: Map<string, number> | undefined
- ) => void
- serializeLayoutProps: (node: SceneNode, nc: KiwiNodeChange) => void
- serializeGeometry: (node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Array[]) => void
- serializeVariableBindings: (
- node: SceneNode,
- nc: KiwiNodeChange,
- graph: SceneGraph,
- varIdToGuid?: Map<string, GUID>
- ) => void
- sceneNodeToKiwi: (
- node: SceneNode,
- parentGuid: GUID,
- childIndex: number,
- localIdCounter: { value: number },
- context: SceneNodeToKiwiContext
- ) => KiwiNodeChange[]
-}
-
-function applyColorVariableBinding(
- context: SceneNodeToKiwiContext,
- node: SceneNode,
- paint: Paint,
- field: string
-): Paint {
- const variableId = node.boundVariables[field]
- if (!variableId) return paint
- return {
- ...paint,
- colorVariableBinding: {
- variableID: context.varIdToGuid?.get(variableId) ?? stringToGuid(variableId)
- }
- }
-}
-
-function createStrokePaints(context: SceneNodeToKiwiContext, node: SceneNode): Paint[] {
- return node.strokes.map((stroke, index) =>
- applyColorVariableBinding(
- context,
- node,
- {
- type: 'SOLID',
- color: context.safeColor(stroke.color),
- opacity: stroke.opacity,
- visible: stroke.visible,
- blendMode: 'NORMAL'
- },
- `strokes/${index}/color`
- )
- )
-}
-
function componentPropertyTypeForKiwi(type: string) {
if (type === 'BOOLEAN') return 'BOOL'
return type
@@ -158,8 +85,27 @@ function componentPropertyValue(
return { textValue: { characters: value } }
}
-function parseGuidOrNull(value: string) {
- return /^\d+:\d+$/.test(value) ? stringToGuid(value) : null
+function componentPropertyVariableValue(
+ type: string,
+ value: string,
+ context: SceneNodeToKiwiContext,
+ localIdCounter: { value: number }
+) {
+ const legacy = componentPropertyValue(type, value, context, localIdCounter)
+ if (type === 'BOOLEAN')
+ return {
+ value: { boolValue: value === 'true' },
+ dataType: 'BOOLEAN',
+ resolvedDataType: 'BOOLEAN'
+ }
+ if (type === 'INSTANCE_SWAP' && 'guidValue' in legacy) {
+ return {
+ value: { symbolIdValue: { guid: legacy.guidValue } },
+ dataType: 'SYMBOL_ID',
+ resolvedDataType: 'SYMBOL_ID'
+ }
+ }
+ return { value: { textValue: value }, dataType: 'STRING', resolvedDataType: 'STRING' }
}
function serializeVariableModes(
@@ -322,161 +268,6 @@ function materializeFigmaPayload(
return materialized
}
-function resolveInstanceComponentId(context: SceneNodeToKiwiContext, componentId: string): string {
- const seen = new Set<string>()
- let currentId = componentId
- while (!seen.has(currentId)) {
- seen.add(currentId)
- const node = context.graph.getNode(currentId)
- if (node?.type !== 'INSTANCE' || !node.componentId) return currentId
- currentId = node.componentId
- }
- return componentId
-}
-
-function getOrCreateNodeGuid(
- context: SceneNodeToKiwiContext,
- nodeId: string,
- localIdCounter: { value: number }
-): GUID | undefined {
- const node = context.graph.getNode(nodeId)
- if (!node) return undefined
- const existing = context.nodeIdToGuid?.get(nodeId)
- if (existing) return existing
- const importedGuid = node.source.id ? parseGuidOrNull(node.source.id) : null
-
- // When source.id maps to a GUID value that is already assigned to a
- // different node (e.g. two nodes from different canvases with the same
- // source.id "1:94"), fall back to the counter to avoid collisions.
- if (importedGuid && context.assignedGuidValues) {
- const key = `${importedGuid.sessionID}:${importedGuid.localID}`
- if (context.assignedGuidValues.has(key)) {
- const guid: GUID = { sessionID: 1, localID: localIdCounter.value++ }
- context.nodeIdToGuid?.set(nodeId, guid)
- context.assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)
- return guid
- }
- }
-
- const guid = importedGuid ?? { sessionID: 1, localID: localIdCounter.value++ }
- context.nodeIdToGuid?.set(nodeId, guid)
- context.assignedGuidValues?.add(`${guid.sessionID}:${guid.localID}`)
- return guid
-}
-
-/**
- * Component property IDs ("prop:abc123") never match the Figma GUID shape,
- * so parseGuidOrNull always rejects them — mint a stable synthetic GUID from
- * the shared node-id counter instead, memoized so every def/ref/assignment/
- * variantPropSpec pointing at the same property ID round-trips consistently.
- */
-function getOrCreatePropertyGuid(
- context: SceneNodeToKiwiContext,
- propertyId: string,
- localIdCounter: { value: number }
-): GUID {
- const existing = context.propertyIdToGuid.get(propertyId)
- if (existing) return existing
- const parsed = parseGuidOrNull(propertyId)
- if (parsed) return parsed
- const guid = { sessionID: 1, localID: localIdCounter.value++ }
- context.propertyIdToGuid.set(propertyId, guid)
- context.assignedGuidValues?.add(`${guid.sessionID}:${guid.localID}`)
- return guid
-}
-
-function isDescendantOf(context: SceneNodeToKiwiContext, nodeId: string, ancestorId: string) {
- let current = context.graph.getNode(nodeId)
- while (current?.parentId) {
- if (current.parentId === ancestorId) return true
- current = context.graph.getNode(current.parentId)
- }
- return false
-}
-
-function serializeTextOverrides(
- context: SceneNodeToKiwiContext,
- instance: SceneNode,
- localIdCounter: { value: number }
-): KiwiSymbolOverridePayload[] {
- const result: KiwiSymbolOverridePayload[] = []
- forEachInstanceOverride(instance.instanceOverrides, (nodeId, field, value) => {
- if (field !== 'text' || !nodeId) return
- const target = context.graph.getNode(nodeId)
- if (!target || !isDescendantOf(context, nodeId, instance.id)) return
- const targetGuid = resolveOverrideTargetGuid(context, target, localIdCounter)
- if (targetGuid)
- result.push({
- guidPath: { guids: [targetGuid] },
- textData: { characters: typeof value === 'string' ? value : target.text }
- })
- })
- return result
-}
-
-/**
- * Resolves the descendant-node identity a symbol override applies to: the
- * GUID of the corresponding node inside the target's own main component
- * (cloneNodeProps stamps componentId with that node's id on every clone).
- */
-function resolveOverrideTargetGuid(
- context: SceneNodeToKiwiContext,
- target: SceneNode,
- localIdCounter: { value: number }
-): GUID | undefined {
- const sourceId = target.componentId
- if (!sourceId) return undefined
- const source = context.graph.getNode(sourceId)
- const overrideGuid = source?.overrideKey ? parseGuidOrNull(source.overrideKey) : null
- return overrideGuid ?? getOrCreateNodeGuid(context, sourceId, localIdCounter)
-}
-
-function serializeFillOverrides(
- context: SceneNodeToKiwiContext,
- instance: SceneNode,
- localIdCounter: { value: number }
-): KiwiSymbolOverridePayload[] {
- const result: KiwiSymbolOverridePayload[] = []
- forEachInstanceOverride(instance.instanceOverrides, (nodeId, field) => {
- if (field !== 'fills' || !nodeId) return
- const target = context.graph.getNode(nodeId)
- if (!target || !isDescendantOf(context, nodeId, instance.id)) return
- const targetGuid = resolveOverrideTargetGuid(context, target, localIdCounter)
- if (targetGuid)
- result.push({
- guidPath: { guids: [targetGuid] },
- fillPaints: target.fills.map((fill) => context.fillToKiwiPaint(fill))
- })
- })
- return result
-}
-
-function overridePathKey(payload: KiwiSymbolOverridePayload): string | null {
- const guids = payload.guidPath?.guids
- return guids?.length
- ? guids.map(({ sessionID, localID }) => `${sessionID}:${localID}`).join('/')
- : null
-}
-
-function mergeOverrides(
- symbolOverrides: KiwiSymbolOverridePayload[],
- newOverrides: KiwiSymbolOverridePayload[]
-): void {
- for (const override of newOverrides) {
- const pathKey = overridePathKey(override)
- let existingIndex = -1
- if (pathKey) {
- for (let index = symbolOverrides.length - 1; index >= 0; index--) {
- if (overridePathKey(symbolOverrides[index]) !== pathKey) continue
- existingIndex = index
- break
- }
- }
- if (existingIndex < 0) symbolOverrides.push(override)
- else symbolOverrides[existingIndex] = { ...symbolOverrides[existingIndex], ...override }
- }
-}
-
/**
* Fields that are ALWAYS set by explicit serialization and must NOT be
* overwritten by rawNodeFields (which may contain stale Figma defaults).
@@ -576,7 +367,15 @@ function applyRawFigmaNodeFields(
// The scene model may lose this distinction for instance children whose
// strokes are resolved from component overrides. Prefer the raw data.
if ((key === 'fillPaints' || key === 'strokePaints') && node.source.id) {
- nc[key] = materialized[key]
+ const paints = materialized[key]
+ nc[key] = paints?.map((paint, index) =>
+ applyColorVariableBinding(
+ context,
+ node,
+ paint,
+ `${key === 'fillPaints' ? 'fills' : 'strokes'}/${index}/color`
+ )
+ )
continue
}
if (
@@ -648,11 +447,15 @@ function applyInstancePayload(
}) as KiwiSymbolOverridePayload[])
)
}
- mergeOverrides(symbolOverrides, serializeTextOverrides(context, node, localIdCounter))
- mergeOverrides(symbolOverrides, serializeFillOverrides(context, node, localIdCounter))
+ mergeOverrides(
+ symbolOverrides,
+ serializeRuntimePropertyOverrides(context, node, localIdCounter)
+ )
if (symbolOverrides.length > 0) symbolData.symbolOverrides = symbolOverrides
- if (node.source.fig.uniformScaleFactor != null) {
- symbolData.uniformScaleFactor = node.source.fig.uniformScaleFactor
+ if (!Number.isFinite(node.componentScale) || node.componentScale <= 0)
+ throw new Error('Invalid instance uniform scale')
+ if (node.componentScale !== 1 || node.source.fig.uniformScaleFactor != null) {
+ symbolData.uniformScaleFactor = node.componentScale
}
nc.symbolData = symbolData as KiwiNodeChange['symbolData']
}
@@ -670,17 +473,22 @@ function applyInstancePayload(
}
)
}
- if (node.source.fig.derivedSymbolData.length > 0) {
- nc.derivedSymbolData = materializeFigmaPayload(
- node.source.fig.derivedSymbolData,
- context.blobs,
- {
- blobIndexByHex: context.blobIndexByHex,
- includePaintVariables: true,
- includeVariableMaps: true
- }
- )
- }
+ const retainedGeometry = materializeFigmaPayload(
+ node.source.fig.derivedSymbolData,
+ context.blobs,
+ {
+ blobIndexByHex: context.blobIndexByHex,
+ includePaintVariables: true,
+ includeVariableMaps: true
+ }
+ ) as DerivedSymbolOverride[]
+ nc.derivedSymbolData = snapshotInstanceGeometry(
+ context.graph,
+ node,
+ instanceGuidResolver(context, localIdCounter),
+ retainedGeometry,
+ (target) => ({ size: exportNodeSize(target), transform: exportNodeTransform(context, target) })
+ )
if (node.source.fig.derivedSymbolDataLayoutVersion != null) {
nc.derivedSymbolDataLayoutVersion = node.source.fig.derivedSymbolDataLayoutVersion
}
@@ -732,6 +540,55 @@ function shouldSerializeRawBackedField(
return hasValue && !(rawField in effectiveFigmaRawNodeFields(node)) && !alreadySerialized
}
+interface ExportedPropertyReference {
+ defID: GUID
+ componentPropNodeField: string
+}
+interface ExportedParameterEntry {
+ variableField?: string
+ variableData?: {
+ value: { propRefValue: { defId: GUID } }
+ dataType: string
+ resolvedDataType: string
+ }
+}
+function mergeParameterBindings(nc: KiwiNodeChange): void {
+ const parameters = nc.parameterConsumptionMap as
+ | { entries?: Array<{ variableField?: string }> }
+ | undefined
+ const entries = parameters?.entries ?? []
+ const fields = new Set(entries.map((entry) => entry.variableField))
+ const variables = nc.variableConsumptionMap?.entries ?? []
+ if (!variables.length) return
+ nc.parameterConsumptionMap = {
+ entries: [...variables.filter((entry) => !fields.has(entry.variableField)), ...entries]
+ }
+}
+
+function applyParameterReferences(nc: KiwiNodeChange, refs: ExportedPropertyReference[]): void {
+ if (!refs.length) return
+ const existing = nc.parameterConsumptionMap as { entries?: ExportedParameterEntry[] } | undefined
+ const fields = new Set(refs.map((ref) => ref.componentPropNodeField))
+ const entries = (existing?.entries ?? []).filter(
+ (entry) => !fields.has(entry.variableField ?? '')
+ )
+ const types: Record<string, string> = {
+ VISIBLE: 'BOOLEAN',
+ TEXT_DATA: 'STRING',
+ OVERRIDDEN_SYMBOL_ID: 'SYMBOL_ID'
+ }
+ for (const ref of refs)
+ entries.push({
+ variableField: ref.componentPropNodeField,
+ variableData: {
+ value: { propRefValue: { defId: ref.defID } },
+ dataType: 'PROP_REF',
+ resolvedDataType: types[ref.componentPropNodeField]
+ }
+ })
+ nc.parameterConsumptionMap = { entries }
+}
+
function applyComponentMetadata(
context: SceneNodeToKiwiContext,
node: SceneNode,
@@ -757,6 +614,7 @@ function applyComponentMetadata(
name: def.name,
type: componentPropertyTypeForKiwi(def.type),
initialValue: componentPropertyValue(def.type, def.defaultValue, context, localIdCounter),
+ varValue: componentPropertyVariableValue(def.type, def.defaultValue, context, localIdCounter),
preferredValues: componentPropertyPreferredValues(def, context)
}))
if (shouldSerializeRawBackedField(node, 'componentPropDefs', componentPropDefs.length > 0)) {
@@ -771,13 +629,15 @@ function applyComponentMetadata(
nc.componentPropRefs = componentPropRefs
}
+ applyParameterReferences(nc, componentPropRefs)
const componentPropAssignments = Object.entries(node.componentPropertyAssignments)
.map(([propertyId, value]) => {
const definition = context.componentPropertyDefinitionsById.get(propertyId)
if (!definition) return null
return {
defID: getOrCreatePropertyGuid(context, propertyId, localIdCounter),
- value: componentPropertyValue(definition.type, value, context, localIdCounter)
+ value: componentPropertyValue(definition.type, value, context, localIdCounter),
+ varValue: componentPropertyVariableValue(definition.type, value, context, localIdCounter)
}
})
.filter((assignment): assignment is NonNullable<typeof assignment> => assignment !== null)
@@ -860,12 +720,17 @@ function nodeForGeometryExport(node: SceneNode): SceneNode {
}
}
-function applySharedStyleProps(node: SceneNode, nc: KiwiNodeChange): void {
- if (node.fillStyleId) nc.styleIdForFill = { guid: stringToGuid(node.fillStyleId) }
- if (node.strokeStyleId) nc.styleIdForStrokeFill = { guid: stringToGuid(node.strokeStyleId) }
- if (node.textStyleId) nc.styleIdForText = { guid: stringToGuid(node.textStyleId) }
- if (node.effectStyleId) nc.styleIdForEffect = { guid: stringToGuid(node.effectStyleId) }
- if (node.gridStyleId) nc.styleIdForGrid = { guid: stringToGuid(node.gridStyleId) }
+function applySharedStyleProps(
+ context: SceneNodeToKiwiContext,
+ node: SceneNode,
+ nc: KiwiNodeChange
+): void {
+ const reference = (id: string) => ({ guid: context.nodeIdToGuid?.get(id) ?? stringToGuid(id) })
+ if (node.fillStyleId) nc.styleIdForFill = reference(node.fillStyleId)
+ if (node.strokeStyleId) nc.styleIdForStrokeFill = reference(node.strokeStyleId)
+ if (node.textStyleId) nc.styleIdForText = reference(node.textStyleId)
+ if (node.effectStyleId) nc.styleIdForEffect = reference(node.effectStyleId)
+ if (node.gridStyleId) nc.styleIdForGrid = reference(node.gridStyleId)
if (node.layoutGrids.length > 0) nc.layoutGrids = structuredClone(node.layoutGrids)
if (node.guides.length > 0) nc.guides = exportCanvasGuides(node.guides)
}
@@ -883,16 +748,7 @@ function applyNodeVisualProps(
nc.borderLeftWeight = node.borderLeftWeight
}
- if (node.fills.length > 0) {
- nc.fillPaints = node.fills.map((fill, index) =>
- applyColorVariableBinding(
- context,
- node,
- context.fillToKiwiPaint(fill),
- `fills/${index}/color`
- )
- )
- }
+ if (node.fills.length > 0) nc.fillPaints = createFillPaints(context, node)
context.serializeCornerRadii(node, nc)
@@ -921,7 +777,7 @@ function applyNodeVisualProps(
}
if (node.type !== 'VECTOR') nc.frameMaskDisabled = !node.clipsContent
- applySharedStyleProps(node, nc)
+ applySharedStyleProps(context, node, nc)
if (node.horizontalConstraint !== 'MIN') nc.horizontalConstraint = node.horizontalConstraint
if (node.verticalConstraint !== 'MIN') nc.verticalConstraint = node.verticalConstraint
if (node.strokeCap !== 'NONE') nc.strokeCap = node.strokeCap
@@ -974,7 +830,7 @@ export function sceneNodeToKiwiWithContext(
guid,
parentIndex: {
guid: parentGuid,
- position: node.source.orderKey ?? context.fractionalPosition(childIndex)
+ position: context.fractionalPosition(childIndex)
},
type: exportType,
name: node.name,
@@ -1010,6 +866,7 @@ export function sceneNodeToKiwiWithContext(
context.serializeLayoutProps(node, nc)
context.serializeGeometry(nodeForGeometryExport(node), nc, context.blobs)
context.serializeVariableBindings(node, nc, context.graph, context.varIdToGuid)
+ mergeParameterBindings(nc)
applyRawFigmaNodeFields(context, node, nc)
const variableModeBySetMap = serializeVariableModes(
node,
@@ -1031,7 +888,9 @@ export function sceneNodeToKiwiWithContext(
const children =
node.type === 'INSTANCE'
? []
- : context.graph.getChildren(node.id).filter((child) => !child.internalOnly)
+ : context.graph
+ .getChildren(node.id)
+ .filter((child) => !child.internalOnly && child.sharedStyleType === null)
for (let i = 0; i < children.length; i++) {
result.push(...context.sceneNodeToKiwi(children[i], guid, i, localIdCounter, context))
}
diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.ts
new file mode 100644
index 000000000..3c76d9cf4
--- /dev/null
+++ b/packages/fig/src/node-change/export/override-claims.ts
@@ -0,0 +1,218 @@
+import { SCENE_OVERRIDE_FIELDS } from '#fig/instance-overrides/fields'
+
+import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
+import { forEachInstanceOverride, type SceneNode } from '@open-pencil/scene-graph'
+import type { GUID, Vector } from '@open-pencil/scene-graph/primitives'
+
+import { instanceExportAddress } from '../instance-geometry'
+import { mergeVariableConsumptionMaps, overrideVariableBindingEntry } from '../variable-bindings'
+import {
+ buildStyleReferences,
+ createFillPaints,
+ createStrokePaints,
+ getOrCreateNodeGuid,
+ instanceGuidResolver,
+ isDescendantOf,
+ type KiwiSymbolOverridePayload,
+ type SceneNodeToKiwiContext,
+ type StyleReference
+} from './context'
+
+function exportedTextStyleReference(context: SceneNodeToKiwiContext, id: string): StyleReference {
+ context.styleReferences ??= buildStyleReferences(context.graph)
+ const mapped = context.nodeIdToGuid?.get(id)
+ if (mapped) return { guid: mapped }
+ return context.styleReferences.get(id) ?? { guid: stringToGuid(id) }
+}
+
+function unscaledRootSize(instance: SceneNode, target: SceneNode): Vector {
+ const scale = instance.componentScale
+ if (!Number.isFinite(scale) || scale <= 0) throw new Error('Invalid instance uniform scale')
+ return { x: target.width / scale, y: target.height / scale }
+}
+
+function exportedSwapOverride(
+ context: SceneNodeToKiwiContext,
+ target: SceneNode,
+ path: GUID[] | undefined,
+ counter: { value: number }
+): KiwiSymbolOverridePayload | undefined {
+ if (!path || target.type !== 'INSTANCE' || !target.componentId) return undefined
+ const component = getOrCreateNodeGuid(context, target.componentId, counter)
+ return component ? { guidPath: { guids: path }, overriddenSymbolID: component } : undefined
+}
+
+/** Layout modes are dimensionless; sizing modes map to Figma's implicit-size vocabulary. */
+function layoutModeClaim(raw: string, value: unknown): Record<string, unknown> | undefined {
+ if (typeof value !== 'string' && typeof value !== 'number') return undefined
+ if (raw === 'stackPrimarySizing' || raw === 'stackCounterSizing')
+ return { [raw]: value === 'HUG' ? 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE' : 'FIXED' }
+ return { [raw]: value }
+}
+
+/** Layout distances are placed-space lengths; claims are written in the owner's pre-scale space. */
+function layoutDistanceClaim(
+ raw: string,
+ value: unknown,
+ instance: SceneNode
+): Record<string, number> | undefined {
+ if (typeof value !== 'number') return undefined
+ const scale = instance.componentScale
+ if (!Number.isFinite(scale) || scale <= 0) throw new Error('Invalid instance uniform scale')
+ return { [raw]: value / scale }
+}
+
+interface ClaimInput {
+ context: SceneNodeToKiwiContext
+ instance: SceneNode
+ target: SceneNode
+ /** The recorded override value, when the override stored one. */
+ value: unknown
+}
+
+/**
+ * The claim an instance override serializes to, by the kind of its scene field. This is the
+ * export side of the same registry materialization records claims from.
+ */
+function registryClaim(
+ field: keyof SceneNode,
+ { context, instance, target, value }: ClaimInput
+): Omit<KiwiSymbolOverridePayload, 'guidPath'> | undefined {
+ const entry = SCENE_OVERRIDE_FIELDS.get(field)
+ if (!entry) return undefined
+ const { raw, field: definition } = entry
+ switch (definition.kind) {
+ case 'scalar':
+ return { [raw]: target[field] }
+ case 'visible':
+ return { visible: target.visible }
+ case 'text':
+ return { textData: { characters: typeof value === 'string' ? value : target.text } }
+ case 'text-style':
+ return target.textStyleId
+ ? { styleIdForText: exportedTextStyleReference(context, target.textStyleId) }
+ : undefined
+ case 'paint':
+ return raw === 'fillPaints'
+ ? { fillPaints: createFillPaints(context, target) }
+ : { strokePaints: createStrokePaints(context, target) }
+ case 'size':
+ return { size: unscaledRootSize(instance, target) }
+ case 'layout-distance':
+ return layoutDistanceClaim(raw, target[field], instance)
+ case 'layout-mode':
+ return layoutModeClaim(raw, target[field])
+ default:
+ return undefined
+ }
+}
+
+function paintBindingOverride(
+ context: SceneNodeToKiwiContext,
+ target: SceneNode,
+ bindingField: string
+): Partial<Pick<KiwiSymbolOverridePayload, 'fillPaints' | 'strokePaints'>> | undefined {
+ if (/^fills\/\d+\/color$/.test(bindingField))
+ return { fillPaints: createFillPaints(context, target) }
+ if (/^strokes\/\d+\/color$/.test(bindingField))
+ return { strokePaints: createStrokePaints(context, target) }
+ return undefined
+}
+
+/** A binding override is a paint claim for paint colours and a consumption entry otherwise. */
+function bindingClaim(
+ { context, instance, target }: ClaimInput,
+ field: string
+): Omit<KiwiSymbolOverridePayload, 'guidPath'> | undefined {
+ const bindingField = field.slice('boundVariables/'.length)
+ const paints = paintBindingOverride(context, target, bindingField)
+ if (paints) return paints
+ const entry = overrideVariableBindingEntry(
+ bindingField,
+ target,
+ instance,
+ context.graph,
+ context.varIdToGuid
+ )
+ return entry ? { parameterConsumptionMap: { entries: [entry] } } : undefined
+}
+
+function overrideClaim(
+ input: ClaimInput,
+ field: string,
+ path: GUID[],
+ counter: { value: number }
+): KiwiSymbolOverridePayload | undefined {
+ if (field === 'componentId')
+ return exportedSwapOverride(input.context, input.target, path, counter)
+ const claim = field.startsWith('boundVariables/')
+ ? bindingClaim(input, field)
+ : registryClaim(field as keyof SceneNode, input)
+ return claim && { guidPath: { guids: path }, ...claim }
+}
+
+/** Every override recorded on this instance and on instances inside it, as full-path claims. */
+export function serializeRuntimePropertyOverrides(
+ context: SceneNodeToKiwiContext,
+ instance: SceneNode,
+ localIdCounter: { value: number }
+): KiwiSymbolOverridePayload[] {
+ const result: KiwiSymbolOverridePayload[] = []
+ const resolveGuid = instanceGuidResolver(context, localIdCounter)
+ const resolveTarget = (owner: SceneNode, nodeId: string) => {
+ const targetId = nodeId || owner.id
+ const target = context.graph.getNode(targetId)
+ if (!target || (target.id !== instance.id && !isDescendantOf(context, targetId, instance.id)))
+ return undefined
+ const path = instanceExportAddress(context.graph, instance, target, resolveGuid)
+ return path ? { target, path } : undefined
+ }
+ const visit = (node: SceneNode): void => {
+ if (node.type === 'INSTANCE')
+ forEachInstanceOverride(node.instanceOverrides, (nodeId, field, value) => {
+ const resolved = resolveTarget(node, nodeId)
+ if (!resolved) return
+ const claim = overrideClaim(
+ { context, instance, target: resolved.target, value },
+ field,
+ resolved.path,
+ localIdCounter
+ )
+ if (claim) result.push(claim)
+ })
+ for (const child of context.graph.getChildren(node.id)) visit(child)
+ }
+ visit(instance)
+ return result
+}
+
+function overridePathKey(payload: KiwiSymbolOverridePayload): string | null {
+ const guids = payload.guidPath?.guids
+ return guids?.length
+ ? guids.map(({ sessionID, localID }) => `${sessionID}:${localID}`).join('/')
+ : null
+}
+
+export function mergeOverrides(
+ symbolOverrides: KiwiSymbolOverridePayload[],
+ newOverrides: KiwiSymbolOverridePayload[]
+): void {
+ for (const override of newOverrides) {
+ const pathKey = overridePathKey(override)
+ let existingIndex = -1
+ if (pathKey) {
+ for (let index = symbolOverrides.length - 1; index >= 0; index--) {
+ if (overridePathKey(symbolOverrides[index]) !== pathKey) continue
+ existingIndex = index
+ break
+ }
+ }
+ if (existingIndex < 0) symbolOverrides.push(override)
+ else
+ symbolOverrides[existingIndex] = {
+ ...symbolOverrides[existingIndex],
+ ...override,
+ ...mergeVariableConsumptionMaps(symbolOverrides[existingIndex], override)
+ }
+ }
+}
diff --git a/packages/fig/src/node-change/export-runtime.ts b/packages/fig/src/node-change/export/runtime.ts
similarity index 87%
rename from packages/fig/src/node-change/export-runtime.ts
rename to packages/fig/src/node-change/export/runtime.ts
index c94591d6a..f32fb5062 100644
--- a/packages/fig/src/node-change/export-runtime.ts
+++ b/packages/fig/src/node-change/export/runtime.ts
@@ -1,4 +1,4 @@
-import type { OutlineCommand } from './path/commands'
+import type { OutlineCommand } from '../path/commands'
export interface FigGlyphOutlineMetric {
commands: OutlineCommand[]
diff --git a/packages/fig/src/node-change/index.ts b/packages/fig/src/node-change/index.ts
index 68841c7cb..958ef0e6b 100644
--- a/packages/fig/src/node-change/index.ts
+++ b/packages/fig/src/node-change/index.ts
@@ -3,8 +3,8 @@ export * from './canvas-guides'
export * from './convert'
export * from './derived-text-data'
export * from './derived-text-glyphs'
-export * from './export-node'
-export * from './export-runtime'
+export * from './export/node'
+export * from './export/runtime'
export * from './font/features'
export * from './font/style'
export * from './font/variations'
diff --git a/packages/fig/src/node-change/instance-geometry.ts b/packages/fig/src/node-change/instance-geometry.ts
new file mode 100644
index 000000000..f25ba33f3
--- /dev/null
+++ b/packages/fig/src/node-change/instance-geometry.ts
@@ -0,0 +1,107 @@
+import type { GUID } from '@open-pencil/kiwi/fig/codec'
+import {
+ findInstanceAncestor,
+ getInstanceOverride,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import type { DerivedSymbolOverride } from '../instance-overrides/types'
+
+type ResolveGuid = (id: string) => GUID | undefined
+
+export function instanceExportAddress(
+ graph: SceneGraph,
+ owner: SceneNode,
+ target: SceneNode,
+ resolveGuid: ResolveGuid
+): GUID[] | undefined {
+ if (target.id === owner.id && owner.componentId) {
+ const guid = resolveGuid(owner.componentId)
+ return guid ? [guid] : undefined
+ }
+ const boundaries: SceneNode[] = []
+ let parent = target.parentId ? graph.getNode(target.parentId) : undefined
+ while (parent && parent.id !== owner.id) {
+ if (parent.type === 'INSTANCE') boundaries.unshift(parent)
+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
+ }
+ if (!parent) return undefined
+ const path: GUID[] = []
+ let scope = owner
+ for (const node of [...boundaries, target]) {
+ const sourceId = definitionSource(graph, sourceOf(scope, node))
+ if (!sourceId) return undefined
+ const guid = resolveGuid(sourceId)
+ if (!guid) return undefined
+ path.push(guid)
+ scope = node
+ }
+ return path
+}
+
+function sourceOf(scope: SceneNode, node: SceneNode): string | null {
+ const mapped = getInstanceOverride(
+ scope.instanceOverrides,
+ scope.id,
+ node.id,
+ 'sourceComponentId'
+ )
+ return typeof mapped === 'string' ? mapped : node.componentId
+}
+
+/**
+ * Only definition-level nodes are written as records, so a path segment must name one.
+ * A source that itself sits inside an instance (a nested instance's child as seen from the
+ * enclosing component) resolves through its own correspondence until it leaves every instance.
+ */
+function definitionSource(graph: SceneGraph, id: string | null): string | undefined {
+ const seen = new Set<string>()
+ let current = id ? graph.getNode(id) : undefined
+ while (current) {
+ const owner = current.parentId ? findInstanceAncestor(graph, current.parentId) : undefined
+ if (!owner) return current.id
+ if (seen.has(current.id)) return undefined
+ seen.add(current.id)
+ const next = sourceOf(owner, current)
+ current = next ? graph.getNode(next) : undefined
+ }
+ return undefined
+}
+
+/** Derived geometry is a snapshot, not an authored size or position claim. */
+export function snapshotInstanceGeometry(
+ graph: SceneGraph,
+ owner: SceneNode,
+ resolveGuid: ResolveGuid,
+ retained: DerivedSymbolOverride[],
+ geometry: (node: SceneNode) => Pick<DerivedSymbolOverride, 'size' | 'transform'>
+): DerivedSymbolOverride[] {
+ const key = (path: GUID[]) => path.map((guid) => `${guid.sessionID}:${guid.localID}`).join('/')
+ const entries = new Map<string, DerivedSymbolOverride>()
+ const unaddressed: DerivedSymbolOverride[] = []
+ for (const entry of retained) {
+ if (!entry.guidPath?.guids?.length) {
+ unaddressed.push(entry)
+ continue
+ }
+ const id = key(entry.guidPath.guids)
+ entries.set(id, { ...entries.get(id), ...entry })
+ }
+ const visited = new Set<string>()
+ const visit = (node: SceneNode): void => {
+ for (const child of graph.getChildren(node.id)) {
+ const path = instanceExportAddress(graph, owner, child, resolveGuid)
+ if (!path)
+ throw new Error(`Missing instance geometry address for ${child.id} under ${owner.id}`)
+ const id = key(path)
+ if (visited.has(id))
+ throw new Error(`Ambiguous instance geometry address ${id} under ${owner.id}`)
+ visited.add(id)
+ entries.set(id, { ...entries.get(id), guidPath: { guids: path }, ...geometry(child) })
+ visit(child)
+ }
+ }
+ visit(owner)
+ return [...unaddressed, ...entries.values()]
+}
diff --git a/packages/fig/src/node-change/plugin-data.ts b/packages/fig/src/node-change/plugin-data.ts
index d787df47e..4a0f7e75c 100644
--- a/packages/fig/src/node-change/plugin-data.ts
+++ b/packages/fig/src/node-change/plugin-data.ts
@@ -1,3 +1,5 @@
+import { omit } from 'es-toolkit/object'
+
import type { NodeChange, PluginData, PluginRelaunchData } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
import {
@@ -12,7 +14,12 @@ import {
import type { Rect } from '@open-pencil/scene-graph/primitives'
import { readEffectiveFigmaRawField } from '../source-metadata'
-import { resolveVariableConsumptionEntry } from './variable-bindings'
+import {
+ resolveVariableConsumptionEntry,
+ variableConsumptionEntries,
+ VARIABLE_BINDING_FIELDS_INVERSE,
+ referencesVariable
+} from './variable-bindings'
export const OPEN_PENCIL_PLUGIN_ID = 'open-pencil'
export const TEXT_DIRECTION_PLUGIN_KEY = 'textDirection'
@@ -116,12 +123,16 @@ function parseBoundVariablesPluginValue(value: string | null): Record<string, st
}
export function extractBoundVariables(nc: NodeChange): Record<string, string> {
- const bindings = parseBoundVariablesPluginValue(
+ let bindings = parseBoundVariablesPluginValue(
getOpenPencilPluginValue(nc, BOUND_VARIABLES_PLUGIN_KEY)
)
- for (const entry of nc.variableConsumptionMap?.entries ?? []) {
+ for (const entry of variableConsumptionEntries(nc)) {
const binding = resolveVariableConsumptionEntry(entry)
if (binding) bindings[binding.field] = binding.variableId
+ else if (entry.variableField && !referencesVariable(entry.variableData?.dataType)) {
+ const field = VARIABLE_BINDING_FIELDS_INVERSE[entry.variableField]
+ if (field) bindings = omit(bindings, [field])
+ }
}
nc.fillPaints?.forEach((paint, i) => {
const variableGuid =
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index e3e15bd82..5a1d5b817 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -3,9 +3,8 @@ import { normalizeFontFamily, weightToStyle } from '@open-pencil/scene-graph'
import { effectiveFigmaRawNodeFields } from '../source-metadata'
import { computeExportTransform, fractionalPosition, mapToFigmaType } from './basics'
import { bytesToHex } from './bytes'
-import { VARIABLE_BINDING_FIELDS } from './convert'
import { buildDerivedTextData as buildSharedDerivedTextData } from './derived-text-data'
-import { EMPTY_EXPORT_RUNTIME, type FigNodeChangeExportRuntime } from './export-runtime'
+import { EMPTY_EXPORT_RUNTIME, type FigNodeChangeExportRuntime } from './export/runtime'
import { applyFontFeaturesToKiwi } from './font/features'
import { weightToFigmaStyle } from './font/style'
import { fillToKiwiPaint, safeColor } from './paint'
@@ -14,8 +13,13 @@ import {
BOUND_VARIABLES_PLUGIN_KEY,
LAYOUT_DIRECTION_PLUGIN_KEY,
TEXT_DIRECTION_PLUGIN_KEY,
- upsertPluginData
+ upsertPluginData,
+ OPEN_PENCIL_PLUGIN_ID
} from './plugin-data'
+import {
+ exportedVariableConsumptionEntries,
+ mergeVariableConsumptionMaps
+} from './variable-bindings'
import {
buildStyleOverrideTable,
encodeVectorNetworkBlob,
@@ -28,9 +32,9 @@ export {
FIG_KIWI_DEFAULT_VERSION,
parseFigKiwiChunks
} from '@open-pencil/kiwi/fig/container'
-import type { NodeChange, VariableConsumptionEntry } from '@open-pencil/kiwi/fig/codec'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { GUID, JSONObject } from '@open-pencil/scene-graph/primitives'
import {
@@ -38,8 +42,9 @@ import {
buildComponentPropIndex,
sceneNodeToKiwiWithContext,
type KiwiNodeChange
-} from './export-node'
+} from './export/node'
import { exportTextData, fontVariationToKiwi } from './text-data-export'
+import { toKiwiWindingRule } from './vector-geometry'
function textLines(text: string): NonNullable<NodeChange['textData']>['lines'] {
const lineCount = Math.max(1, text.split('\n').length)
@@ -187,23 +192,6 @@ function serializeCornerRadii(node: SceneNode, nc: KiwiNodeChange): void {
}
}
-function resolveTextAutoResize(node: SceneNode, graph: SceneGraph): SceneNode['textAutoResize'] {
- // For nodes imported from .fig files, preserve the original textAutoResize
- // value. Forcing 'HEIGHT' for fixed-height text inside auto-layout causes
- // layout drift on roundtrip.
- if (node.source.id) return node.textAutoResize
- const parent = node.parentId ? graph.getNode(node.parentId) : undefined
- if (
- parent &&
- parent.layoutMode !== 'NONE' &&
- parent.layoutMode !== 'GRID' &&
- node.layoutPositioning !== 'ABSOLUTE'
- ) {
- return 'HEIGHT'
- }
- return node.textAutoResize
-}
-
function serializeTextProps(
node: SceneNode,
nc: KiwiNodeChange,
@@ -224,7 +212,7 @@ function serializeTextProps(
if (node.fontVariations.length > 0) {
nc.fontVariations = node.fontVariations.map(fontVariationToKiwi)
}
- const autoResize = resolveTextAutoResize(node, graph)
+ const autoResize = node.textAutoResize
const rawNodeFields = effectiveFigmaRawNodeFields(node)
if (!node.source.id || autoResize !== 'NONE' || 'textAutoResize' in rawNodeFields) {
nc.textAutoResize = autoResize
@@ -337,6 +325,40 @@ function serializeSizeConstraints(node: SceneNode, nc: KiwiNodeChange): void {
}
}
+function exportSizing(value: SceneNode['primaryAxisSizing']) {
+ return value === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'
+}
+
+function applyEditedLayoutFields(node: SceneNode, nc: KiwiNodeChange): void {
+ const values: Partial<Record<keyof SceneNode, Partial<KiwiNodeChange>>> = {
+ layoutMode: { stackMode: normalizeStackMode(node.layoutMode) },
+ itemSpacing: { stackSpacing: node.itemSpacing },
+ paddingLeft: { stackHorizontalPadding: node.paddingLeft },
+ paddingRight: { stackPaddingRight: node.paddingRight },
+ paddingTop: { stackVerticalPadding: node.paddingTop },
+ paddingBottom: { stackPaddingBottom: node.paddingBottom },
+ primaryAxisSizing: { stackPrimarySizing: exportSizing(node.primaryAxisSizing) },
+ counterAxisSizing: { stackCounterSizing: exportSizing(node.counterAxisSizing) },
+ primaryAxisAlign: { stackPrimaryAlignItems: normalizeStackJustify(node.primaryAxisAlign) },
+ counterAxisAlign: {
+ stackCounterAlignItems: normalizeStackCounterAlignItems(node.counterAxisAlign)
+ },
+ layoutGrow: { stackChildPrimaryGrow: node.layoutGrow },
+ layoutAlignSelf: { stackChildAlignSelf: node.layoutAlignSelf },
+ layoutPositioning: { stackPositioning: node.layoutPositioning },
+ layoutWrap: { stackWrap: node.layoutWrap },
+ counterAxisSpacing: { stackCounterSpacing: node.counterAxisSpacing },
+ strokesIncludedInLayout: { bordersTakeSpace: node.strokesIncludedInLayout },
+ itemReverseZIndex: { stackReverseZIndex: node.itemReverseZIndex }
+ }
+ for (const field of node.source.editedFields) {
+ if (field in values) Object.assign(nc, values[field as keyof SceneNode])
+ }
+ if (node.source.editedFields.includes('layoutDirection')) {
+ upsertPluginData(node, LAYOUT_DIRECTION_PLUGIN_KEY, node.layoutDirection)
+ }
+}
+
function serializeLayoutProps(node: SceneNode, nc: KiwiNodeChange, graph: SceneGraph): void {
if (!node.source.id) upsertPluginData(node, LAYOUT_DIRECTION_PLUGIN_KEY, node.layoutDirection)
serializeSizeConstraints(node, nc)
@@ -377,6 +399,7 @@ function serializeLayoutProps(node: SceneNode, nc: KiwiNodeChange, graph: SceneG
nc.bordersTakeSpace = figLayout.bordersTakeSpace
if (figLayout.stackReverseZIndex) nc.stackReverseZIndex = true
serializeInheritedCounterAxisStretch(node, nc, graph)
+ applyEditedLayoutFields(node, nc)
return
}
if (node.layoutMode !== 'NONE' && node.layoutMode !== 'GRID') {
@@ -386,8 +409,8 @@ function serializeLayoutProps(node: SceneNode, nc: KiwiNodeChange, graph: SceneG
nc.stackHorizontalPadding = node.paddingLeft
nc.stackPaddingBottom = node.paddingBottom
nc.stackPaddingRight = node.paddingRight
- nc.stackPrimarySizing = node.primaryAxisSizing === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'
- nc.stackCounterSizing = node.counterAxisSizing === 'HUG' ? 'RESIZE_TO_FIT' : 'FIXED'
+ nc.stackPrimarySizing = exportSizing(node.primaryAxisSizing)
+ nc.stackCounterSizing = exportSizing(node.counterAxisSizing)
nc.stackPrimaryAlignItems = normalizeStackJustify(node.primaryAxisAlign)
nc.stackCounterAlignItems = normalizeStackCounterAlignItems(node.counterAxisAlign)
if (node.layoutWrap === 'WRAP') nc.stackWrap = 'WRAP'
@@ -427,11 +450,18 @@ function serializeGeometry(node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Arra
const blobIdx = blobs.length
blobs.push(geometry.commandsBlob)
if (!geometry.fills || geometry.fills.length === 0) {
- return { windingRule: geometry.windingRule, commandsBlob: blobIdx }
+ return {
+ windingRule: toKiwiWindingRule(geometry.windingRule),
+ commandsBlob: blobIdx
+ }
}
const styleID = styleOverrides.length + 1
styleOverrides.push({ styleID, fillPaints: geometry.fills.map(fillToKiwiPaint) })
- return { windingRule: geometry.windingRule, commandsBlob: blobIdx, styleID }
+ return {
+ windingRule: toKiwiWindingRule(geometry.windingRule),
+ commandsBlob: blobIdx,
+ styleID
+ }
})
}
@@ -442,7 +472,7 @@ function serializeGeometry(node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Arra
nc.strokeGeometry = node.strokeGeometry.map((g) => {
const blobIdx = blobs.length
blobs.push(g.commandsBlob)
- return { windingRule: g.windingRule, commandsBlob: blobIdx }
+ return { windingRule: toKiwiWindingRule(g.windingRule), commandsBlob: blobIdx }
})
}
}
@@ -453,32 +483,46 @@ function serializeVariableBindings(
graph: SceneGraph,
varIdToGuid?: Map<string, GUID>
): void {
- if (Object.keys(node.boundVariables).length === 0) return
- const entries: VariableConsumptionEntry[] = []
+ const entries = exportedVariableConsumptionEntries(node, graph, varIdToGuid)
const roundtripBindings: Record<string, string> = {}
- const typeMap: Record<string, string> = { COLOR: 'COLOR', BOOLEAN: 'BOOLEAN', STRING: 'STRING' }
for (const [field, varId] of Object.entries(node.boundVariables)) {
const variable = graph.variables.get(varId)
if (!variable) continue
const varGuid = varIdToGuid?.get(varId) ?? stringToGuid(varId)
roundtripBindings[field] = guidToString(varGuid)
-
- const kiwiField = VARIABLE_BINDING_FIELDS[field]
- if (!kiwiField) continue
- const resolvedType = typeMap[variable.type] ?? 'FLOAT'
- entries.push({
- variableData: {
- value: { alias: { guid: varGuid } },
- dataType: 'ALIAS',
- resolvedDataType: resolvedType
- },
- variableField: kiwiField
- })
}
- if (Object.keys(roundtripBindings).length > 0) {
+ if (
+ Object.keys(roundtripBindings).length > 0 ||
+ node.pluginData.some(
+ (entry) =>
+ entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === BOUND_VARIABLES_PLUGIN_KEY
+ )
+ ) {
upsertPluginData(node, BOUND_VARIABLES_PLUGIN_KEY, JSON.stringify(roundtripBindings))
}
- if (entries.length > 0) nc.variableConsumptionMap = { entries }
+ if (entries.length > 0) {
+ nc.variableConsumptionMap = { entries }
+ Object.assign(
+ nc,
+ mergeVariableConsumptionMaps(effectiveFigmaRawNodeFields(node), {
+ parameterConsumptionMap: { entries }
+ })
+ )
+ }
+}
+
+/** Identity maps and caches one document shares across every node it serializes. */
+export interface SceneNodeToKiwiOptions {
+ nodeIdToGuid?: Map<string, GUID>
+ fontDigestMap?: Map<string, Uint8Array>
+ varIdToGuid?: Map<string, GUID>
+ glyphBlobMap?: Map<string, number>
+ blobIndexByHex?: Map<string, number>
+ assignedGuidValues?: Set<string>
+ runtime?: FigNodeChangeExportRuntime
+ componentPropertyDefinitionsById?: ReadonlyMap<string, ComponentPropertyDefinition>
+ modeIdToGuid?: Map<string, GUID>
+ propertyIdToGuid?: Map<string, GUID>
}
export function sceneNodeToKiwi(
@@ -488,17 +532,20 @@ export function sceneNodeToKiwi(
localIdCounter: { value: number },
graph: SceneGraph,
blobs: Uint8Array[],
- nodeIdToGuid?: Map<string, GUID>,
- fontDigestMap?: Map<string, Uint8Array>,
- varIdToGuid?: Map<string, GUID>,
- glyphBlobMap = new Map<string, number>(),
- blobIndexByHex?: Map<string, number>,
- assignedGuidValues?: Set<string>,
- runtime: FigNodeChangeExportRuntime = EMPTY_EXPORT_RUNTIME,
- componentPropertyDefinitionsById = buildComponentPropIndex(graph),
- modeIdToGuid?: Map<string, GUID>,
- propertyIdToGuid = new Map<string, GUID>()
+ options: SceneNodeToKiwiOptions = {}
): KiwiNodeChange[] {
+ const {
+ nodeIdToGuid,
+ fontDigestMap,
+ varIdToGuid,
+ glyphBlobMap = new Map<string, number>(),
+ blobIndexByHex,
+ assignedGuidValues,
+ runtime = EMPTY_EXPORT_RUNTIME,
+ componentPropertyDefinitionsById = buildComponentPropIndex(graph),
+ modeIdToGuid,
+ propertyIdToGuid = new Map<string, GUID>()
+ } = options
// Raw paints retain library asset refs; effects use this map because their
// Kiwi schema accepts only GUID-backed aliases.
const assetRefToVarGuid = varIdToGuid ? buildAssetRefToVarGuidMap(graph, varIdToGuid) : undefined
diff --git a/packages/fig/src/node-change/style-refs.ts b/packages/fig/src/node-change/style-refs.ts
index dea557eea..2378a6f01 100644
--- a/packages/fig/src/node-change/style-refs.ts
+++ b/packages/fig/src/node-change/style-refs.ts
@@ -19,12 +19,7 @@ type StyleSource = Pick<
| 'fillPaints'
| 'effects'
| 'layoutGrids'
- | 'fontSize'
- | 'fontName'
- | 'lineHeight'
- | 'letterSpacing'
- | 'textDecoration'
- | 'textCase'
+ | (typeof TEXT_STYLE_FIELDS)[number]
>
type StyleChangeMap = ReadonlyMap<string, Partial<StyleSource>>
diff --git a/packages/fig/src/node-change/variable-bindings.ts b/packages/fig/src/node-change/variable-bindings.ts
index c9d2a9315..24b7ee6ee 100644
--- a/packages/fig/src/node-change/variable-bindings.ts
+++ b/packages/fig/src/node-change/variable-bindings.ts
@@ -1,6 +1,14 @@
-import type { VariableConsumptionEntry } from '@open-pencil/kiwi/fig/codec'
-import { guidToString } from '@open-pencil/kiwi/fig/guid'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import type { VariableConsumptionEntry, GUID } from '@open-pencil/kiwi/fig/codec'
+import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'
+import {
+ isNumericVariableBindingField,
+ type SceneNode,
+ type SceneGraph
+} from '@open-pencil/scene-graph'
+
+import { effectiveFigmaRawNodeFields } from '../source-metadata'
+import { cloneRecord } from './clone'
+import { linearVariableExpression } from './variable-expression'
export const VARIABLE_BINDING_FIELDS: Record<string, string> = {
cornerRadius: 'CORNER_RADIUS',
@@ -21,6 +29,7 @@ export const VARIABLE_BINDING_FIELDS: Record<string, string> = {
counterAxisSpacing: 'STACK_COUNTER_SPACING',
gridRowGap: 'GRID_ROW_GAP',
gridColumnGap: 'GRID_COLUMN_GAP',
+ text: 'TEXT_DATA',
visible: 'VISIBLE',
opacity: 'OPACITY',
width: 'WIDTH',
@@ -42,9 +51,150 @@ export const VARIABLE_BINDING_FIELDS_INVERSE: Record<string, string> = Object.fr
Object.entries(VARIABLE_BINDING_FIELDS).map(([field, kiwiField]) => [kiwiField, field])
)
+interface VariableConsumptionSource extends Record<string, unknown> {
+ variableConsumptionMap?: { entries?: VariableConsumptionEntry[] }
+ parameterConsumptionMap?: unknown
+}
+
+/** Modern parameter entries follow legacy entries and can explicitly clear them. */
+/**
+ * A bound opacity is authored as a percentage and stored as a unit fraction, so every
+ * conversion between the two forms goes through this factor.
+ */
+const OPACITY_UNIT_PER_PERCENT = 0.01
+
+/** Only an alias or an expression carries a variable reference worth resolving. */
+export function referencesVariable(dataType: string | undefined): boolean {
+ return dataType === 'ALIAS' || dataType === 'EXPRESSION'
+}
+
+export function variableConsumptionEntries(
+ node: VariableConsumptionSource
+): VariableConsumptionEntry[] {
+ const parameters = node.parameterConsumptionMap as
+ | { entries?: VariableConsumptionEntry[] }
+ | undefined
+ const fields = new Map<string, VariableConsumptionEntry>()
+ const unkeyed: VariableConsumptionEntry[] = []
+ for (const entry of [
+ ...(node.variableConsumptionMap?.entries ?? []),
+ ...(parameters?.entries ?? [])
+ ]) {
+ if (entry.variableField) fields.set(entry.variableField, entry)
+ else unkeyed.push(entry)
+ }
+ return [...unkeyed, ...fields.values()]
+}
+
+export function mergeVariableConsumptionMaps(
+ base: VariableConsumptionSource,
+ patch: VariableConsumptionSource
+): Record<string, unknown> {
+ const incoming = variableConsumptionEntries(patch)
+ if (incoming.length === 0) return {}
+ const entries: VariableConsumptionEntry[] = []
+ for (const entry of [...variableConsumptionEntries(base), ...incoming]) {
+ const index = entry.variableField
+ ? entries.findIndex((previous) => previous.variableField === entry.variableField)
+ : -1
+ if (index < 0) entries.push(cloneRecord(entry))
+ else entries[index] = cloneRecord(entry)
+ }
+ // VariableDataMap carries nothing but its entries, so the merged list is the whole map.
+ return { parameterConsumptionMap: { entries } }
+}
+
+export function variableBindingEntry(
+ field: string,
+ variableId: string | undefined,
+ graph: SceneGraph,
+ ids?: Map<string, GUID>,
+ multiplier = 1,
+ expression = false
+): VariableConsumptionEntry | undefined {
+ const variableField = VARIABLE_BINDING_FIELDS[field]
+ if (!variableField) return undefined
+ if (!variableId) return { variableField }
+ const variable = graph.variables.get(variableId)
+ if (!variable) throw new Error(`Missing bound variable ${variableId}`)
+ if (!Number.isFinite(multiplier)) throw new Error('Non-finite variable binding multiplier')
+ const alias = {
+ dataType: 'ALIAS',
+ resolvedDataType: variable.type,
+ value: { alias: { guid: ids?.get(variableId) ?? stringToGuid(variableId) } }
+ }
+ if (variable.type !== 'FLOAT' || (!expression && multiplier === 1))
+ return { variableField, variableData: alias }
+ return {
+ variableField,
+ variableData: {
+ dataType: 'EXPRESSION',
+ resolvedDataType: 'FLOAT',
+ value: {
+ expressionValue: {
+ expressionFunction: 'MULTIPLY',
+ expressionArguments: [
+ { dataType: 'FLOAT', resolvedDataType: 'FLOAT', value: { floatValue: multiplier } },
+ alias
+ ]
+ }
+ }
+ }
+ }
+}
+
+function numericBindingUnit(field: string, distanceScale: number): number {
+ if (field === 'opacity') return OPACITY_UNIT_PER_PERCENT
+ if (field === 'rotation') return 1
+ return distanceScale
+}
+
+export function overrideVariableBindingEntry(
+ field: string,
+ target: SceneNode,
+ owner: SceneNode,
+ graph: SceneGraph,
+ ids?: Map<string, GUID>
+): VariableConsumptionEntry | undefined {
+ const units = numericBindingUnit(field, owner.componentScale)
+ const multiplier =
+ target.variableBindingScales[field] === undefined
+ ? 1
+ : target.variableBindingScales[field] / units
+ return variableBindingEntry(field, target.boundVariables[field], graph, ids, multiplier)
+}
+
+export function exportedVariableConsumptionEntries(
+ node: SceneNode,
+ graph: SceneGraph,
+ ids?: Map<string, GUID>
+): VariableConsumptionEntry[] {
+ const fields = new Set(Object.keys(node.boundVariables))
+ for (const entry of variableConsumptionEntries(effectiveFigmaRawNodeFields(node))) {
+ if (!referencesVariable(entry.variableData?.dataType)) continue
+ const field = entry.variableField && VARIABLE_BINDING_FIELDS_INVERSE[entry.variableField]
+ if (field) fields.add(field)
+ }
+ return [...fields].flatMap((field) => {
+ const multiplier =
+ (node.variableBindingScales[field] ?? 1) /
+ (field === 'opacity' ? OPACITY_UNIT_PER_PERCENT : 1)
+ const entry = variableBindingEntry(
+ field,
+ node.boundVariables[field],
+ graph,
+ ids,
+ multiplier,
+ node.type === 'INSTANCE' && node.componentScale !== 1
+ )
+ return entry ? [entry] : []
+ })
+}
+
export interface ResolvedVariableConsumption {
field: string
variableId: string
+ multiplier: number
}
export function resolveVariableConsumptionEntry(
@@ -53,47 +203,59 @@ export function resolveVariableConsumptionEntry(
const field = entry.variableField
? VARIABLE_BINDING_FIELDS_INVERSE[entry.variableField]
: undefined
- const guid = entry.variableData?.value?.alias?.guid
- return field && guid ? { field, variableId: guidToString(guid) } : undefined
+ if (!field) return undefined
+ const expression = linearVariableExpression(entry.variableData)
+ if (entry.variableData?.value?.expressionValue && !expression?.reference)
+ throw new Error('Variable expression must contain one alias')
+ const guid = expression?.reference?.guid
+ return guid
+ ? { field, variableId: guidToString(guid), multiplier: expression.multiplier }
+ : undefined
+}
+
+export function sourceVariableBindingScales(
+ source: VariableConsumptionSource
+): Record<string, number> {
+ const scales: Record<string, number> = {}
+ for (const entry of variableConsumptionEntries(source)) {
+ const binding = resolveVariableConsumptionEntry(entry)
+ if (binding && isNumericVariableBindingField(binding.field)) {
+ scales[binding.field] =
+ binding.multiplier * (binding.field === 'opacity' ? OPACITY_UNIT_PER_PERCENT : 1)
+ }
+ }
+ return scales
}
-const NUMERIC_BINDING_FIELDS = new Set([
- 'cornerRadius',
- 'topLeftRadius',
- 'topRightRadius',
- 'bottomLeftRadius',
- 'bottomRightRadius',
- 'strokeWeight',
- 'borderTopWeight',
- 'borderBottomWeight',
- 'borderLeftWeight',
- 'borderRightWeight',
- 'itemSpacing',
- 'paddingLeft',
- 'paddingTop',
- 'paddingRight',
- 'paddingBottom',
- 'counterAxisSpacing',
- 'gridRowGap',
- 'gridColumnGap',
- 'width',
- 'height',
- 'minWidth',
- 'maxWidth',
- 'minHeight',
- 'maxHeight',
- 'x',
- 'y',
- 'rotation',
- 'fontSize',
- 'letterSpacing',
- 'lineHeight'
-])
+/** Omit identity conversions: most unscaled scopes need only percentage opacity units. */
+export function numericVariableAssignmentScales(layoutScale = 1): Record<string, number> {
+ if (layoutScale === 1) return {}
+ return Object.fromEntries(
+ Object.entries(numericVariableBindingScales(VARIABLE_BINDING_FIELDS, layoutScale)).filter(
+ ([, scale]) => scale !== 1
+ )
+ )
+}
+
+/** Translate Figma numeric bindings into persistent scene-unit conversions. */
+export function numericVariableBindingScales(
+ bindings: Record<string, string>,
+ layoutScale: number,
+ declarationScales: Partial<Record<string, number>> = {}
+): Record<string, number> {
+ const scales: Record<string, number> = {}
+ for (const field of Object.keys(bindings)) {
+ if (!isNumericVariableBindingField(field)) continue
+ scales[field] = declarationScales[field] ?? numericBindingUnit(field, layoutScale)
+ }
+ return scales
+}
export function resolvedNumericBindingUpdate(
field: string,
value: number
): Partial<SceneNode> | undefined {
- if (field === 'opacity') return { opacity: Math.max(0, Math.min(1, value / 100)) }
- return NUMERIC_BINDING_FIELDS.has(field) ? { [field]: value } : undefined
+ if (field === 'opacity')
+ return { opacity: Math.max(0, Math.min(1, value * OPACITY_UNIT_PER_PERCENT)) }
+ return isNumericVariableBindingField(field) ? { [field]: value } : undefined
}
diff --git a/packages/fig/src/node-change/variable-expression.ts b/packages/fig/src/node-change/variable-expression.ts
new file mode 100644
index 000000000..51c0351f9
--- /dev/null
+++ b/packages/fig/src/node-change/variable-expression.ts
@@ -0,0 +1,55 @@
+import type { VariableAnyValue, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'
+
+type Reference = NonNullable<VariableAnyValue['alias']>
+interface LinearValue {
+ multiplier: number
+ reference?: Reference
+}
+const MAX_EXPRESSION_DEPTH = 64
+
+/** Decode only exactly representable constant × alias expressions, never approximate. */
+export function linearVariableExpression(
+ data: VariableDataEntry | undefined,
+ depth = 0
+): LinearValue | undefined {
+ if (depth > MAX_EXPRESSION_DEPTH) throw new Error('Variable expression exceeds maximum depth')
+ const value = data?.value
+ if (data?.dataType === 'EXPRESSION' && !value?.expressionValue)
+ throw new Error('Missing variable expression value')
+ if (!value) return undefined
+ if (value.alias) return { multiplier: 1, reference: value.alias }
+ if (typeof value.floatValue === 'number' && Number.isFinite(value.floatValue))
+ return { multiplier: value.floatValue }
+ const expression = value.expressionValue
+ if (!expression) return undefined
+ if (expression.expressionFunction !== 'MULTIPLY' || !expression.expressionArguments?.length) {
+ throw new Error(`Unsupported variable expression ${expression.expressionFunction}`)
+ }
+ return multiplyLinearValues(expression.expressionArguments, depth)
+}
+
+function multiplyLinearValues(factors: VariableDataEntry[], depth: number): LinearValue {
+ const result: LinearValue = { multiplier: 1 }
+ for (const argument of factors) {
+ const term = linearVariableExpression(argument, depth + 1)
+ if (!term || (result.reference && term.reference))
+ throw new Error('Variable expression is not a constant multiplied by one alias')
+ result.multiplier *= term.multiplier
+ if (term.reference) result.reference = term.reference
+ }
+ if (!Number.isFinite(result.multiplier))
+ throw new Error('Variable expression has a non-finite multiplier')
+ return result
+}
+
+export function visitVariableReferences(
+ data: VariableDataEntry | undefined,
+ visit: (reference: Reference) => void,
+ depth = 0
+): void {
+ if (depth > MAX_EXPRESSION_DEPTH) throw new Error('Variable expression exceeds maximum depth')
+ if (data?.value?.alias) visit(data.value.alias)
+ for (const argument of data?.value?.expressionValue?.expressionArguments ?? []) {
+ visitVariableReferences(argument, visit, depth + 1)
+ }
+}
diff --git a/packages/fig/src/node-change/vector-geometry.ts b/packages/fig/src/node-change/vector-geometry.ts
index 80e06a101..e2d8d07fd 100644
--- a/packages/fig/src/node-change/vector-geometry.ts
+++ b/packages/fig/src/node-change/vector-geometry.ts
@@ -1,11 +1,21 @@
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import type { Fill, GeometryPath, VectorNetwork, WindingRule } from '@open-pencil/scene-graph'
+import type { Fill, GeometryPath, VectorNetwork } from '@open-pencil/scene-graph'
import { copyFills } from '@open-pencil/scene-graph/copy'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import { convertFills } from './paint'
import { decodeVectorNetworkBlob, type StyleOverride } from './vector-network'
+/** Scene winding rules name the even-odd case EVENODD; the archive names it ODD. */
+export function toKiwiWindingRule(rule: string | undefined): 'ODD' | 'NONZERO' {
+ return rule === 'EVENODD' ? 'ODD' : 'NONZERO'
+}
+
+/** The archive's ODD reads back as the scene's EVENODD. */
+export function fromKiwiWindingRule(rule: string | undefined): 'EVENODD' | 'NONZERO' {
+ return rule === 'ODD' || rule === 'EVENODD' ? 'EVENODD' : 'NONZERO'
+}
+
export function alignGeometryWindingRules(
geometry: GeometryPath[],
vectorNetwork: VectorNetwork | null
@@ -104,7 +114,7 @@ export function resolveGeometryPaths(
if (blob.length === 0) continue
const fills = p.styleID ? fillsByStyleId?.get(p.styleID) : undefined
result.push({
- windingRule: (p.windingRule === 'EVENODD' ? 'EVENODD' : 'NONZERO') as WindingRule,
+ windingRule: fromKiwiWindingRule(p.windingRule),
commandsBlob: blob,
fills: fills && fills.length > 0 ? copyFills(fills) : undefined
})
diff --git a/packages/fig/src/node-classification.ts b/packages/fig/src/node-classification.ts
new file mode 100644
index 000000000..4093b4e8a
--- /dev/null
+++ b/packages/fig/src/node-classification.ts
@@ -0,0 +1,32 @@
+const UNSUPPORTED_FRAGMENT_TYPES: ReadonlySet<string> = new Set([
+ 'STYLE',
+ 'STYLE_SET',
+ 'INTERNAL_ONLY_NODE',
+ 'WIDGET',
+ 'STAMP',
+ 'STICKY',
+ 'SHAPE_WITH_TEXT',
+ 'CONNECTOR',
+ 'CODE_BLOCK',
+ 'TABLE_NODE',
+ 'TABLE_CELL',
+ 'SECTION_OVERLAY',
+ 'SLIDE',
+ 'VARIABLE_COLLECTION'
+])
+
+const CONTAINER_AND_RESOURCE_TYPES: ReadonlySet<string> = new Set([
+ 'DOCUMENT',
+ 'CANVAS',
+ 'VARIABLE_SET',
+ 'VARIABLE'
+])
+
+export function isUnsupportedFigFragmentType(type: string | undefined): boolean {
+ return UNSUPPORTED_FRAGMENT_TYPES.has(type ?? '')
+}
+
+/** Clipboard bounds exclude containers, resources, and unsupported scene records. */
+export function isFigClipboardVisualType(type: string | undefined): boolean {
+ return !!type && !CONTAINER_AND_RESOURCE_TYPES.has(type) && !isUnsupportedFigFragmentType(type)
+}
diff --git a/packages/fig/tests/document/binding/expression.test.ts b/packages/fig/tests/document/binding/expression.test.ts
new file mode 100644
index 000000000..0d94c737f
--- /dev/null
+++ b/packages/fig/tests/document/binding/expression.test.ts
@@ -0,0 +1,72 @@
+import { expect, test } from 'bun:test'
+
+import { linearVariableExpression } from '#fig/node-change/variable-expression'
+
+import { nodeChangeToProps } from '@open-pencil/fig/node-change'
+import type { VariableDataEntry } from '@open-pencil/kiwi/fig/codec'
+
+const alias: VariableDataEntry = {
+ dataType: 'ALIAS',
+ value: { alias: { guid: { sessionID: 1, localID: 2 } } }
+}
+const literal = (floatValue: number): VariableDataEntry => ({
+ dataType: 'FLOAT',
+ value: { floatValue }
+})
+const multiply = (...expressionArguments: VariableDataEntry[]): VariableDataEntry => ({
+ dataType: 'EXPRESSION',
+ value: { expressionValue: { expressionFunction: 'MULTIPLY', expressionArguments } }
+})
+
+test('linear products retain their symbolic alias and exact coefficient', () => {
+ expect(linearVariableExpression(multiply(literal(2), multiply(alias, literal(0.25))))).toEqual({
+ reference: alias.value?.alias,
+ multiplier: 0.5
+ })
+ const props = nodeChangeToProps(
+ {
+ type: 'FRAME',
+ parameterConsumptionMap: {
+ entries: [
+ {
+ variableField: 'OPACITY',
+ variableData: multiply(literal(0.5), alias)
+ }
+ ]
+ }
+ },
+ []
+ )
+ expect(props.boundVariables).toEqual({ opacity: '1:2' })
+ expect(props.variableBindingScales).toEqual({ opacity: 0.005 })
+})
+
+test('nonlinear, unsupported, overflowing, and unbounded expressions fail rather than lose bindings', () => {
+ expect(() => linearVariableExpression(multiply(alias, alias))).toThrow('one alias')
+ expect(() => linearVariableExpression({ dataType: 'EXPRESSION' })).toThrow('Missing')
+ expect(() =>
+ nodeChangeToProps(
+ {
+ type: 'FRAME',
+ parameterConsumptionMap: {
+ entries: [
+ {
+ variableField: 'WIDTH',
+ variableData: multiply(literal(2), literal(3))
+ }
+ ]
+ }
+ },
+ []
+ )
+ ).toThrow('one alias')
+ expect(() =>
+ linearVariableExpression({ value: { expressionValue: { expressionFunction: 'ADD' } } })
+ ).toThrow('Unsupported')
+ expect(() =>
+ linearVariableExpression(multiply(literal(Number.MAX_VALUE), literal(2), alias))
+ ).toThrow('non-finite')
+ let deep = alias
+ for (let index = 0; index < 66; index++) deep = multiply(literal(1), deep)
+ expect(() => linearVariableExpression(deep)).toThrow('maximum depth')
+})
diff --git a/packages/fig/tests/document/binding/modes.test.ts b/packages/fig/tests/document/binding/modes.test.ts
new file mode 100644
index 000000000..3f1eb0278
--- /dev/null
+++ b/packages/fig/tests/document/binding/modes.test.ts
@@ -0,0 +1,104 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { applyDocumentLayoutBindings } from '#fig/document/bindings/layout'
+import { materializeDocument } from '#fig/document/materialize'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('saved occurrence dimensions win over unscaled bindings without blocking spacing', () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Sizes')
+ const variable = graph.createVariable('Size', 'FLOAT', collection.id, 16)
+ const node = graph.createNode('FRAME', graph.getPages()[0].id, {
+ width: 14.253506660461426,
+ height: 14.253506660461426,
+ itemSpacing: 15,
+ boundVariables: { width: variable.id, height: variable.id, itemSpacing: variable.id }
+ })
+ applyDocumentLayoutBindings(graph, new Set([node.id]), [node])
+ expect(node.width).toBe(14.253506660461426)
+ expect(node.height).toBe(14.253506660461426)
+ expect(node.itemSpacing).toBe(16)
+})
+
+test('repeated instances resolve nested bindings using inherited collection modes', () => {
+ const changes = [
+ { guid: guid(1), type: 'DOCUMENT' },
+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'VARIABLE_SET',
+ key: 'collection',
+ version: 'v1',
+ variableSetModes: [
+ { id: guid(10), name: 'Light' },
+ { id: guid(11), name: 'Dark' }
+ ]
+ },
+ {
+ guid: guid(4),
+ type: 'VARIABLE',
+ key: 'width',
+ version: 'v1',
+ variableResolvedType: 'FLOAT',
+ variableSetID: { assetRef: { key: 'collection', version: 'v1' } },
+ variableDataValues: {
+ entries: [10, 11].map((mode) => ({
+ modeID: guid(mode),
+ variableData: { dataType: 'FLOAT', value: { floatValue: mode * 10 } }
+ }))
+ }
+ },
+ { guid: guid(5), type: 'SYMBOL', parentIndex: { guid: guid(2), position: 'a' } },
+ {
+ guid: guid(6),
+ type: 'RECTANGLE',
+ size: { x: 50, y: 20 },
+ parentIndex: { guid: guid(5), position: 'a' }
+ },
+ ...[7, 8].map((id, index) => ({
+ guid: guid(id),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(2), position: String(id) },
+ variableModeBySetMap: {
+ entries: [
+ {
+ variableSetID: { assetRef: { key: 'collection', version: 'v1' } },
+ variableModeID: guid(10 + index)
+ }
+ ]
+ },
+ symbolData: {
+ symbolID: guid(5),
+ symbolOverrides: [
+ {
+ guidPath: { guids: [guid(6)] },
+ variableConsumptionMap: {
+ entries: [
+ {
+ variableField: 'WIDTH',
+ variableData: { value: { alias: { assetRef: { key: 'width', version: 'v1' } } } }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ }))
+ ] as NodeChange[]
+ const { graph, sources } = materializeDocument(changes)
+ for (const [sourceId, expected] of [
+ ['1:7', 100],
+ ['1:8', 110]
+ ] as const) {
+ const id = sources.get(sourceId)
+ if (!id) throw new Error('Missing instance')
+ const child = graph.getChildren(id)[0]
+ expect(child.boundVariables.width).toBe('1:4')
+ const mode = graph.getNodeVariableModeId(child.id, '1:3')
+ expect(graph.resolveVariable(child.boundVariables.width, mode)).toBe(expected)
+ expect(child.width).toBe(expected)
+ }
+})
diff --git a/packages/fig/tests/document/binding/paint-alpha.test.ts b/packages/fig/tests/document/binding/paint-alpha.test.ts
new file mode 100644
index 000000000..40d3b74ee
--- /dev/null
+++ b/packages/fig/tests/document/binding/paint-alpha.test.ts
@@ -0,0 +1,54 @@
+import { expect, test } from 'bun:test'
+
+import { applyDocumentPaintBindings } from '#fig/document/bindings/paint'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function setup(alpha: number, opacity: number) {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Colors')
+ const variable = graph.createVariable('Accent', 'COLOR', collection.id, {
+ r: 1,
+ g: 1,
+ b: 1,
+ a: alpha
+ })
+ const node = graph.createNode('RECTANGLE', graph.getPages()[0].id, {
+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity, visible: true }],
+ boundVariables: { 'fills/0/color': variable.id }
+ })
+ return { graph, node }
+}
+
+/** Drawing takes a solid fill's alpha from its opacity, so the variable has to own it. */
+test('a bound fill takes its alpha from the variable, not the paint', () => {
+ const { graph, node } = setup(0.2, 1)
+ applyDocumentPaintBindings(graph, [node])
+ expect(node.fills[0].color).toEqual({ r: 1, g: 1, b: 1, a: 1 })
+ expect(node.fills[0].opacity).toBeCloseTo(0.2)
+})
+
+/** An opacity left over from an override the binding supersedes must not survive. */
+test('a bound fill replaces a stale opacity rather than combining with it', () => {
+ const { graph, node } = setup(1, 0.5)
+ applyDocumentPaintBindings(graph, [node])
+ expect(node.fills[0].opacity).toBe(1)
+})
+
+test('a bound stroke follows the same rule', () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Colors')
+ const variable = graph.createVariable('Line', 'COLOR', collection.id, {
+ r: 0,
+ g: 0,
+ b: 0,
+ a: 0.4
+ })
+ const node = graph.createNode('RECTANGLE', graph.getPages()[0].id, {
+ strokes: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }],
+ boundVariables: { 'strokes/0/color': variable.id }
+ })
+ applyDocumentPaintBindings(graph, [node])
+ expect(node.strokes[0].color).toEqual({ r: 0, g: 0, b: 0, a: 1 })
+ expect(node.strokes[0].opacity).toBeCloseTo(0.4)
+})
diff --git a/packages/fig/tests/document/binding/references.test.ts b/packages/fig/tests/document/binding/references.test.ts
new file mode 100644
index 000000000..8ee58b58c
--- /dev/null
+++ b/packages/fig/tests/document/binding/references.test.ts
@@ -0,0 +1,109 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { resolveDocumentBindingReferences } from '#fig/document/bindings/references'
+
+import { nodeChangeToProps } from '@open-pencil/fig/node-change'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('shadowed legacy resource references are not treated as required bindings', () => {
+ const diagnostics: unknown[] = []
+ resolveDocumentBindingReferences(
+ [
+ {
+ guid: guid(1),
+ type: 'RECTANGLE',
+ variableConsumptionMap: {
+ entries: [
+ {
+ variableField: 'WIDTH',
+ variableData: {
+ dataType: 'ALIAS',
+ value: { alias: { assetRef: { key: 'retired' } } }
+ }
+ }
+ ]
+ },
+ parameterConsumptionMap: { entries: [{ variableField: 'WIDTH' }] }
+ }
+ ],
+ (diagnostic) => diagnostics.push(diagnostic)
+ )
+ expect(diagnostics).toEqual([])
+})
+
+test('modern explicit clearing removes only the targeted legacy binding', () => {
+ const props = nodeChangeToProps(
+ {
+ type: 'RECTANGLE',
+ variableConsumptionMap: {
+ entries: [
+ { variableField: 'WIDTH', variableData: { value: { alias: { guid: guid(1) } } } },
+ { variableField: 'HEIGHT', variableData: { value: { alias: { guid: guid(2) } } } }
+ ]
+ },
+ parameterConsumptionMap: { entries: [{ variableField: 'WIDTH' }] }
+ },
+ []
+ )
+ expect(props.boundVariables).toEqual({ height: '1:2' })
+})
+
+for (const map of ['variableConsumptionMap', 'parameterConsumptionMap'] as const) {
+ for (const expression of [false, true]) {
+ test(`${map} ${expression ? 'expression' : 'alias'} normalizes versioned references without mutating source records`, () => {
+ const alias = { value: { alias: { assetRef: { key: 'number', version: 'v1' } } } }
+ const variableData = expression
+ ? {
+ dataType: 'EXPRESSION',
+ value: {
+ expressionValue: {
+ expressionFunction: 'MULTIPLY',
+ expressionArguments: [{ value: { floatValue: 0.5 } }, alias]
+ }
+ }
+ }
+ : alias
+ const changes = [
+ { guid: guid(1), type: 'VARIABLE', key: 'number', version: 'v1' },
+ { guid: guid(2), type: 'VARIABLE', key: 'color', version: 'v1' },
+ { guid: guid(3), type: 'VARIABLE_SET', key: 'set', version: 'v1' },
+ {
+ guid: guid(4),
+ type: 'RECTANGLE',
+ [map]: {
+ entries: [
+ {
+ variableField: 'WIDTH',
+ variableData
+ }
+ ]
+ },
+ fillPaints: [
+ {
+ type: 'SOLID',
+ colorVar: { value: { alias: { assetRef: { key: 'color', version: 'v1' } } } }
+ }
+ ],
+ variableModeBySetMap: {
+ entries: [
+ {
+ variableSetID: { assetRef: { key: 'set', version: 'v1' } },
+ variableModeID: guid(10)
+ }
+ ]
+ }
+ }
+ ] as NodeChange[]
+ const before = structuredClone(changes)
+ const diagnostics: unknown[] = []
+ const normalized = resolveDocumentBindingReferences(changes, (d) => diagnostics.push(d))
+ const props = nodeChangeToProps(normalized[3], [])
+ expect(props.boundVariables).toEqual({ width: '1:1', 'fills/0/color': '1:2' })
+ expect(props.variableModes).toEqual({ '1:3': '1:10' })
+ expect(diagnostics).toEqual([])
+ expect(changes).toEqual(before)
+ expect(props.variableBindingScales?.width).toBe(expression ? 0.5 : 1)
+ })
+ }
+}
diff --git a/packages/fig/tests/document/checkpoint.test.ts b/packages/fig/tests/document/checkpoint.test.ts
new file mode 100644
index 000000000..6f088333d
--- /dev/null
+++ b/packages/fig/tests/document/checkpoint.test.ts
@@ -0,0 +1,56 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { checkpointComponent, restoreComponentCheckpoint } from '#fig/document/component/checkpoint'
+import { interpretComponent } from '#fig/instance-overrides/interpret'
+import { materializeInstance } from '#fig/instance-overrides/materialize-instance'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function setup() {
+ const occurrence = interpretComponent(
+ [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1), position: '!' },
+ textData: { characters: 'Original' }
+ }
+ ],
+ '1:1'
+ )
+ const graph = new SceneGraph()
+ const materialized = materializeInstance(graph, graph.getPages()[0].id, occurrence, new Map())
+ const checkpoint = checkpointComponent({ occurrence, materialized })
+ return { graph, occurrence, materialized, checkpoint }
+}
+
+test('compact checkpoint reconnects source paths without overwriting live edits', () => {
+ const { graph, occurrence, materialized, checkpoint } = setup()
+ const child = graph.getChildren(materialized.root.id)[0]
+ graph.updateNode(child.id, { text: 'Edited' })
+ const restored = restoreComponentCheckpoint(graph, occurrence, structuredClone(checkpoint))
+ expect(restored.materialized.nodes.get(occurrence.children[0])).toBe(child)
+ expect(child.text).toBe('Edited')
+ expect(checkpoint.nodes[1].path).toEqual(['1:2'])
+})
+
+for (const corruption of ['missing', 'duplicate', 'path', 'component', 'root'] as const) {
+ test(`reports ${corruption} checkpoint handling before graph mutation`, () => {
+ const { graph, occurrence, checkpoint } = setup()
+ const before = corruption === 'missing' ? null : structuredClone([...graph.nodes])
+ if (corruption === 'missing') {
+ graph.deleteNode(checkpoint.nodes.at(-1)?.nodeId ?? '')
+ checkpoint.nodes.pop()
+ }
+ if (corruption === 'duplicate') checkpoint.nodes.push(checkpoint.nodes[1])
+ if (corruption === 'path') checkpoint.nodes[1].path = ['missing']
+ if (corruption === 'component') checkpoint.nodes[1].mainComponentId = 'other'
+ if (corruption === 'root') checkpoint.rootId = checkpoint.nodes[1].nodeId
+ if (corruption === 'missing')
+ expect(() => restoreComponentCheckpoint(graph, occurrence, checkpoint)).not.toThrow()
+ else expect(() => restoreComponentCheckpoint(graph, occurrence, checkpoint)).toThrow()
+ if (before) expect([...graph.nodes]).toEqual(before)
+ })
+}
diff --git a/packages/fig/tests/document/component-dependencies.test.ts b/packages/fig/tests/document/component-dependencies.test.ts
new file mode 100644
index 000000000..fb7c502c5
--- /dev/null
+++ b/packages/fig/tests/document/component-dependencies.test.ts
@@ -0,0 +1,30 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { componentDependencies } from '#fig/document/component/dependencies'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('collects component dependencies from instances, inactive defaults and nested assignments', () => {
+ const source = {
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [
+ {
+ overriddenSymbolID: guid(2),
+ componentPropAssignments: [
+ { defID: guid(90), varValue: { value: { symbolIdValue: { guid: guid(3) } } } }
+ ]
+ }
+ ]
+ },
+ componentPropDefs: [
+ { type: 'INSTANCE_SWAP', initialValue: { guidValue: guid(4) } },
+ { type: 'TEXT', initialValue: { textValue: '1:999' } }
+ ],
+ componentPropAssignments: [{ defID: guid(91), value: { guidValue: guid(1) } }]
+ } as NodeChange
+ const before = structuredClone(source)
+ expect([...componentDependencies(source)].sort()).toEqual(['1:1', '1:2', '1:3', '1:4'])
+ expect(source).toEqual(before)
+})
diff --git a/packages/fig/tests/document/constraint-resize.test.ts b/packages/fig/tests/document/constraint-resize.test.ts
new file mode 100644
index 000000000..32157c147
--- /dev/null
+++ b/packages/fig/tests/document/constraint-resize.test.ts
@@ -0,0 +1,74 @@
+import { expect, test } from 'bun:test'
+
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+for (const autoLayout of [false, true]) {
+ for (const horizontalConstraint of ['MAX', 'STRETCH'] as const) {
+ test(`resized occurrence applies ${horizontalConstraint} constraints without repair (auto-layout=${autoLayout})`, () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const changes: NodeChange[] = [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ stackMode: autoLayout ? 'HORIZONTAL' : 'NONE',
+ size: { x: 100, y: 80 },
+ parentIndex: { guid: guid(1), position: '!' }
+ },
+ {
+ guid: guid(3),
+ type: 'RECTANGLE',
+ parentIndex: { guid: guid(2), position: '!' },
+ size: { x: horizontalConstraint === 'MAX' ? 10 : 80, y: 60 },
+ transform: {
+ m00: 1,
+ m01: 0,
+ m02: horizontalConstraint === 'MAX' ? 80 : 10,
+ m10: 0,
+ m11: 1,
+ m12: 10
+ },
+ horizontalConstraint,
+ stackPositioning: 'ABSOLUTE',
+ verticalConstraint: 'STRETCH'
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ size: { x: 200, y: 120 },
+ symbolData: { symbolID: guid(2) }
+ }
+ ]
+ const { graph, sources } = materializeDocument(changes)
+ const instance = sources.get('1:4')
+ if (!instance) throw new Error('Missing instance')
+ expect(graph.getChildren(instance)[0]).toMatchObject({
+ x: horizontalConstraint === 'MAX' ? 180 : 10,
+ y: 10,
+ width: horizontalConstraint === 'MAX' ? 10 : 180,
+ height: 100
+ })
+ const placed = changes.find((node) => node.type === 'INSTANCE')
+ if (!placed) throw new Error('Missing source instance')
+ placed.derivedSymbolData = [
+ {
+ guidPath: { guids: [guid(3)] },
+ size: { x: 37, y: 42 },
+ transform: { m00: 1, m01: 0, m02: 19, m10: 0, m11: 1, m12: 23 }
+ }
+ ]
+ const saved = materializeDocument(changes, [], { derivedBounds: true })
+ const savedId = saved.sources.get('1:4')
+ if (!savedId) throw new Error('Missing saved instance')
+ expect(saved.graph.getChildren(savedId)[0]).toMatchObject({
+ x: 19,
+ y: 23,
+ width: 37,
+ height: 42
+ })
+ })
+ }
+}
diff --git a/packages/fig/tests/document/dependency-closure.test.ts b/packages/fig/tests/document/dependency-closure.test.ts
new file mode 100644
index 000000000..366550c0c
--- /dev/null
+++ b/packages/fig/tests/document/dependency-closure.test.ts
@@ -0,0 +1,86 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { collectSceneDependencies } from '#fig/document/dependency-closure'
+import { createSourceIndex } from '#fig/instance-overrides/source-index'
+
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('retains external preferred choices separately from required component dependencies', () => {
+ const changes = [
+ { guid: guid(1), type: 'CANVAS' },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ componentPropDefs: [
+ {
+ id: guid(90),
+ type: 'INSTANCE_SWAP',
+ initialValue: { guidValue: guid(3) },
+ preferredValues: { instanceSwapValues: [{ key: 'external' }, { key: 'local' }] }
+ }
+ ]
+ },
+ { guid: guid(3), type: 'SYMBOL', key: 'local', parentIndex: { guid: guid(4), position: '!' } },
+ { guid: guid(4), type: 'CANVAS', internalOnly: true }
+ ] as NodeChange[]
+ const result = collectSceneDependencies(changes, undefined, createSourceIndex(changes))
+ expect(result.contentIds.has('1:3')).toBe(true)
+ expect([...result.externalPreferredKeys]).toEqual(['external'])
+ expect(result.missingIds.size).toBe(0)
+})
+
+test('includes component ownership without pulling in unrelated internal definitions', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'DOCUMENT' },
+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'CANVAS',
+ internalOnly: true,
+ parentIndex: { guid: guid(1), position: '"' }
+ },
+ { guid: guid(4), type: 'FRAME', parentIndex: { guid: guid(3), position: '!' } },
+ { guid: guid(5), type: 'SYMBOL', parentIndex: { guid: guid(4), position: '!' } },
+ {
+ guid: guid(6),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(4), position: '"' },
+ symbolData: { symbolID: guid(99) }
+ },
+ {
+ guid: guid(7),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(2), position: '!' },
+ symbolData: { symbolID: guid(5) }
+ }
+ ]
+ const result = collectSceneDependencies(changes, undefined, createSourceIndex(changes))
+ expect([...result.contentIds].sort()).toEqual(['1:2', '1:5', '1:7'])
+ expect(result.ancestorIds.has('1:4')).toBe(true)
+ expect(result.missingIds.size).toBe(0)
+ expect(result.contentIds.has('1:6')).toBe(false)
+ const assembled = materializeDocument(changes)
+ const componentId = assembled.sources.get('1:5')
+ if (!componentId) throw new Error('Missing required component')
+ expect(assembled.graph.getNode(componentId)?.parentId).toBe(assembled.sources.get('1:4'))
+ expect(assembled.sources.has('1:6')).toBe(false)
+ const closureChanges = [
+ ...changes,
+ {
+ guid: guid(8),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(2), position: '"' },
+ symbolData: { symbolID: guid(99) }
+ }
+ ] as NodeChange[]
+ const reached = collectSceneDependencies(
+ closureChanges,
+ undefined,
+ createSourceIndex(closureChanges)
+ )
+ expect([...reached.missingComponentIds]).toEqual(['1:99'])
+ expect(reached.missingIds.size).toBe(0)
+})
diff --git a/packages/fig/tests/document/fragment.test.ts b/packages/fig/tests/document/fragment.test.ts
new file mode 100644
index 000000000..60a58c590
--- /dev/null
+++ b/packages/fig/tests/document/fragment.test.ts
@@ -0,0 +1,116 @@
+import { expect, test } from 'bun:test'
+
+import { normalizeFigFragment } from '#fig/document/fragment'
+
+import { materializeDocument, materializeFigFragment } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const guid = (localID: number) => ({ sessionID: 0, localID })
+test('fragment containers avoid existing IDs and retain source input', () => {
+ const input: NodeChange[] = [
+ { guid: guid(0), type: 'FRAME', name: 'Pasted', parentIndex: { guid: guid(99), position: '!' } }
+ ]
+ const before = structuredClone(input)
+ const normalized = normalizeFigFragment(input)
+ const graph = materializeDocument(normalized).graph
+ expect(graph.getChildren(graph.getPages()[0].id).map((node) => node.name)).toEqual(['Pasted'])
+ expect(new Set(normalized.map((node) => JSON.stringify(node.guid))).size).toBe(3)
+ expect(input).toEqual(before)
+})
+
+test('empty missing instances detach only under explicit fragment policy', () => {
+ const input: NodeChange[] = [
+ {
+ guid: guid(2),
+ type: 'INSTANCE',
+ name: 'Missing',
+ symbolData: { symbolID: guid(99) },
+ size: { x: 120, y: 40 }
+ }
+ ]
+ expect(() => normalizeFigFragment(input)).toThrow('Missing fragment component')
+ const nodes = normalizeFigFragment(input, { missingComponent: 'detach-empty' })
+ const detached = nodes.find((node) => node.name === 'Missing')
+ expect(detached?.type).toBe('FRAME')
+ expect(detached?.size).toEqual({ x: 120, y: 40 })
+ expect(detached?.symbolData).toBeUndefined()
+ expect(() =>
+ normalizeFigFragment(
+ [...input, { guid: guid(3), type: 'TEXT', parentIndex: { guid: guid(2), position: '!' } }],
+ { missingComponent: 'detach-empty' }
+ )
+ ).toThrow('Missing fragment component')
+})
+
+test('fragment interpretation retains hidden component dependencies without selecting them', () => {
+ const source: NodeChange[] = [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'CANVAS',
+ internalOnly: true,
+ parentIndex: { guid: guid(0), position: '"' }
+ },
+ {
+ guid: guid(3),
+ type: 'SYMBOL',
+ name: 'Definition',
+ parentIndex: { guid: guid(2), position: '!' }
+ },
+ {
+ guid: guid(4),
+ type: 'RECTANGLE',
+ name: 'Child',
+ parentIndex: { guid: guid(3), position: '!' },
+ size: { x: 20, y: 10 }
+ },
+ {
+ guid: guid(5),
+ type: 'INSTANCE',
+ name: 'Pasted',
+ parentIndex: { guid: guid(1), position: '!' },
+ symbolData: { symbolID: guid(3) }
+ }
+ ]
+ const { graph, rootIds, dependencyPageIds } = materializeFigFragment(source)
+ expect(rootIds).toHaveLength(1)
+ expect(dependencyPageIds).toHaveLength(1)
+ const root = graph.getNode(rootIds[0])
+ expect(root?.type).toBe('INSTANCE')
+ expect(graph.getNode(root?.componentId ?? '')?.type).toBe('COMPONENT')
+ expect(graph.getChildren(rootIds[0]).map((node) => node.name)).toEqual(['Child'])
+ expect(graph.getChildren(dependencyPageIds[0]).map((node) => node.name)).toEqual(['Definition'])
+})
+
+test('fragment interpretation does not silently accept missing override dependencies', () => {
+ const source: NodeChange[] = [
+ {
+ guid: guid(2),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(99),
+ symbolOverrides: [{ guidPath: { guids: [guid(100)] }, visible: false }]
+ }
+ } as NodeChange
+ ]
+ expect(() => materializeFigFragment(source, [], { missingComponent: 'detach-empty' })).toThrow(
+ 'Missing fragment component'
+ )
+})
+
+test('synthetic containers never satisfy a missing component reference', () => {
+ const source: NodeChange[] = [
+ { guid: guid(2), type: 'INSTANCE', symbolData: { symbolID: guid(0) } }
+ ]
+ expect(() => materializeFigFragment(source)).toThrow('Missing fragment component 0:0')
+})
+
+test('fragment normalization rejects ambiguous source identity', () => {
+ expect(() =>
+ normalizeFigFragment([
+ { guid: guid(1), type: 'FRAME' },
+ { guid: guid(1), type: 'FRAME' }
+ ])
+ ).toThrow('Duplicate')
+})
diff --git a/packages/fig/tests/document/load-transaction.test.ts b/packages/fig/tests/document/load-transaction.test.ts
new file mode 100644
index 000000000..2ee09d8c4
--- /dev/null
+++ b/packages/fig/tests/document/load-transaction.test.ts
@@ -0,0 +1,56 @@
+import { expect, test } from 'bun:test'
+
+import { loadPageTransaction } from '#fig/document/load-transaction'
+import type { AssemblyState } from '#fig/document/materialize'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('failed page mutation restores changed existing instance indexes and object identity', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const a = graph.createNode('COMPONENT', page.id)
+ const b = graph.createNode('COMPONENT', page.id)
+ const instance = graph.createInstance(a.id, page.id)
+ if (!instance) throw new Error('Missing instance')
+ const state: AssemblyState = {
+ graph,
+ sources: new Map([['instance', instance.id]]),
+ components: new Map(),
+ componentIds: new Map(),
+ savedSizeNodes: new Set()
+ }
+ let events = 0
+ graph.onNodeEvents({
+ updated: () => {
+ events++
+ }
+ })
+ expect(() =>
+ loadPageTransaction(
+ state,
+ {
+ contentIds: new Set(['instance']),
+ ancestorIds: new Set(),
+ missingIds: new Set(),
+ externalPreferredKeys: new Set()
+ },
+ () => {
+ state.sources.set('partial', instance.id)
+ state.componentIds.set('partial', b.id)
+ state.savedSizeNodes.add(instance.id)
+ graph.createNode('INSTANCE', page.id, { componentId: b.id })
+ graph.updateNode(instance.id, { componentId: b.id, name: 'Partial' })
+ throw new Error('Fail after update')
+ }
+ )
+ ).toThrow('Fail after update')
+ expect(graph.getNode(instance.id)).toBe(instance)
+ expect(instance.componentId).toBe(a.id)
+ expect(graph.instanceIndex.get(a.id)?.has(instance.id)).toBe(true)
+ expect(graph.instanceIndex.get(b.id)?.has(instance.id) ?? false).toBe(false)
+ expect(state.sources.has('partial')).toBe(false)
+ expect(state.componentIds.has('partial')).toBe(false)
+ expect(state.savedSizeNodes.has(instance.id)).toBe(false)
+ expect(graph.getChildren(page.id)).toHaveLength(3)
+ expect(events).toBe(0)
+})
diff --git a/packages/fig/tests/document/nested-components.test.ts b/packages/fig/tests/document/nested-components.test.ts
new file mode 100644
index 000000000..be1806d6f
--- /dev/null
+++ b/packages/fig/tests/document/nested-components.test.ts
@@ -0,0 +1,35 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { materializeDocument } from '#fig/document/materialize'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('constructs nested definitions once under their actual component parent', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'DOCUMENT' },
+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },
+ { guid: guid(3), type: 'SYMBOL', parentIndex: { guid: guid(2), position: 'a' } },
+ { guid: guid(4), type: 'SYMBOL', parentIndex: { guid: guid(3), position: 'a' } },
+ {
+ guid: guid(5),
+ type: 'TEXT',
+ parentIndex: { guid: guid(4), position: 'a' },
+ textData: { characters: 'Nested' }
+ },
+ {
+ guid: guid(6),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(2), position: 'b' },
+ symbolData: { symbolID: guid(4) }
+ }
+ ]
+ const { graph, sources } = materializeDocument(changes)
+ const outer = sources.get('1:3')
+ const inner = sources.get('1:4')
+ const instance = sources.get('1:6')
+ if (!outer || !inner || !instance) throw new Error('Missing nodes')
+ expect(graph.getNode(inner)?.parentId).toBe(outer)
+ expect(graph.getNode(instance)?.componentId).toBe(inner)
+ expect([...graph.getAllNodes()].filter((node) => node.type === 'COMPONENT')).toHaveLength(2)
+})
diff --git a/packages/fig/tests/document/nested-constraint-resize.test.ts b/packages/fig/tests/document/nested-constraint-resize.test.ts
new file mode 100644
index 000000000..76175e0f1
--- /dev/null
+++ b/packages/fig/tests/document/nested-constraint-resize.test.ts
@@ -0,0 +1,57 @@
+import { expect, test } from 'bun:test'
+
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+for (const autoLayout of [false, true]) {
+ for (const pinned of [false, true]) {
+ test(`nested resized occurrences preserve ${pinned ? 'pinned offsets' : 'text insets'} (auto-layout=${autoLayout})`, () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const changes: NodeChange[] = [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ stackMode: autoLayout ? 'HORIZONTAL' : 'NONE',
+ size: { x: pinned ? 442 : 280, y: 40 },
+ parentIndex: { guid: guid(1), position: '!' }
+ },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ textData: { characters: 'Placeholder' },
+ parentIndex: { guid: guid(2), position: '!' },
+ size: { x: pinned ? 14 : 248, y: 20 },
+ transform: { m00: 1, m01: 0, m02: pinned ? 420 : 16, m10: 0, m11: 1, m12: 10 },
+ horizontalConstraint: pinned ? 'MAX' : 'MIN',
+ stackPositioning: 'ABSOLUTE'
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ size: { x: 240, y: 40 },
+ symbolData: { symbolID: guid(2) }
+ },
+ {
+ guid: guid(5),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '#' },
+ size: { x: 180, y: 40 },
+ symbolData: { symbolID: guid(4) }
+ }
+ ]
+ const { graph, sources } = materializeDocument(changes)
+ const root = sources.get('1:5')
+ if (!root) throw new Error('Missing occurrence')
+ const child = graph.getChildren(root)[0]
+ expect({ x: child.x, y: child.y, text: child.text }).toEqual({
+ x: pinned ? 158 : 16,
+ y: 10,
+ text: 'Placeholder'
+ })
+ expect(child.width).toBe(pinned ? 14 : 248)
+ })
+ }
+}
diff --git a/packages/fig/tests/document/occurrence-conversion.test.ts b/packages/fig/tests/document/occurrence-conversion.test.ts
new file mode 100644
index 000000000..1a962c9b7
--- /dev/null
+++ b/packages/fig/tests/document/occurrence-conversion.test.ts
@@ -0,0 +1,46 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+
+import { nodeChangeToProps } from '@open-pencil/fig/node-change'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('instances do not duplicate component-owned property definitions', () => {
+ const source = {
+ type: 'INSTANCE',
+ componentPropDefs: [
+ { id: guid(90), name: 'Label', type: 'TEXT', initialValue: { textValue: 'Default' } }
+ ],
+ componentPropAssignments: [{ defID: guid(90), value: { textValue: 'Assigned' } }]
+ } as NodeChange
+ const props = nodeChangeToProps(source, [], 'occurrence')
+ expect(props.componentPropertyDefinitions).toEqual([])
+ expect(props.componentPropertyAssignments).toEqual({ '1:90': 'Assigned' })
+ expect(
+ nodeChangeToProps({ ...source, type: 'SYMBOL' }, []).componentPropertyDefinitions
+ ).toHaveLength(1)
+})
+
+test('occurrence conversion preserves editable properties without constructing discarded raw metadata', () => {
+ const source: NodeChange = {
+ guid: guid(1),
+ type: 'FRAME',
+ name: 'Content',
+ size: { x: 120, y: 40 },
+ stackMode: 'HORIZONTAL',
+ stackCounterSizing: 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE',
+ fillPaints: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ }
+ const full = nodeChangeToProps(source, [])
+ const occurrence = nodeChangeToProps(source, [], 'occurrence')
+ const { source: fullMetadata, ...fullProps } = full
+ const { source: occurrenceMetadata, ...occurrenceProps } = occurrence
+ expect(occurrenceProps).toEqual(fullProps)
+ expect(occurrenceMetadata?.fig.layout).toEqual(fullMetadata?.fig.layout)
+ expect(occurrenceMetadata?.id).toBeNull()
+ expect(occurrenceMetadata?.fig.rawNodeFields).toEqual({})
+ if (!occurrence.fills?.[0]?.color) throw new Error('Missing fill')
+ occurrence.fills[0].color.r = 0
+ expect(full.fills?.[0]?.color?.r).toBe(1)
+ expect(source.fillPaints?.[0]?.color?.r).toBe(1)
+})
diff --git a/packages/fig/tests/document/page-selection.test.ts b/packages/fig/tests/document/page-selection.test.ts
new file mode 100644
index 000000000..e83139aa2
--- /dev/null
+++ b/packages/fig/tests/document/page-selection.test.ts
@@ -0,0 +1,43 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('selected-page assembly excludes unrelated content but keeps cross-page components', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'CANVAS', name: 'Design' },
+ { guid: guid(2), type: 'CANVAS', name: 'Library' },
+ { guid: guid(3), type: 'SYMBOL', parentIndex: { guid: guid(2), position: '!' } },
+ {
+ guid: guid(4),
+ type: 'TEXT',
+ parentIndex: { guid: guid(3), position: '!' },
+ textData: { characters: 'Shared' }
+ },
+ {
+ guid: guid(5),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '!' },
+ symbolData: { symbolID: guid(3) }
+ },
+ {
+ guid: guid(6),
+ type: 'TEXT',
+ parentIndex: { guid: guid(2), position: '"' },
+ textData: { characters: 'Unrelated' }
+ }
+ ]
+ const selected = materializeDocument(changes, [], { pageIds: new Set(['1:1']) })
+ const full = materializeDocument(changes)
+ expect(selected.graph.getPages()).toHaveLength(2)
+ expect(selected.sources.has('1:6')).toBe(false)
+ expect(full.sources.has('1:6')).toBe(true)
+ const id = selected.sources.get('1:5')
+ if (!id) throw new Error('Missing selected instance')
+ expect(selected.graph.getChildren(id)[0].text).toBe('Shared')
+ expect(() => materializeDocument(changes, [], { pageIds: new Set(['missing']) })).toThrow(
+ 'Unknown page'
+ )
+})
diff --git a/packages/fig/tests/document/property-inheritance.test.ts b/packages/fig/tests/document/property-inheritance.test.ts
new file mode 100644
index 000000000..e3c93aac0
--- /dev/null
+++ b/packages/fig/tests/document/property-inheritance.test.ts
@@ -0,0 +1,57 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { createDocumentReader } from '#fig/document/read'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('inherits parent definition semantics without replacing local property identity', () => {
+ const changes = [
+ {
+ guid: guid(1),
+ type: 'FRAME',
+ isStateGroup: true,
+ componentPropDefs: [
+ { id: guid(10), name: 'Icon', type: 'INSTANCE_SWAP', initialValue: { guidValue: guid(4) } }
+ ]
+ },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ componentPropDefs: [{ id: guid(11), parentPropDefId: guid(10) }]
+ },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(2), position: '!' },
+ symbolData: { symbolID: guid(4) },
+ componentPropRefs: [{ defID: guid(11), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }]
+ },
+ { guid: guid(4), type: 'SYMBOL', name: 'Default' },
+ { guid: guid(5), type: 'SYMBOL', name: 'Replacement' },
+ { guid: guid(6), type: 'CANVAS' },
+ {
+ guid: guid(7),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(6), position: '!' },
+ symbolData: { symbolID: guid(2) },
+ componentPropAssignments: [{ defID: guid(11), value: { guidValue: guid(5) } }]
+ }
+ ] as NodeChange[]
+ const before = structuredClone(changes)
+ const reader = createDocumentReader(changes)
+ const component = reader.readComponent('1:2')
+ expect(component.properties.componentPropDefs).toEqual([
+ {
+ id: guid(11),
+ parentPropDefId: guid(10),
+ name: 'Icon',
+ type: 'INSTANCE_SWAP',
+ initialValue: { guidValue: guid(4) }
+ }
+ ])
+ expect(component.children[0].mainComponentId).toBe('1:4')
+ expect(reader.readPage('1:6').children[0].children[0].mainComponentId).toBe('1:5')
+ expect(changes).toEqual(before)
+})
diff --git a/packages/fig/tests/document/read.test.ts b/packages/fig/tests/document/read.test.ts
new file mode 100644
index 000000000..1a5e76956
--- /dev/null
+++ b/packages/fig/tests/document/read.test.ts
@@ -0,0 +1,84 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { planComponentConstruction } from '#fig/document/components'
+import { materializeDocument } from '#fig/document/materialize'
+import { createDocumentReader } from '#fig/document/read'
+import { indexRecords } from '#fig/instance-overrides/source-index'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('reads pages independently through one index with cross-page component expansion', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'DOCUMENT' },
+ {
+ guid: guid(2),
+ type: 'CANVAS',
+ name: 'Components',
+ parentIndex: { guid: guid(1), position: 'b' }
+ },
+ {
+ guid: guid(3),
+ type: 'CANVAS',
+ name: 'Design',
+ parentIndex: { guid: guid(1), position: 'a' }
+ },
+ { guid: guid(4), type: 'SYMBOL', parentIndex: { guid: guid(2), position: 'a' } },
+ {
+ guid: guid(5),
+ type: 'TEXT',
+ parentIndex: { guid: guid(4), position: 'a' },
+ textData: { characters: 'Label' }
+ },
+ {
+ guid: guid(6),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(3), position: 'a' },
+ symbolData: { symbolID: guid(4) }
+ }
+ ]
+ const reader = createDocumentReader(changes)
+ expect(reader.pages.map((page) => page.name)).toEqual(['Design', 'Components'])
+ const page = reader.readPage('1:3')
+ expect(page.children[0].mainComponentId).toBe('1:4')
+ expect(page.children[0].children[0].properties.textData?.characters).toBe('Label')
+ page.children[0].children[0].properties.opacity = 0.2
+ expect(reader.readPage('1:3').children[0].children[0].properties.opacity).toBeUndefined()
+ expect(reader.readPage('1:2').children[0].sourceId).toBe('1:4')
+ const roots = [page, reader.readPage('1:2')]
+ const reused = planComponentConstruction(
+ changes,
+ roots,
+ () => {
+ throw new Error('Unexpected component re-expansion')
+ },
+ indexRecords(changes)
+ )
+ expect(reused[0].occurrence).toBe(roots[1].children[0])
+ const plan = reader.planComponents([page, reader.readPage('1:2')])
+ expect(
+ plan.map(({ sourceId, parentSourceId, pageSourceId }) => ({
+ sourceId,
+ parentSourceId,
+ pageSourceId
+ }))
+ ).toEqual([{ sourceId: '1:4', parentSourceId: '1:2', pageSourceId: '1:2' }])
+ expect(reader.planComponents([page]).map((component) => component.sourceId)).toEqual(['1:4'])
+ const { graph, sources } = materializeDocument(changes)
+ expect(graph.getPages().map((node) => node.name)).toEqual(['Design', 'Components'])
+ const componentId = sources.get('1:4')
+ const instanceId = sources.get('1:6')
+ if (!componentId || !instanceId) throw new Error('Missing assembled nodes')
+ expect(graph.getNode(instanceId)?.componentId).toBe(componentId)
+ expect(graph.getNode(componentId)?.parentId).toBe(sources.get('1:2'))
+ expect([...graph.getAllNodes()].filter((node) => node.type === 'COMPONENT')).toHaveLength(1)
+ expect(graph.getChildren(instanceId)[0].text).toBe('Label')
+ const exportedSources = reader.sourceRecords
+ const exportedText = exportedSources.find((node) => node.guid?.localID === 5)
+ if (!exportedText?.textData) throw new Error('Missing copied text')
+ exportedText.textData.characters = 'Mutated snapshot'
+ expect(reader.readPage('1:3').children[0].children[0].properties.textData?.characters).toBe(
+ 'Label'
+ )
+ expect(() => reader.readPage('1:4')).toThrow('Unknown page')
+})
diff --git a/packages/fig/tests/document/resource-reference.test.ts b/packages/fig/tests/document/resource-reference.test.ts
new file mode 100644
index 000000000..a4f1a5694
--- /dev/null
+++ b/packages/fig/tests/document/resource-reference.test.ts
@@ -0,0 +1,29 @@
+import { expect, test } from 'bun:test'
+
+import { createResourceResolver } from '#fig/document/resource-reference'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('an explicit unversioned record wins regardless of source ordering', () => {
+ const entries: NodeChange[] = [
+ { guid: { sessionID: 1, localID: 1 }, key: 'style' },
+ { guid: { sessionID: 1, localID: 2 }, key: 'style', version: 'v2' }
+ ]
+ for (const records of [entries, entries.toReversed()]) {
+ const resolve = createResourceResolver(records)
+ expect(resolve({ assetRef: { key: 'style' } })).toBe('1:1')
+ expect(resolve({ assetRef: { key: 'style', version: 'v2' } })).toBe('1:2')
+ expect(resolve({ assetRef: { key: 'style', version: 'missing' } })).toBeUndefined()
+ }
+})
+
+test('resolves exact resource versions and refuses ambiguous unversioned references', () => {
+ const resolve = createResourceResolver([
+ { guid: { sessionID: 1, localID: 1 }, key: 'collection', version: 'v1' },
+ { guid: { sessionID: 1, localID: 2 }, key: 'collection', version: 'v2' }
+ ] as NodeChange[])
+ expect(resolve({ assetRef: { key: 'collection', version: 'v2' } })).toBe('1:2')
+ expect(resolve({ assetRef: { key: 'collection', version: 'missing' } })).toBeUndefined()
+ expect(resolve({ assetRef: { key: 'collection' } })).toBeUndefined()
+ expect(resolve({ guid: { sessionID: 2, localID: 3 } })).toBe('2:3')
+})
diff --git a/packages/fig/tests/document/resources.test.ts b/packages/fig/tests/document/resources.test.ts
new file mode 100644
index 000000000..f66a610cd
--- /dev/null
+++ b/packages/fig/tests/document/resources.test.ts
@@ -0,0 +1,70 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { materializeDocument } from '#fig/document/materialize'
+import { createDocumentReader } from '#fig/document/read'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('copies archive images into document-owned resources', () => {
+ const bytes = new Uint8Array([1, 2, 3])
+ const { graph } = materializeDocument([], [], { images: new Map([['image-hash', bytes]]) })
+ expect(graph.images.get('image-hash')).toEqual(bytes)
+ bytes[0] = 9
+ expect(graph.images.get('image-hash')?.[0]).toBe(1)
+})
+
+test('loads mode values without treating false, zero or empty text as missing', () => {
+ const mode = guid(10)
+ const collection = guid(3)
+ const resources: NodeChange[] = [
+ { guid: collection, type: 'VARIABLE_SET', variableSetModes: [{ id: mode, name: 'Default' }] },
+ ...(['BOOLEAN', 'FLOAT', 'STRING'] as const).map((type, index) => ({
+ guid: guid(4 + index),
+ type: 'VARIABLE' as const,
+ variableResolvedType: type,
+ variableSetID: { guid: collection },
+ variableDataValues: {
+ entries: [
+ {
+ modeID: mode,
+ variableData: {
+ dataType: type,
+ value: {
+ BOOLEAN: { boolValue: false },
+ FLOAT: { floatValue: 0 },
+ STRING: { textValue: '' }
+ }[type]
+ }
+ }
+ ]
+ }
+ }))
+ ]
+ const { graph } = materializeDocument(resources)
+ expect([...graph.variables.values()].map((variable) => variable.valuesByMode['1:10'])).toEqual([
+ false,
+ 0,
+ ''
+ ])
+ expect(graph.variableCollections.get('1:3')?.variableIds).toEqual(['1:4', '1:5', '1:6'])
+})
+
+test('keeps variable resources outside scene pages and rejects silent omission', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'DOCUMENT' },
+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },
+ { guid: guid(3), type: 'VARIABLE_SET', parentIndex: { guid: guid(2), position: '!' } },
+ { guid: guid(4), type: 'VARIABLE', parentIndex: { guid: guid(3), position: '!' } }
+ ]
+ const reader = createDocumentReader(changes)
+ expect(reader.resources.map((node) => node.type)).toEqual(['VARIABLE_SET', 'VARIABLE'])
+ expect(reader.readPage('1:2').children).toEqual([])
+ expect(() => materializeDocument(changes)).toThrow('Unsupported document resource')
+ const reported: NodeChange[] = []
+ const { graph } = materializeDocument(changes, [], {
+ onUnsupportedResource: (node) => reported.push(node)
+ })
+ expect(reported).toHaveLength(2)
+ expect(graph.getChildren(graph.getPages()[0].id)).toEqual([])
+})
diff --git a/packages/fig/tests/document/retained-records.test.ts b/packages/fig/tests/document/retained-records.test.ts
new file mode 100644
index 000000000..703b3088f
--- /dev/null
+++ b/packages/fig/tests/document/retained-records.test.ts
@@ -0,0 +1,48 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { createDocumentReader } from '#fig/document/read'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+function records(): NodeChange[] {
+ return [
+ { guid: guid(1), type: 'CANVAS' },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ name: 'Retained',
+ parentIndex: { guid: guid(1), position: '!' },
+ ancestorPathBeforeDeletion: [guid(99)]
+ },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ parentIndex: { guid: guid(2), position: '!' },
+ textData: { characters: 'Retained content' }
+ }
+ ] as NodeChange[]
+}
+
+test('deletion history alone does not remove a node from the current hierarchy', () => {
+ const input = records()
+ const reader = createDocumentReader(input)
+ expect(reader.readPage('1:1').children.map((node) => node.sourceId)).toEqual(['1:2'])
+ expect(reader.readComponent('1:2').children[0].properties.textData?.characters).toBe(
+ 'Retained content'
+ )
+ expect(input[1].parentIndex?.guid).toEqual(guid(1))
+})
+
+test('references and current hierarchy both retain definitions with deletion history', () => {
+ const input = records()
+ input.push({
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: { symbolID: guid(2) }
+ })
+ const page = createDocumentReader(input).readPage('1:1')
+ expect(page.children.map((node) => node.sourceId)).toEqual(['1:2', '1:4'])
+ expect(page.children[1].children[0].properties.textData?.characters).toBe('Retained content')
+})
diff --git a/packages/fig/tests/document/scale-constraints.test.ts b/packages/fig/tests/document/scale-constraints.test.ts
new file mode 100644
index 000000000..38990d102
--- /dev/null
+++ b/packages/fig/tests/document/scale-constraints.test.ts
@@ -0,0 +1,45 @@
+import { expect, test } from 'bun:test'
+
+import { materializeDocument } from '@open-pencil/fig'
+
+for (const image of [false, true]) {
+ test(`SCALE constrained occurrence resizes ${image ? 'rectangle' : 'vector'} without changing MIN sibling`, () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const { graph, sources } = materializeDocument([
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 100, y: 100 }
+ },
+ {
+ guid: guid(3),
+ type: image ? 'ROUNDED_RECTANGLE' : 'VECTOR',
+ parentIndex: { guid: guid(2), position: '!' },
+ size: { x: 20, y: 10 },
+ horizontalConstraint: 'SCALE',
+ verticalConstraint: 'SCALE'
+ },
+ {
+ guid: guid(4),
+ type: 'RECTANGLE',
+ parentIndex: { guid: guid(2), position: '"' },
+ size: { x: 10, y: 10 }
+ },
+ {
+ guid: guid(5),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: { symbolID: guid(2) },
+ size: { x: 50, y: 50 }
+ }
+ ])
+ const root = sources.get('1:5')
+ if (!root) throw new Error('Missing instance')
+ const [scaled, sibling] = graph.getChildren(root)
+ expect([scaled.width, scaled.height]).toEqual([10, 5])
+ expect([sibling.width, sibling.height]).toEqual([10, 10])
+ })
+}
diff --git a/packages/fig/tests/document/target-aspect-resize.test.ts b/packages/fig/tests/document/target-aspect-resize.test.ts
new file mode 100644
index 000000000..79d5ef8dc
--- /dev/null
+++ b/packages/fig/tests/document/target-aspect-resize.test.ts
@@ -0,0 +1,80 @@
+import { expect, test } from 'bun:test'
+
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+for (const wrapper of [false, true]) {
+ test(`target-aspect metadata does not override child constraints (wrapper=${wrapper})`, () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const width = wrapper ? 310 : 24,
+ height = wrapper ? 62 : 24
+ const changes: NodeChange[] = [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: width, y: height }
+ },
+ {
+ guid: guid(4),
+ type: 'VECTOR',
+ parentIndex: { guid: guid(wrapper ? 3 : 2), position: '"' },
+ size: { x: wrapper ? 56.392 : 6, y: wrapper ? 61.214 : 6 },
+ transform: { m00: 1, m01: 0, m02: wrapper ? 0 : 9, m10: 0, m11: 1, m12: wrapper ? 0 : 3 },
+ horizontalConstraint: 'SCALE',
+ verticalConstraint: 'SCALE'
+ },
+ {
+ guid: guid(5),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: { symbolID: guid(2) },
+ size: { x: wrapper ? 100 : 14, y: wrapper ? 20 : 14 },
+ targetAspectRatio: { value: { x: wrapper ? 310 : 32, y: wrapper ? 62 : 32 } }
+ }
+ ]
+ if (wrapper)
+ changes.push(
+ {
+ guid: guid(3),
+ type: 'FRAME',
+ parentIndex: { guid: guid(2), position: '!' },
+ size: { x: 310, y: 61.214 }
+ },
+ {
+ guid: guid(6),
+ type: 'RECTANGLE',
+ parentIndex: { guid: guid(3), position: '!' },
+ size: { x: 20, y: 20 },
+ transform: { m00: 1, m01: 0, m02: 250, m10: 0, m11: 1, m12: 10 },
+ horizontalConstraint: 'MAX'
+ }
+ )
+ const { graph, sources } = materializeDocument(changes)
+ const id = sources.get('1:5')
+ if (!id) throw new Error('Missing instance')
+ const child = graph.getChildren(id)[0]
+ if (wrapper) {
+ expect(child.width).toBeCloseTo(310)
+ expect(child.height).toBeCloseTo(61.214)
+ const [inset, vector] = graph.getChildren(child.id)
+ expect({ x: inset.x, y: inset.y, width: inset.width, height: inset.height }).toEqual({
+ x: 250,
+ y: 10,
+ width: 20,
+ height: 20
+ })
+ expect(vector.width).toBeCloseTo(56.392)
+ expect(vector.height).toBeCloseTo(61.214)
+ } else {
+ expect({ x: child.x, y: child.y, width: child.width, height: child.height }).toEqual({
+ x: (9 * 14) / 24,
+ y: (3 * 14) / 24,
+ width: (6 * 14) / 24,
+ height: (6 * 14) / 24
+ })
+ }
+ })
+}
diff --git a/packages/fig/tests/document/text-bindings.test.ts b/packages/fig/tests/document/text-bindings.test.ts
new file mode 100644
index 000000000..0c7fd2bfb
--- /dev/null
+++ b/packages/fig/tests/document/text-bindings.test.ts
@@ -0,0 +1,136 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { materializeDocument } from '#fig/document/materialize'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const mode = guid(10)
+const collection = guid(11)
+const variable = guid(12)
+const page = guid(1)
+const component = guid(2)
+const label = guid(3)
+const placed = guid(4)
+
+/** A string variable named by an alias, the way Figma records a bound text layer. */
+function textBinding(): NodeChange['variableConsumptionMap'] {
+ return {
+ entries: [
+ {
+ variableField: 'TEXT_DATA',
+ variableData: {
+ dataType: 'ALIAS',
+ resolvedDataType: 'STRING',
+ value: { alias: { guid: variable } }
+ }
+ }
+ ]
+ }
+}
+
+function resources(value: string): NodeChange[] {
+ return [
+ { guid: collection, type: 'VARIABLE_SET', variableSetModes: [{ id: mode, name: 'Default' }] },
+ {
+ guid: variable,
+ type: 'VARIABLE',
+ variableResolvedType: 'STRING',
+ variableSetID: { guid: collection },
+ variableDataValues: {
+ entries: [
+ { modeID: mode, variableData: { dataType: 'STRING', value: { textValue: value } } }
+ ]
+ }
+ }
+ ] as NodeChange[]
+}
+
+function textOf(graph: ReturnType<typeof materializeDocument>['graph'], name: string): string {
+ const node = graph.getAllNodes().find((candidate) => candidate.name === name)
+ if (!node) throw new Error(`Missing ${name}`)
+ return node.text
+}
+
+test('reads a layer whose text is bound to a string variable', () => {
+ const changes = [
+ ...resources('Bound'),
+ { guid: page, type: 'CANVAS' },
+ {
+ guid: label,
+ type: 'TEXT',
+ name: 'Label',
+ parentIndex: { guid: page, position: '!' },
+ textData: { characters: 'Stale' },
+ variableConsumptionMap: textBinding()
+ }
+ ] as NodeChange[]
+ const { graph } = materializeDocument(changes)
+ expect(textOf(graph, 'Label')).toBe('Bound')
+})
+
+/**
+ * Figma retires a literal override of a bound layer rather than applying it, so the
+ * binding decides what the instance reads.
+ */
+test('a bound layer keeps its variable value over an owner’s literal override', () => {
+ const changes = [
+ ...resources('Bound'),
+ { guid: page, type: 'CANVAS' },
+ { guid: component, type: 'SYMBOL', parentIndex: { guid: page, position: '!' } },
+ {
+ guid: label,
+ type: 'TEXT',
+ name: 'Label',
+ parentIndex: { guid: component, position: '!' },
+ textData: { characters: 'Bound' },
+ variableConsumptionMap: textBinding()
+ },
+ {
+ guid: placed,
+ type: 'INSTANCE',
+ name: 'Placed',
+ parentIndex: { guid: page, position: '"' },
+ symbolData: {
+ symbolID: component,
+ symbolOverrides: [{ guidPath: { guids: [label] }, textData: { characters: 'Override' } }]
+ }
+ }
+ ] as NodeChange[]
+ const { graph } = materializeDocument(changes)
+ const instance = graph.getAllNodes().find((node) => node.name === 'Placed')
+ if (!instance) throw new Error('Missing instance')
+ const child = graph.getChildren(instance.id)[0]
+ expect(child.boundVariables.text).toBe('1:12')
+ expect(child.text).toBe('Bound')
+})
+
+/** An override may carry the binding alone, with no literal text to fall back on. */
+test('an override that only binds a variable supplies the text', () => {
+ const changes = [
+ ...resources('9+'),
+ { guid: page, type: 'CANVAS' },
+ { guid: component, type: 'SYMBOL', parentIndex: { guid: page, position: '!' } },
+ {
+ guid: label,
+ type: 'TEXT',
+ name: 'Label',
+ parentIndex: { guid: component, position: '!' },
+ textData: { characters: 'Default' }
+ },
+ {
+ guid: placed,
+ type: 'INSTANCE',
+ name: 'Placed',
+ parentIndex: { guid: page, position: '"' },
+ symbolData: {
+ symbolID: component,
+ symbolOverrides: [{ guidPath: { guids: [label] }, variableConsumptionMap: textBinding() }]
+ }
+ }
+ ] as NodeChange[]
+ const { graph } = materializeDocument(changes)
+ const instance = graph.getAllNodes().find((node) => node.name === 'Placed')
+ if (!instance) throw new Error('Missing instance')
+ expect(graph.getChildren(instance.id)[0].text).toBe('9+')
+})
diff --git a/packages/fig/tests/document/text-chain.test.ts b/packages/fig/tests/document/text-chain.test.ts
new file mode 100644
index 000000000..807e377ba
--- /dev/null
+++ b/packages/fig/tests/document/text-chain.test.ts
@@ -0,0 +1,45 @@
+import { expect, test } from 'bun:test'
+
+import { materializeDocument } from '@open-pencil/fig'
+
+test('nested source instances inherit text geometry and paints without clone repair', () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const { graph, sources } = materializeDocument([
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 200, y: 40 }
+ },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ parentIndex: { guid: guid(2), position: '!' },
+ size: { x: 80, y: 20 },
+ textData: { characters: 'Label' },
+ fillPaints: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: { symbolID: guid(2) }
+ },
+ {
+ guid: guid(5),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '#' },
+ symbolData: { symbolID: guid(4) }
+ }
+ ])
+ for (const id of ['1:4', '1:5']) {
+ const root = sources.get(id)
+ if (!root) throw new Error('Missing instance')
+ const child = graph.getChildren(root)[0]
+ expect(child.width).toBe(80)
+ expect(child.text).toBe('Label')
+ expect(child.fills[0].color).toEqual({ r: 1, g: 0, b: 0, a: 1 })
+ }
+})
diff --git a/packages/fig/tests/document/variant-values.test.ts b/packages/fig/tests/document/variant-values.test.ts
new file mode 100644
index 000000000..60734e0d0
--- /dev/null
+++ b/packages/fig/tests/document/variant-values.test.ts
@@ -0,0 +1,40 @@
+import { expect, test } from 'bun:test'
+
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const guid = (localID: number) => ({ sessionID: 1, localID })
+
+// A variant's specs name definitions owned by its component set; its own definitions do not
+// include them, so the names can only resolve once the set exists in the graph.
+test('variant property values resolve through the component set definitions', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'FRAME',
+ isStateGroup: true,
+ name: 'Button',
+ parentIndex: { guid: guid(1), position: '!' },
+ componentPropDefs: [
+ { id: guid(10), name: 'State', type: 'VARIANT' },
+ { id: guid(11), name: 'Label', type: 'TEXT', initialValue: { textValue: 'Button' } }
+ ]
+ },
+ {
+ guid: guid(3),
+ type: 'SYMBOL',
+ name: 'State=Disabled',
+ parentIndex: { guid: guid(2), position: '!' },
+ variantPropSpecs: [{ propDefId: guid(10), value: 'Disabled' }],
+ componentPropDefs: [
+ { id: guid(12), name: 'Icon', type: 'BOOL', initialValue: { boolValue: true } }
+ ]
+ } as NodeChange
+ ]
+ const { graph, sources } = materializeDocument(changes)
+ const variant = graph.getNode(sources.get('1:3') ?? '')
+ expect(variant?.componentPropertyValues).toEqual({ State: 'Disabled' })
+ expect(variant?.variantPropSpecs).toEqual([{ propDefId: '1:10', value: 'Disabled' }])
+})
diff --git a/packages/fig/tests/document/visual-scale-contract.test.ts b/packages/fig/tests/document/visual-scale-contract.test.ts
new file mode 100644
index 000000000..732c39514
--- /dev/null
+++ b/packages/fig/tests/document/visual-scale-contract.test.ts
@@ -0,0 +1,88 @@
+import { expect, test } from 'bun:test'
+
+import { materializeDocument } from '@open-pencil/fig'
+
+test('uniform FIG scale covers corners, dashes, and effects', () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const { graph, sources } = materializeDocument([
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 40, y: 20 }
+ },
+ {
+ guid: guid(3),
+ type: 'ROUNDED_RECTANGLE',
+ parentIndex: { guid: guid(2), position: '!' },
+ size: { x: 40, y: 20 },
+ cornerRadius: 10,
+ rectangleTopLeftCornerRadius: 2,
+ rectangleTopRightCornerRadius: 4,
+ rectangleBottomRightCornerRadius: 6,
+ rectangleBottomLeftCornerRadius: 8,
+ dashPattern: [2, 4],
+ effects: [{ type: 'DROP_SHADOW', offset: { x: 3, y: 5 }, radius: 7, spread: 9 }]
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: { symbolID: guid(2), uniformScaleFactor: 2 },
+ size: { x: 80, y: 40 }
+ }
+ ])
+ const id = sources.get('1:4')
+ if (!id) throw new Error('Missing instance')
+ const child = graph.getChildren(id)[0]
+ expect(child).toMatchObject({
+ cornerRadius: 20,
+ topLeftRadius: 4,
+ topRightRadius: 8,
+ bottomRightRadius: 12,
+ bottomLeftRadius: 16,
+ dashPattern: [4, 8]
+ })
+ expect(child.effects[0]).toMatchObject({ offset: { x: 6, y: 10 }, radius: 14, spread: 18 })
+})
+
+test('a scaled instance keeps its own placed-space visual values verbatim', () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const { graph, sources } = materializeDocument([
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 40, y: 20 },
+ cornerRadius: 10,
+ strokePaints: [
+ { type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }
+ ],
+ strokeWeight: 1,
+ dashPattern: [2, 4],
+ effects: [{ type: 'DROP_SHADOW', offset: { x: 3, y: 5 }, radius: 7, spread: 9 }]
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: { symbolID: guid(2), uniformScaleFactor: 2 },
+ size: { x: 80, y: 40 },
+ // The record already describes the placed result; scaling must not touch it.
+ cornerRadius: 12,
+ strokeWeight: 3,
+ dashPattern: [1, 1],
+ effects: [{ type: 'DROP_SHADOW', offset: { x: 1, y: 1 }, radius: 2, spread: 0 }]
+ }
+ ])
+ const id = sources.get('1:4')
+ if (!id) throw new Error('Missing instance')
+ const node = graph.getNode(id)
+ expect(node).toMatchObject({ width: 80, height: 40, cornerRadius: 12, dashPattern: [1, 1] })
+ expect(node?.strokes[0]?.weight).toBe(3)
+ expect(node?.effects[0]).toMatchObject({ offset: { x: 1, y: 1 }, radius: 2 })
+})
diff --git a/packages/fig/tests/helpers/assert.ts b/packages/fig/tests/helpers/assert.ts
new file mode 100644
index 000000000..e90518053
--- /dev/null
+++ b/packages/fig/tests/helpers/assert.ts
@@ -0,0 +1,4 @@
+export function expectDefined<T>(value: T | null | undefined, label = 'value'): NonNullable<T> {
+ if (value == null) throw new Error(`${label} was expected to be defined`)
+ return value
+}
diff --git a/packages/fig/tests/helpers/errors.ts b/packages/fig/tests/helpers/errors.ts
new file mode 100644
index 000000000..bb07aef88
--- /dev/null
+++ b/packages/fig/tests/helpers/errors.ts
@@ -0,0 +1,22 @@
+import { expect } from 'bun:test'
+
+import type { InstancePathDiagnostic } from '#fig/instance-overrides/interpret'
+import { InstancePathError } from '#fig/instance-overrides/occurrence-path'
+
+/**
+ * Assert why a path failed to resolve rather than how the message reads. A count of
+ * candidates is the contract; the sentence around it is not.
+ */
+export function expectPathError(
+ run: () => unknown,
+ reason: InstancePathDiagnostic['reason']
+): InstancePathDiagnostic {
+ try {
+ run()
+ } catch (error) {
+ if (!(error instanceof InstancePathError)) throw error
+ expect(error.diagnostic.reason).toBe(reason)
+ return error.diagnostic
+ }
+ throw new Error(`Expected an InstancePathError with reason ${reason}`)
+}
diff --git a/packages/fig/tests/helpers/fig-fixtures.ts b/packages/fig/tests/helpers/fig-fixtures.ts
new file mode 100644
index 000000000..75cb743bc
--- /dev/null
+++ b/packages/fig/tests/helpers/fig-fixtures.ts
@@ -0,0 +1,25 @@
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+/** Shared archives live outside the package; this is the only path that reaches them. */
+export const FIXTURES = resolve(import.meta.dir, '../../../../tests/fixtures')
+
+/** Read a shared JSON fixture as data; a module import would escape the package root. */
+export function readFixtureJSON<T>(name: string): T {
+ return JSON.parse(readFileSync(resolve(FIXTURES, name), 'utf8')) as T
+}
+
+export function readFixtureBytes(name: string): Uint8Array {
+ return readFileSync(resolve(FIXTURES, name))
+}
+
+export function readFixtureArrayBuffer(name: string): ArrayBuffer {
+ const bytes = readFixtureBytes(name)
+ const buffer = bytes.buffer
+ if (buffer instanceof ArrayBuffer) {
+ return buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
+ }
+ const copy = new Uint8Array(bytes.byteLength)
+ copy.set(bytes)
+ return copy.buffer
+}
diff --git a/packages/fig/tests/helpers/guid.ts b/packages/fig/tests/helpers/guid.ts
new file mode 100644
index 000000000..559f72914
--- /dev/null
+++ b/packages/fig/tests/helpers/guid.ts
@@ -0,0 +1,5 @@
+import type { GUID } from '@open-pencil/kiwi/fig/codec'
+
+export function guid(localID: number, sessionID = 1): GUID {
+ return { sessionID, localID }
+}
diff --git a/packages/fig/tests/index.test.ts b/packages/fig/tests/index.test.ts
index af6387545..b3409995c 100644
--- a/packages/fig/tests/index.test.ts
+++ b/packages/fig/tests/index.test.ts
@@ -1,5 +1,12 @@
import { beforeAll, describe, expect, it } from 'bun:test'
+import {
+ FIG_PACKAGE_STATUS,
+ parseFigBuffer,
+ readFigContainer,
+ writeFigArchive,
+ writeFigContainer
+} from '#fig/index'
import { deflateSync } from 'fflate'
import {
@@ -9,15 +16,6 @@ import {
initCodec
} from '@open-pencil/kiwi/fig/codec'
-import {
- FIG_PACKAGE_STATUS,
- assertFigPackageReady,
- parseFigBuffer,
- readFigContainer,
- writeFigArchive,
- writeFigContainer
-} from '../src/index'
-
const PNG_SIGNATURE = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
function appendChunk(container: Uint8Array, chunk: Uint8Array): Uint8Array {
@@ -34,7 +32,7 @@ describe('@open-pencil/fig package API', () => {
})
it('exports archive API status', () => {
- expect(FIG_PACKAGE_STATUS).toBe('archive-api')
+ expect(FIG_PACKAGE_STATUS).toBe('document-reader')
})
it('round-trips fig-kiwi container bytes', () => {
@@ -109,8 +107,4 @@ describe('@open-pencil/fig package API', () => {
it('rejects invalid fig-kiwi containers', () => {
expect(() => readFigContainer(new Uint8Array([1, 2, 3]))).toThrow('Invalid fig-kiwi')
})
-
- it('directs consumers to core for SceneGraph read/write', () => {
- expect(() => assertFigPackageReady()).toThrow('archive/container APIs')
- })
})
diff --git a/packages/fig/tests/instance-overrides.test.ts b/packages/fig/tests/instance-overrides.test.ts
deleted file mode 100644
index 3e84cd080..000000000
--- a/packages/fig/tests/instance-overrides.test.ts
+++ /dev/null
@@ -1,450 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-
-import { SceneGraph } from '@open-pencil/scene-graph'
-
-import {
- populateAndApplyOverrides,
- protectField,
- syncNodeProps,
- type ProtectionMap
-} from '../src/instance-overrides'
-import { propagateOverridesTransitively } from '../src/instance-overrides/sync/propagate'
-
-describe('@open-pencil/fig instance interpretation', () => {
- test('populates an empty instance from its component tree', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const component = graph.createNode('COMPONENT', pageId, { name: 'Button' })
- graph.createNode('TEXT', component.id, { text: 'Label' })
- const instance = graph.createNode('INSTANCE', pageId, {
- componentId: component.id,
- childIds: []
- })
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- const populated = graph.getNode(instance.id)
- expect(populated?.childIds).toHaveLength(1)
- expect(graph.getNode(populated?.childIds[0] ?? '')?.text).toBe('Label')
- })
-
- test('repositions pinned children through nested resized instances', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const component = graph.createNode('COMPONENT', pageId, {
- width: 442,
- height: 32,
- layoutMode: 'HORIZONTAL'
- })
- graph.createNode('TEXT', component.id, { x: 32, y: 6, width: 80, height: 20 })
- graph.createNode('TEXT', component.id, { x: 120, y: 6, width: 80, height: 20 })
- graph.createNode('INSTANCE', component.id, {
- x: 420,
- y: 9,
- width: 14,
- height: 14,
- layoutPositioning: 'ABSOLUTE',
- horizontalConstraint: 'MAX',
- verticalConstraint: 'CENTER'
- })
- const source = graph.createNode('INSTANCE', pageId, {
- width: 256,
- height: 32,
- layoutMode: 'HORIZONTAL',
- componentId: component.id
- })
- const instance = graph.createNode('INSTANCE', pageId, {
- width: 256,
- height: 32,
- layoutMode: 'HORIZONTAL',
- componentId: source.id
- })
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- const pinned = graph.getChildren(instance.id)[2]
- expect(pinned).toMatchObject({ x: 234, y: 9, width: 14, height: 14 })
- })
-
- test('resizes stretched absolute children with resized instances', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const component = graph.createNode('COMPONENT', pageId, {
- width: 100,
- height: 80,
- layoutMode: 'HORIZONTAL'
- })
- graph.createNode('RECTANGLE', component.id, {
- x: 10,
- y: 10,
- width: 80,
- height: 60,
- layoutPositioning: 'ABSOLUTE',
- horizontalConstraint: 'STRETCH',
- verticalConstraint: 'STRETCH'
- })
- const instance = graph.createNode('INSTANCE', pageId, {
- width: 200,
- height: 120,
- layoutMode: 'HORIZONTAL',
- componentId: component.id
- })
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- expect(graph.getChildren(instance.id)[0]).toMatchObject({
- x: 10,
- y: 10,
- width: 180,
- height: 100
- })
- })
-
- test('applies pinned constraints inside resized freeform instances', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const component = graph.createNode('COMPONENT', pageId, { width: 100, height: 80 })
- graph.createNode('RECTANGLE', component.id, {
- x: 80,
- y: 10,
- width: 10,
- height: 60,
- layoutPositioning: 'ABSOLUTE',
- horizontalConstraint: 'MAX',
- verticalConstraint: 'STRETCH'
- })
- const instance = graph.createNode('INSTANCE', pageId, {
- width: 200,
- height: 120,
- componentId: component.id
- })
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- expect(graph.getChildren(instance.id)[0]).toMatchObject({
- x: 180,
- y: 10,
- width: 10,
- height: 100
- })
- })
-
- test('preserves an inset child when a nested instance becomes narrower', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const field = graph.createNode('COMPONENT', pageId, { width: 280, height: 40 })
- graph.createNode('TEXT', field.id, {
- x: 16,
- y: 10,
- width: 248,
- height: 20,
- text: 'Placeholder'
- })
- const source = graph.createNode('INSTANCE', pageId, {
- width: 240,
- height: 40,
- componentId: field.id
- })
- const instance = graph.createNode('INSTANCE', pageId, {
- width: 180,
- height: 40,
- componentId: source.id
- })
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- const placeholder = graph.getChildren(instance.id)[0]
- expect(placeholder).toMatchObject({ x: 16, y: 10, text: 'Placeholder' })
- })
-
- test('scales target-aspect instance geometry through fixed wrappers', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const component = graph.createNode('COMPONENT', pageId, { width: 310, height: 62 })
- const wrapper = graph.createNode('FRAME', component.id, { width: 310, height: 61.214 })
- const inset = graph.createNode('RECTANGLE', wrapper.id, {
- x: 250,
- y: 10,
- width: 20,
- height: 20,
- horizontalConstraint: 'MAX',
- verticalConstraint: 'MIN'
- })
- const vector = graph.createNode('VECTOR', wrapper.id, {
- width: 56.392,
- height: 61.214,
- horizontalConstraint: 'SCALE',
- verticalConstraint: 'SCALE'
- })
- const instance = graph.createNode('INSTANCE', pageId, {
- width: 100,
- height: 20,
- componentId: component.id
- })
- instance.source.fig.rawNodeFields.targetAspectRatio = { value: { x: 310, y: 62 } }
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- const scaledWrapper = graph.getChildren(instance.id)[0]
- const scaledShape = graph.getChildren(scaledWrapper.id)[1]
- const preservedInset = graph.getChildren(scaledWrapper.id)[0]
- expect(scaledWrapper.width).toBeCloseTo(100)
- expect(scaledWrapper.height).toBeCloseTo((61.214 * 20) / 62)
- expect(preservedInset).toMatchObject({
- x: inset.x,
- y: inset.y,
- width: inset.width,
- height: inset.height
- })
- expect(scaledShape.width).toBeCloseTo((vector.width * 100) / 310)
- expect(scaledShape.height).toBeCloseTo((vector.height * 20) / 62)
- })
-
- test('uses target-aspect metadata only to reach scale-constrained descendants', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const component = graph.createNode('COMPONENT', pageId, { width: 24, height: 24 })
- const vector = graph.createNode('VECTOR', component.id, {
- x: 9,
- y: 3,
- width: 6,
- height: 6,
- horizontalConstraint: 'SCALE',
- verticalConstraint: 'SCALE'
- })
- const instance = graph.createNode('INSTANCE', pageId, {
- width: 14,
- height: 14,
- componentId: component.id
- })
- instance.source.fig.rawNodeFields.targetAspectRatio = { value: { x: 32, y: 32 } }
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- const scaledVector = graph.getChildren(instance.id)[0]
- expect(scaledVector).toMatchObject({
- x: (vector.x * 14) / 24,
- y: (vector.y * 14) / 24,
- width: (vector.width * 14) / 24,
- height: (vector.height * 14) / 24
- })
- })
-
- test('limits lazy population to required global propagation scans', () => {
- const graph = new SceneGraph()
- const activePage = graph.getPages()[0]
- const unrelatedPage = graph.addPage('Unrelated')
- const component = graph.createNode('COMPONENT', unrelatedPage.id, {
- width: 100,
- height: 40
- })
- graph.createNode('TEXT', component.id, { text: 'Label' })
- const instance = graph.createNode('INSTANCE', activePage.id, {
- width: 100,
- height: 40,
- componentId: component.id
- })
- for (let index = 0; index < 5_000; index++) {
- graph.createNode('RECTANGLE', unrelatedPage.id)
- }
-
- let globalScans = 0
- const getAllNodes = graph.getAllNodes.bind(graph)
- graph.getAllNodes = () => {
- globalScans++
- return getAllNodes()
- }
-
- populateAndApplyOverrides(graph, new Map(), new Map(), [], [activePage.id])
-
- expect(graph.getNode(instance.id)?.childIds).toHaveLength(1)
- expect(globalScans).toBe(2)
- })
-
- test('restores effective image and thin-clone geometry after final swaps', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const avatarComponent = graph.createNode('COMPONENT', pageId, { width: 100, height: 100 })
- graph.createNode('ROUNDED_RECTANGLE', avatarComponent.id, {
- width: 100,
- height: 100,
- horizontalConstraint: 'SCALE',
- verticalConstraint: 'SCALE',
- fills: [
- { type: 'IMAGE', imageHash: 'avatar', opacity: 1, visible: true, blendMode: 'NORMAL' }
- ]
- })
- const avatar = graph.createNode('INSTANCE', pageId, {
- componentId: avatarComponent.id,
- width: 14,
- height: 14
- })
-
- const dividerComponent = graph.createNode('COMPONENT', pageId, {
- width: 112,
- height: 28,
- layoutMode: 'HORIZONTAL',
- counterAxisAlign: 'CENTER'
- })
- const dividerSource = graph.createNode('RECTANGLE', dividerComponent.id, {
- x: 0,
- y: 13.5,
- width: 112,
- height: 1,
- derivedLayout: { x: 0, y: 13.5, width: 112, height: 1 }
- })
- const dividerInstance = graph.createNode('INSTANCE', pageId, {
- componentId: dividerComponent.id,
- width: 112,
- height: 28,
- layoutMode: 'HORIZONTAL',
- counterAxisAlign: 'CENTER'
- })
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- const avatarLeaf = graph.getChildren(avatar.id)[0]
- expect(avatarLeaf).toMatchObject({ width: 14, height: 14 })
- const divider = graph.getChildren(dividerInstance.id)[0]
- expect(divider.componentId).toBe(dividerSource.id)
- expect(divider.derivedLayout).toMatchObject({ x: 0, y: 13.5 })
- })
-
- test('leaves unrelated scaled vector and multi-child instance geometry unchanged', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const vectorComponent = graph.createNode('COMPONENT', pageId, { width: 100, height: 100 })
- graph.createNode('VECTOR', vectorComponent.id, {
- width: 20,
- height: 10,
- horizontalConstraint: 'SCALE',
- verticalConstraint: 'SCALE'
- })
- const vectorInstance = graph.createNode('INSTANCE', pageId, {
- componentId: vectorComponent.id,
- width: 50,
- height: 50
- })
- const multiComponent = graph.createNode('COMPONENT', pageId, { width: 100, height: 100 })
- graph.createNode('ROUNDED_RECTANGLE', multiComponent.id, {
- width: 100,
- height: 100,
- horizontalConstraint: 'SCALE',
- verticalConstraint: 'SCALE',
- fills: [
- { type: 'IMAGE', imageHash: 'avatar', opacity: 1, visible: true, blendMode: 'NORMAL' }
- ]
- })
- graph.createNode('RECTANGLE', multiComponent.id, { width: 10, height: 10 })
- const multiInstance = graph.createNode('INSTANCE', pageId, {
- componentId: multiComponent.id,
- width: 50,
- height: 50
- })
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- expect(graph.getChildren(vectorInstance.id)[0]).toMatchObject({ width: 10, height: 5 })
- expect(graph.getChildren(multiInstance.id)[0]).toMatchObject({ width: 50, height: 50 })
- })
-
- test('resolves text clone chains to their source values', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const source = graph.createNode('TEXT', pageId, {
- text: 'Label',
- width: 80,
- fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
- })
- const middle = graph.createNode('TEXT', pageId, {
- componentId: source.id,
- text: 'Label',
- width: 120
- })
- const leaf = graph.createNode('TEXT', pageId, {
- componentId: middle.id,
- text: 'Label',
- width: 160
- })
-
- populateAndApplyOverrides(graph, new Map(), new Map())
-
- expect(graph.getNode(middle.id)?.width).toBe(80)
- expect(graph.getNode(leaf.id)).toMatchObject({ width: 80, fills: source.fills })
- })
-
- test('synchronizes opacity bindings with their resolved value', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const source = graph.createNode('INSTANCE', pageId, {
- opacity: 0.5,
- boundVariables: { opacity: 'opacity-var' }
- })
- const target = graph.createNode('INSTANCE', pageId, {
- opacity: 1,
- componentId: source.id
- })
-
- syncNodeProps(graph, source, target)
-
- expect(graph.getNode(target.id)).toMatchObject({
- opacity: 0.5,
- boundVariables: { opacity: 'opacity-var' }
- })
- })
-
- test('clears opacity bindings removed from the source', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const source = graph.createNode('INSTANCE', pageId, { opacity: 1 })
- const target = graph.createNode('INSTANCE', pageId, {
- opacity: 0.5,
- componentId: source.id,
- boundVariables: { opacity: 'stale-opacity-var', width: 'width-var' }
- })
-
- syncNodeProps(graph, source, target)
-
- expect(graph.getNode(target.id)?.boundVariables).toEqual({ width: 'width-var' })
- })
-
- test('inherits effective text on a structurally protected clone', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const component = graph.createNode('COMPONENT', pageId)
- const source = graph.createNode('TEXT', component.id, {
- text: 'Effective label'
- })
- const instance = graph.createNode('INSTANCE', pageId, { componentId: component.id })
- graph.populateInstanceChildren(instance.id, component.id, 'fig-import')
- const clone = graph.getChildren(instance.id)[0]
- graph.updateNode(clone.id, { text: 'Default label' })
- const protections: ProtectionMap = new Map()
- protectField(protections, clone.id, 'width')
-
- propagateOverridesTransitively(
- graph,
- new Set([source.id, clone.id]),
- new Set(),
- new Map(),
- undefined,
- undefined,
- protections
- )
-
- expect(graph.getNode(clone.id)?.text).toBe('Effective label')
- })
-
- test('preserves protected text while synchronizing other fields', () => {
- const graph = new SceneGraph()
- const pageId = graph.getPages()[0].id
- const source = graph.createNode('TEXT', pageId, { text: 'Source', visible: false })
- const target = graph.createNode('TEXT', pageId, { text: 'Override', visible: true })
- const protections: ProtectionMap = new Map()
- protectField(protections, target.id, 'text')
-
- syncNodeProps(graph, source, target, protections)
-
- expect(graph.getNode(target.id)).toMatchObject({ text: 'Override', visible: false })
- })
-})
diff --git a/packages/fig/tests/instance-overrides/addressing.test.ts b/packages/fig/tests/instance-overrides/addressing.test.ts
new file mode 100644
index 000000000..cd2d1f5a2
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/addressing.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, test } from 'bun:test'
+
+import { expectPathError } from '#fig-tests/helpers/errors'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const component = { sessionID: 1, localID: 1 }
+const label = { sessionID: 1, localID: 2 }
+const alias = { sessionID: 8, localID: 2 }
+const first = { sessionID: 2, localID: 1 }
+const second = { sessionID: 2, localID: 2 }
+const outer = { sessionID: 3, localID: 1 }
+const placed = { sessionID: 4, localID: 1 }
+
+function fixture(): NodeChange[] {
+ return [
+ { guid: component, type: 'SYMBOL' },
+ {
+ guid: label,
+ overrideKey: alias,
+ type: 'TEXT',
+ parentIndex: { guid: component, position: '!' },
+ textData: { characters: 'Default' }
+ },
+ { guid: outer, type: 'SYMBOL' },
+ {
+ guid: first,
+ type: 'INSTANCE',
+ parentIndex: { guid: outer, position: '!' },
+ symbolData: { symbolID: component }
+ },
+ {
+ guid: second,
+ type: 'INSTANCE',
+ parentIndex: { guid: outer, position: '"' },
+ symbolData: { symbolID: component }
+ },
+ {
+ guid: placed,
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: outer,
+ symbolOverrides: [
+ { guidPath: { guids: [second, alias] }, textData: { characters: 'Second' } },
+ { guidPath: { guids: [outer] }, opacity: 0.5 }
+ ]
+ }
+ } as NodeChange
+ ]
+}
+
+describe('instance addressing contracts', () => {
+ test('targets the second occurrence through overrideKey without touching its sibling', () => {
+ const result = interpretInstance(fixture(), '4:1')
+ expect(result.properties.opacity).toBe(0.5)
+ expect(result.children[0].children[0].properties.textData?.characters).toBe('Default')
+ expect(result.children[1].children[0].properties.textData?.characters).toBe('Second')
+ })
+
+ test('retains explicit equal-to-default claims without treating inherited fields as overrides', () => {
+ const input = fixture()
+ const placedSource = input.find((node) => node.guid === placed)
+ if (!placedSource?.symbolData) throw new Error('Missing placed source')
+ placedSource.symbolData.symbolOverrides = [
+ { guidPath: { guids: [second, alias] }, textData: { characters: 'Default' } }
+ ]
+ const result = interpretInstance(input, '4:1')
+ expect(result.children[0].propertyClaims).toEqual([])
+ expect(result.propertyClaims).toEqual([
+ {
+ declaredBy: '4:1',
+ path: [second, alias],
+ properties: { textData: { characters: 'Default' } }
+ }
+ ])
+ expect(result.children[0].children[0].properties.textData?.characters).toBe(
+ result.children[1].children[0].properties.textData?.characters
+ )
+ })
+
+ test('occurrence payloads and subsequent interpretations share no mutable data', () => {
+ const input = fixture()
+ const result = interpretInstance(input, '4:1')
+ const text = result.children[0].children[0].properties.textData
+ if (!text) throw new Error('Expected text payload')
+ text.characters = 'Mutated'
+ expect(result.children[1].children[0].properties.textData?.characters).toBe('Second')
+ expect(
+ interpretInstance(input, '4:1').children[0].children[0].properties.textData?.characters
+ ).toBe('Default')
+ })
+
+ test('does not search across nested instance boundaries for a missing path segment', () => {
+ const input = fixture()
+ const root = input.find((node) => node.guid === placed)
+ if (!root) throw new Error('Missing root')
+ root.symbolData = {
+ symbolID: outer,
+ symbolOverrides: [{ guidPath: { guids: [alias] }, opacity: 0 }]
+ } as NodeChange['symbolData']
+ expectPathError(() => interpretInstance(input, '4:1'), 'missing-target')
+ })
+
+ test('rejects ambiguous overrideKey matches rather than choosing the first', () => {
+ const input = fixture()
+ input.push({
+ guid: { sessionID: 1, localID: 3 },
+ type: 'TEXT',
+ overrideKey: alias,
+ parentIndex: { guid: component, position: '"' }
+ })
+ expectPathError(() => interpretInstance(input, '4:1'), 'ambiguous-target')
+ })
+
+ test('rejects missing component sources', () => {
+ expect(() =>
+ interpretInstance(
+ fixture().filter((node) => node.guid !== component),
+ '4:1'
+ )
+ ).toThrow('Missing source node 1:1')
+ })
+})
diff --git a/packages/fig/tests/instance-overrides/binding-provenance.test.ts b/packages/fig/tests/instance-overrides/binding-provenance.test.ts
new file mode 100644
index 000000000..31973b125
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/binding-provenance.test.ts
@@ -0,0 +1,110 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import {
+ bindSourceProperties,
+ componentBindings,
+ instanceBindings,
+ type BoundPropertyClaim
+} from '#fig/instance-overrides/bindings/properties'
+import { materializeComponentClosure } from '#fig/instance-overrides/component-closure'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+import { materializeInstance } from '#fig/instance-overrides/materialize-instance'
+import { mapInstanceSourceChildren } from '#fig/instance-overrides/source-children'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph, hasInstanceOverride } from '@open-pencil/scene-graph'
+
+test('materialization preserves explicit equal-to-default text', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1, 3), type: 'SYMBOL' },
+ {
+ guid: guid(2, 3),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1, 3), position: '!' },
+ textData: { characters: 'Default' }
+ },
+ {
+ guid: guid(3, 3),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1, 3),
+ symbolOverrides: [
+ { guidPath: { guids: [guid(2, 3)] }, textData: { characters: 'Default' } }
+ ]
+ }
+ } as NodeChange
+ ]
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const occurrence = interpretInstance(changes, '3:3')
+ const closure = materializeComponentClosure(graph, page.id, changes, occurrence)
+ const ids = new Map([...closure].map(([id, value]) => [id, value.materialized.root.id]))
+ const result = materializeInstance(graph, page.id, occurrence, ids, {
+ sourceChildren: mapInstanceSourceChildren(occurrence, closure)
+ })
+ const component = closure.get('3:1')
+ if (!component) throw new Error('Missing component')
+ graph.updateNode(graph.getChildren(component.materialized.root.id)[0].id, { text: 'Changed' })
+ graph.syncInstances(component.materialized.root.id)
+ expect(graph.getChildren(result.root.id)[0].text).toBe('Default')
+})
+
+const id = { sessionID: 1, localID: 10 }
+
+for (const assigned of [false, true]) {
+ test(`materialization protects Boolean assignments only (assigned=${assigned})`, () => {
+ const changes = [
+ {
+ guid: guid(1, 2),
+ type: 'SYMBOL',
+ componentPropDefs: [{ id, initialValue: { boolValue: false } }]
+ },
+ {
+ guid: guid(2, 2),
+ type: 'RECTANGLE',
+ parentIndex: { guid: guid(1, 2), position: '!' },
+ componentPropRefs: [{ defID: id, componentPropNodeField: 'VISIBLE' }]
+ },
+ {
+ guid: guid(3, 2),
+ type: 'INSTANCE',
+ symbolData: { symbolID: guid(1, 2) },
+ componentPropAssignments: assigned ? [{ defID: id, value: { boolValue: false } }] : []
+ }
+ ] as NodeChange[]
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const occurrence = interpretInstance(changes, '2:3')
+ const closure = materializeComponentClosure(graph, page.id, changes, occurrence)
+ const ids = new Map([...closure].map(([id, value]) => [id, value.materialized.root.id]))
+ const result = materializeInstance(graph, page.id, occurrence, ids, {
+ sourceChildren: mapInstanceSourceChildren(occurrence, closure)
+ })
+ const child = graph.getChildren(result.root.id)[0]
+ expect(child.visible).toBe(false)
+ expect(hasInstanceOverride(graph, child.id, 'visible')).toBe(assigned)
+ })
+}
+
+test('distinguishes an equal-to-default Boolean assignment from a component default', () => {
+ const component = {
+ componentPropDefs: [{ id, initialValue: { boolValue: false } }]
+ } as NodeChange
+ const child = {
+ componentPropRefs: [{ defID: id, componentPropNodeField: 'VISIBLE' }]
+ } as NodeChange
+ const defaults = componentBindings(component)
+ const inheritedClaims: BoundPropertyClaim[] = []
+ const assignedClaims: BoundPropertyClaim[] = []
+ const inherited = bindSourceProperties(child, defaults, (claim) => inheritedClaims.push(claim))
+ const assigned = bindSourceProperties(
+ child,
+ instanceBindings(defaults, [{ defID: id, value: { boolValue: false } }]),
+ (claim) => assignedClaims.push(claim)
+ )
+ expect(inherited.visible).toBe(false)
+ expect(assigned.visible).toBe(false)
+ expect(inheritedClaims).toEqual([{ definitionId: id, field: 'visible', origin: 'default' }])
+ expect(assignedClaims).toEqual([{ definitionId: id, field: 'visible', origin: 'assignment' }])
+})
diff --git a/packages/fig/tests/instance-overrides/bindings.test.ts b/packages/fig/tests/instance-overrides/bindings.test.ts
new file mode 100644
index 000000000..8a34ea48a
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/bindings.test.ts
@@ -0,0 +1,381 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+import type { SymbolOverride } from '#fig/instance-overrides/types'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+function withRootOverrides(
+ changes: NodeChange[],
+ localID: number,
+ overrides: SymbolOverride[]
+): void {
+ const node = changes.find((source) => source.guid?.localID === localID)
+ if (!node?.symbolData) throw new Error('Missing instance')
+ node.symbolData = { ...node.symbolData, symbolOverrides: overrides } as NodeChange['symbolData']
+}
+
+test('outer bindings control nested instance roots without entering their component scope', () => {
+ const changes = fixture()
+ const icon = changes.find((node) => node.guid?.localID === 4)
+ const inner = changes.find((node) => node.guid?.localID === 10)
+ const innerLeaf = changes.find((node) => node.guid?.localID === 11)
+ if (!icon || !inner || !innerLeaf) throw new Error('Missing fixture nodes')
+ icon.componentPropRefs = [{ defID: guid(90), componentPropNodeField: 'VISIBLE' }]
+ inner.componentPropDefs = [
+ { id: guid(90), name: 'Inner shown', type: 'BOOL', initialValue: { boolValue: false } }
+ ]
+ innerLeaf.componentPropRefs = [{ defID: guid(90), componentPropNodeField: 'VISIBLE' }]
+ withRootOverrides(changes, 30, [{ guidPath: { guids: [guid(22), guid(4)] }, visible: false }])
+ changes.push(
+ { guid: guid(50), type: 'SYMBOL' },
+ {
+ guid: guid(51),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(50), position: '!' },
+ symbolData: { symbolID: guid(30) }
+ },
+ { guid: guid(52), type: 'INSTANCE', symbolData: { symbolID: guid(50) } }
+ )
+ withRootOverrides(changes, 52, [
+ {
+ guidPath: { guids: [guid(51), guid(22)] },
+ componentPropAssignments: [{ defID: guid(90), value: { boolValue: true } }]
+ }
+ ])
+ const target = interpretInstance(changes, '1:52').children[0].children[1].children[0].children[1]
+ expect(target.properties.visible).toBe(true)
+ expect(target.children[0].properties.visible).toBe(false)
+})
+
+test('a newer binding wins over an intermediate patch to the same text field', () => {
+ const changes = fixture()
+ withRootOverrides(changes, 30, [
+ {
+ guidPath: { guids: [guid(22), guid(3)] },
+ textData: { characters: 'Intermediate edit' },
+ opacity: 0.4
+ }
+ ])
+ changes.push(
+ { guid: guid(50), type: 'SYMBOL' },
+ {
+ guid: guid(51),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(50), position: '!' },
+ symbolData: { symbolID: guid(30) }
+ },
+ { guid: guid(52), type: 'INSTANCE', symbolData: { symbolID: guid(50) } }
+ )
+ withRootOverrides(changes, 52, [
+ {
+ guidPath: { guids: [guid(51), guid(22)] },
+ componentPropAssignments: [{ defID: guid(91), value: { textValue: 'Outer assignment' } }]
+ }
+ ])
+ const result = interpretInstance(changes, '1:52')
+ const label = result.children[0].children[1].children[0].children[0]
+ expect(result.children[0].propertyClaims).toEqual([
+ { declaredBy: '1:30', path: [guid(22), guid(3)], properties: { opacity: 0.4 } }
+ ])
+ expect(label.properties.textData?.characters).toBe('Outer assignment')
+ expect(label.properties.opacity).toBe(0.4)
+ const independent = interpretInstance(changes, '1:30')
+ expect(independent.propertyClaims[0]?.properties.textData).toEqual({
+ characters: 'Intermediate edit'
+ })
+})
+
+test('retains an intermediate explicit descendant override when an outer binding changes', () => {
+ const changes = fixture()
+ withRootOverrides(changes, 30, [
+ {
+ guidPath: { guids: [guid(22), guid(3)] },
+ opacity: 0.4
+ }
+ ])
+ changes.push(
+ { guid: guid(50), type: 'SYMBOL' },
+ {
+ guid: guid(51),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(50), position: '!' },
+ symbolData: { symbolID: guid(30) }
+ },
+ { guid: guid(52), type: 'INSTANCE', symbolData: { symbolID: guid(50) } }
+ )
+ withRootOverrides(changes, 52, [
+ {
+ guidPath: { guids: [guid(51), guid(22)] },
+ componentPropAssignments: [{ defID: guid(91), value: { textValue: 'Outer text' } }]
+ }
+ ])
+ const result = interpretInstance(changes, '1:52')
+ const owner = result.children[0]
+ expect(owner.propertyClaims).toEqual([
+ { declaredBy: '1:30', path: [guid(22), guid(3)], properties: { opacity: 0.4 } }
+ ])
+ const label = result.children[0].children[1].children[0].children[0]
+ expect(label.properties.textData?.characters).toBe('Outer text')
+ expect(label.properties.opacity).toBe(0.4)
+
+ withRootOverrides(changes, 52, [
+ {
+ guidPath: { guids: [guid(51), guid(22)] },
+ componentPropAssignments: [{ defID: guid(91), value: { textValue: 'Outer text' } }]
+ },
+ { guidPath: { guids: [guid(51), guid(22), guid(3)] }, opacity: 0.8 }
+ ])
+ const overridden = interpretInstance(changes, '1:52').children[0].children[1].children[0]
+ .children[0]
+ expect(overridden.properties.opacity).toBe(0.8)
+})
+
+test('restores ordered claims field-wise without mutating source records or sibling occurrences', () => {
+ const changes = fixture()
+ withRootOverrides(changes, 30, [
+ { guidPath: { guids: [guid(22), guid(3)] }, opacity: 0.4, fontSize: 18 },
+ {
+ guidPath: { guids: [guid(22), guid(3)] },
+ opacity: 0.6,
+ textData: { characters: 'Intermediate' }
+ }
+ ])
+ changes.push(
+ { guid: guid(50), type: 'SYMBOL' },
+ {
+ guid: guid(51),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(50), position: '!' },
+ symbolData: { symbolID: guid(30) }
+ },
+ { guid: guid(52), type: 'INSTANCE', symbolData: { symbolID: guid(50) } }
+ )
+ withRootOverrides(changes, 52, [
+ {
+ guidPath: { guids: [guid(51), guid(22)] },
+ componentPropAssignments: [{ defID: guid(91), value: { textValue: 'Outer' } }]
+ }
+ ])
+ const source = structuredClone(changes)
+ const result = interpretInstance(changes, '1:52')
+ const owner = result.children[0]
+ const label = owner.children[1].children[0].children[0]
+ expect(label.properties).toMatchObject({
+ opacity: 0.6,
+ fontSize: 18,
+ textData: { characters: 'Outer' }
+ })
+ expect(owner.propertyClaims.map((claim) => claim.properties)).toEqual([
+ { opacity: 0.4, fontSize: 18 },
+ { opacity: 0.6 }
+ ])
+ expect(owner.children[0].children[0].children[0].properties.textData?.characters).toBe('Default')
+ label.properties.textData = { characters: 'Mutated result' }
+ owner.propertyClaims[0].properties.fontSize = 99
+ const independent = interpretInstance(changes, '1:30')
+ expect(independent.children[1].children[0].children[0].properties).toMatchObject({
+ opacity: 0.6,
+ fontSize: 18,
+ textData: { characters: 'Intermediate' }
+ })
+ expect(changes).toEqual(source)
+})
+
+test('retains intermediate-owner assignments when an outer owner configures another property', () => {
+ const changes = fixture()
+ withRootOverrides(changes, 30, [
+ {
+ guidPath: { guids: [guid(22)] },
+ componentPropAssignments: [{ defID: guid(90), value: { boolValue: true } }]
+ }
+ ])
+ changes.push(
+ { guid: guid(50), type: 'SYMBOL' },
+ {
+ guid: guid(51),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(50), position: '!' },
+ symbolData: { symbolID: guid(30) }
+ },
+ { guid: guid(52), type: 'INSTANCE', symbolData: { symbolID: guid(50) } }
+ )
+ withRootOverrides(changes, 52, [
+ {
+ guidPath: { guids: [guid(51), guid(22)] },
+ componentPropAssignments: [{ defID: guid(91), value: { textValue: 'Outer text' } }]
+ }
+ ])
+ const result = interpretInstance(changes, '1:52')
+ const label = result.children[0].children[1].children[0].children[0]
+ expect(label.properties.visible).toBe(true)
+ expect(label.properties.textData?.characters).toBe('Outer text')
+})
+
+test('combines repeated assignment entries by property, with later values winning', () => {
+ const changes = fixture()
+ withRootOverrides(changes, 30, [
+ {
+ guidPath: { guids: [guid(22)] },
+ componentPropAssignments: [
+ { defID: guid(90), value: { boolValue: true } },
+ { defID: guid(91), value: { textValue: 'Earlier' } }
+ ]
+ },
+ {
+ guidPath: { guids: [guid(22)] },
+ componentPropAssignments: [{ defID: guid(91), value: { textValue: 'Later' } }]
+ }
+ ])
+ const second = interpretInstance(changes, '1:30').children[1].children[0].children
+ expect(second[0].properties.visible).toBe(true)
+ expect(second[0].properties.textData?.characters).toBe('Later')
+ expect(second[1].mainComponentId).toBe('1:12')
+})
+
+test('applies root-targeted assignments without re-entering the same instance', () => {
+ const changes = fixture()
+ withRootOverrides(changes, 22, [
+ {
+ guidPath: { guids: [guid(1)] },
+ componentPropAssignments: [{ defID: guid(91), value: { textValue: 'Root assignment' } }]
+ }
+ ])
+ const second = interpretInstance(changes, '1:30').children[1].children[0].children
+ expect(second[0].properties.textData?.characters).toBe('Root assignment')
+ expect(second[0].properties.visible).toBe(false)
+})
+
+test('applies assignments to the replacement component before descendant overrides', () => {
+ const changes = fixture()
+ changes.push(
+ {
+ guid: guid(40),
+ type: 'SYMBOL',
+ componentPropDefs: [
+ {
+ id: guid(93),
+ name: 'Replacement text',
+ type: 'TEXT',
+ initialValue: { textValue: 'Replacement default' }
+ }
+ ]
+ },
+ {
+ guid: guid(41),
+ type: 'TEXT',
+ parentIndex: { guid: guid(40), position: '!' },
+ componentPropRefs: [{ defID: guid(93), componentPropNodeField: 'TEXT_DATA' }]
+ }
+ )
+ withRootOverrides(changes, 30, [
+ { guidPath: { guids: [guid(22), guid(41)] }, fontSize: 24 },
+ { guidPath: { guids: [guid(22)] }, overriddenSymbolID: guid(40) },
+ {
+ guidPath: { guids: [guid(22)] },
+ componentPropAssignments: [{ defID: guid(93), value: { textValue: 'Assigned replacement' } }]
+ }
+ ])
+ const result = interpretInstance(changes, '1:30')
+ expect(result.children[1].mainComponentId).toBe('1:40')
+ expect(result.children[1].children[0].properties.textData?.characters).toBe(
+ 'Assigned replacement'
+ )
+ expect(result.children[1].children[0].properties.fontSize).toBe(24)
+ expect(result.children[0].children[0].children[0].properties.textData?.characters).toBe('Default')
+})
+
+function fixture(): NodeChange[] {
+ return [
+ {
+ guid: guid(1),
+ type: 'SYMBOL',
+ componentPropDefs: [
+ { id: guid(90), name: 'Shown', type: 'BOOL', initialValue: { boolValue: true } },
+ { id: guid(91), name: 'Text', type: 'TEXT', initialValue: { textValue: 'Default' } },
+ { id: guid(92), name: 'Icon', type: 'INSTANCE_SWAP', initialValue: { guidValue: guid(10) } }
+ ]
+ },
+ { guid: guid(2), type: 'FRAME', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ parentIndex: { guid: guid(2), position: '!' },
+ componentPropRefs: [
+ { defID: guid(90), componentPropNodeField: 'VISIBLE' },
+ { defID: guid(91), componentPropNodeField: 'TEXT_DATA' }
+ ]
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(2), position: '"' },
+ symbolData: { symbolID: guid(10) },
+ componentPropRefs: [{ defID: guid(92), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }]
+ },
+ { guid: guid(10), type: 'SYMBOL' },
+ { guid: guid(11), type: 'RECTANGLE', parentIndex: { guid: guid(10), position: '!' } },
+ { guid: guid(12), type: 'SYMBOL' },
+ { guid: guid(13), type: 'ELLIPSE', parentIndex: { guid: guid(12), position: '!' } },
+ { guid: guid(20), type: 'SYMBOL' },
+ {
+ guid: guid(21),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(20), position: '!' },
+ symbolData: { symbolID: guid(1) }
+ },
+ {
+ guid: guid(22),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(20), position: '"' },
+ symbolData: { symbolID: guid(1) },
+ componentPropAssignments: [
+ { defID: guid(90), value: { boolValue: false } },
+ { defID: guid(91), value: { textValue: 'Second' } },
+ { defID: guid(92), value: { guidValue: guid(12) } }
+ ]
+ },
+ { guid: guid(30), type: 'INSTANCE', symbolData: { symbolID: guid(20) } }
+ ] as NodeChange[]
+}
+
+test('isolates Boolean, text and swap bindings in repeated wrapper instances', () => {
+ const changes = fixture()
+ const before = structuredClone(changes)
+ const result = interpretInstance(changes, '1:30')
+ const [first, second] = result.children.map((node) => node.children[0].children)
+ expect(first[0].properties.visible).toBe(true)
+ expect(first[0].properties.textData?.characters).toBe('Default')
+ expect(first[1].mainComponentId).toBe('1:10')
+ expect(second[0].properties.visible).toBe(false)
+ expect(second[0].properties.textData?.characters).toBe('Second')
+ expect(second[1].mainComponentId).toBe('1:12')
+ expect(second[1].children[0].properties.type).toBe('ELLIPSE')
+ expect(changes).toEqual(before)
+})
+
+test('outer nested assignments override inherited values without leaking to siblings', () => {
+ const changes = fixture()
+ const root = changes.find((node) => node.guid?.localID === 30)
+ if (!root) throw new Error('Missing root')
+ root.symbolData = {
+ symbolID: guid(20),
+ symbolOverrides: [
+ {
+ guidPath: { guids: [guid(22)] },
+ componentPropAssignments: [
+ { defID: guid(90), value: { boolValue: true } },
+ { defID: guid(91), value: { textValue: 'Outer assignment' } },
+ { defID: guid(92), value: { guidValue: guid(10) } }
+ ]
+ }
+ ]
+ } as NodeChange['symbolData']
+ const result = interpretInstance(changes, '1:30')
+ const [first, second] = result.children.map((node) => node.children[0].children)
+ expect(first[0].properties.textData?.characters).toBe('Default')
+ expect(second[0].properties.textData?.characters).toBe('Outer assignment')
+ expect(second[0].properties.visible).toBe(true)
+ expect(second[1].mainComponentId).toBe('1:10')
+})
diff --git a/packages/fig/tests/instance-overrides/closure-properties.test.ts b/packages/fig/tests/instance-overrides/closure-properties.test.ts
new file mode 100644
index 000000000..f4b243893
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/closure-properties.test.ts
@@ -0,0 +1,79 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { materializeComponentClosure } from '#fig/instance-overrides/component-closure'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function records(defaultId = 2): NodeChange[] {
+ return [
+ {
+ guid: guid(1),
+ type: 'SYMBOL',
+ name: 'Host',
+ componentPropDefs: [
+ {
+ id: guid(10),
+ name: 'Choice',
+ type: 'INSTANCE_SWAP',
+ initialValue: { guidValue: guid(defaultId) },
+ preferredValues: { instanceSwapValues: [{ key: 'external-choice', version: 'v1' }] }
+ }
+ ]
+ },
+ { guid: guid(2), type: 'SYMBOL', name: 'Inactive default' },
+ { guid: guid(3), type: 'INSTANCE', symbolData: { symbolID: guid(1) } }
+ ] as NodeChange[]
+}
+
+for (const defaultId of [1, 2]) {
+ test(`closure includes and remaps inactive default ${defaultId} without expanding it`, () => {
+ const changes = records(defaultId)
+ const graph = new SceneGraph()
+ const closure = materializeComponentClosure(
+ graph,
+ graph.getPages()[0].id,
+ changes,
+ interpretInstance(changes, '1:3')
+ )
+ const host = closure.get('1:1')?.materialized.root
+ const target = closure.get(`1:${defaultId}`)?.materialized.root
+ expect(target?.type).toBe('COMPONENT')
+ expect(host?.componentPropertyDefinitions[0].defaultValue).toBe(target?.id)
+ expect(closure.externalPreferredKeys).toEqual(new Set(['external-choice']))
+ expect(host?.componentPropertyDefinitions[0].preferredValues).toEqual(['external-choice'])
+ expect(host?.childIds).toEqual([])
+ expect(changes[0].componentPropDefs?.[0].initialValue?.guidValue).toEqual(guid(defaultId))
+ })
+}
+
+test('closure rejects missing required defaults rather than retaining dangling source IDs', () => {
+ const changes = records(999)
+ const graph = new SceneGraph()
+ expect(() =>
+ materializeComponentClosure(
+ graph,
+ graph.getPages()[0].id,
+ changes,
+ interpretInstance(changes, '1:3')
+ )
+ ).toThrow()
+})
+
+test('closure resolves available preferred choices by exact resource version', () => {
+ const changes = records()
+ changes.push({ guid: guid(4), type: 'SYMBOL', key: 'external-choice', version: 'v1' })
+ changes.push({ guid: guid(5), type: 'SYMBOL', key: 'external-choice', version: 'v2' })
+ const graph = new SceneGraph()
+ const closure = materializeComponentClosure(
+ graph,
+ graph.getPages()[0].id,
+ changes,
+ interpretInstance(changes, '1:3')
+ )
+ expect(closure.has('1:4')).toBe(true)
+ expect(closure.has('1:5')).toBe(false)
+ expect(closure.externalPreferredKeys.size).toBe(0)
+})
diff --git a/packages/fig/tests/instance-overrides/derived-transform.test.ts b/packages/fig/tests/instance-overrides/derived-transform.test.ts
new file mode 100644
index 000000000..6d9bda742
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/derived-transform.test.ts
@@ -0,0 +1,51 @@
+import { expect, test } from 'bun:test'
+
+import { interpretInstance, materializeInstance } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph, getNodeLocalMatrix } from '@open-pencil/scene-graph'
+
+for (const reflected of [false, true]) {
+ test(`derived size keeps the original local matrix (reflected=${reflected})`, () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const transform = reflected
+ ? { m00: 0, m01: -1, m02: 78, m10: -1, m11: 0, m12: 790 }
+ : { m00: 1, m01: 0, m02: 8, m10: 0, m11: 1, m12: 8 }
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'VECTOR',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 24, y: 24 },
+ transform
+ },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ symbolData: { symbolID: guid(1) },
+ derivedSymbolData: [{ guidPath: { guids: [guid(2)] }, size: { x: 184, y: 36 } }]
+ }
+ ]
+ const graph = new SceneGraph()
+ const occurrence = interpretInstance(changes, '1:3', { derivedBounds: true })
+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id)
+ const materialized = materializeInstance(
+ graph,
+ graph.getPages()[0].id,
+ occurrence,
+ new Map([['1:1', component.id]])
+ )
+ const child = graph.getChildren(materialized.root.id)[0]
+ expect([child.width, child.height]).toEqual([184, 36])
+ const actual = getNodeLocalMatrix(child)
+ const expected = [
+ transform.m00,
+ transform.m01,
+ transform.m02,
+ transform.m10,
+ transform.m11,
+ transform.m12
+ ]
+ for (const [index, value] of expected.entries()) expect(actual[index]).toBeCloseTo(value, 10)
+ })
+}
diff --git a/packages/fig/tests/instance-overrides/detached-lineage.test.ts b/packages/fig/tests/instance-overrides/detached-lineage.test.ts
new file mode 100644
index 000000000..b2148c201
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/detached-lineage.test.ts
@@ -0,0 +1,50 @@
+import { expect, test } from 'bun:test'
+
+import { createOccurrenceInterpreter } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const guid = (sessionID: number, localID: number) => ({ sessionID, localID })
+
+test('detached-symbol lineage retires an obsolete property path only when the live property target is explicit', () => {
+ const records: NodeChange[] = [
+ { guid: guid(1, 1), type: 'SYMBOL' },
+ {
+ guid: guid(1, 2),
+ type: 'FRAME',
+ parentIndex: { guid: guid(1, 1), position: '!' },
+ detachedSymbolId: { guid: guid(2, 1) }
+ },
+ {
+ guid: guid(1, 3),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1, 2), position: '!' },
+ componentPropRefs: [{ defID: guid(3, 1), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }],
+ symbolData: { symbolID: guid(4, 1) }
+ },
+ { guid: guid(2, 1), type: 'SYMBOL' },
+ {
+ guid: guid(2, 2),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(2, 1), position: '!' },
+ componentPropRefs: [{ defID: guid(3, 1), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }],
+ symbolData: { symbolID: guid(4, 1) }
+ },
+ {
+ guid: guid(5, 1),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1, 1),
+ symbolOverrides: [
+ {
+ guidPath: { guids: [guid(9, 9)] },
+ componentPropAssignments: [{ defID: guid(3, 1), value: { guidValue: guid(4, 2) } }]
+ }
+ ]
+ }
+ }
+ ]
+ expect(() => createOccurrenceInterpreter(records).instance('5:1')).toThrow(
+ 'Expected one instance-path target'
+ )
+})
diff --git a/packages/fig/tests/instance-overrides/fixtures/README.md b/packages/fig/tests/instance-overrides/fixtures/README.md
new file mode 100644
index 000000000..698201ac6
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/fixtures/README.md
@@ -0,0 +1,21 @@
+# Instance interpreter fixtures
+
+These JSON files contain decoded Figma NodeChanges, not SceneGraph snapshots.
+
+- `accordion-instance-paths.json`: semantic-field reduction of the source closure for instance `7:283` from `shadcn Figma kit (Community).fig`. Tests component selection, distinct repeated labels and outer typography.
+- `accordion-source-closure.json`: all decoded fields on the 23 source records reachable through that instance's component references, explicit swaps and children. Blob indexes refer to the original archive; this fixture is for semantic interpretation, not raster or geometry decoding. It retains the stale `7:93` override.
+- `stale-chevron-override.json`: source records `7:95`, `7:94`, `94:5438` from the same archive. Figma reports the old `I7:95;7:93` stroke override but its actual vector is `I7:95;94:5438`, with no strokes. The interpreter must not retarget the stale override.
+- `saved-swap-paths.json`: semantic fields from a controlled probe exported using Figma's **Save local copy** command. Source component `10965:1259`, replacement `10965:1261`, host `10965:1269`. Instances `10965:1263` and `10965:1266` cover untouched/edited top-level swaps; `10965:1272` and `10965:1276` distinguish nested `swapComponent()` from assigning `mainComponent`. Preserved text is explicitly encoded against the replacement child's GUID.
+- `name-provenance.json`: reduced Figma save records and live observations for untouched, explicitly equal-to-default, and custom instance names, plus variant-set versus unrelated-component swaps. All store a name; only explicit renames carry a root-targeted name claim. Untouched variant instances use the component-set name. Temporary probe pages were removed after capture.
+
+Oracle checks use the actual Figma Plugin API via figma-use. These reduced fixtures establish specific component/text/binding contracts; they do not establish complete rendering or document-editing parity. Derived-geometry and full-document behavior have separate tests.
+
+## Gold Preview source evidence
+
+The archive-backed gold preview test, now in `tests/engine/io/fig/instance/gold/`, uses
+`tests/fixtures/gold-preview.fig`. In original
+Figma file `NmoHzskYNiSKOaRX14bMdw`, source badges `1:1820`, `1:1821`, and `1:1822` report
+`characters` overrides. Their placed occurrences under input `1:3503` inherit those claims
+without reporting additional local overrides. The badge component `1:935` is remote/read-only.
+A separate local probe confirmed equal-to-default text stays overridden after a component edit.
+This is why the untouched sibling labels remain `Badge` in the editing test.
diff --git a/packages/fig/tests/instance-overrides/fixtures/accordion-instance-paths.json b/packages/fig/tests/instance-overrides/fixtures/accordion-instance-paths.json
new file mode 100644
index 000000000..48b5b32a9
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/fixtures/accordion-instance-paths.json
@@ -0,0 +1,858 @@
+[
+ {
+ "guid": { "sessionID": 7, "localID": 250 },
+ "type": "FRAME",
+ "name": "AccordionItem",
+ "isStateGroup": true
+ },
+ {
+ "guid": {
+ "sessionID": 4,
+ "localID": 482
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "position": "!"
+ },
+ "type": "FRAME",
+ "name": "H3 AccordionTrigger",
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "stackMode": "VERTICAL"
+ },
+ {
+ "guid": {
+ "sessionID": 4,
+ "localID": 483
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 91
+ },
+ "position": "#"
+ },
+ "type": "TEXT",
+ "name": "Text",
+ "textData": {
+ "characters": "Is it accessible?"
+ },
+ "fontSize": 16,
+ "size": {
+ "x": 424,
+ "y": 24
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 16
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 91
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 482
+ },
+ "position": "!O"
+ },
+ "type": "FRAME",
+ "name": "Button",
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": -0.000030517578125,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "stackMode": "HORIZONTAL",
+ "stackPrimarySizing": "FIXED",
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 94,
+ "localID": 5467
+ },
+ "position": "I=OOOOOOOOOOOOOOOOOOOP#}}}}}}}f"
+ },
+ "type": "SYMBOL",
+ "name": "Chevron Down",
+ "size": {
+ "x": 24,
+ "y": 24
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 484,
+ "m10": 0,
+ "m11": 1,
+ "m12": 164
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 95
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 91
+ },
+ "position": "%"
+ },
+ "type": "INSTANCE",
+ "name": "Chevron Down",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 93
+ }
+ ]
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 94
+ }
+ ]
+ }
+ }
+ ]
+ },
+ "size": {
+ "x": 16,
+ "y": 16
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 424,
+ "m10": 0,
+ "m11": 1,
+ "m12": 20
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 250
+ },
+ "position": "!"
+ },
+ "type": "SYMBOL",
+ "name": "State=Closed",
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 20,
+ "m10": 0,
+ "m11": 1,
+ "m12": 20
+ },
+ "stackMode": "VERTICAL"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 163
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "position": "%"
+ },
+ "type": "INSTANCE",
+ "name": "AccordionItem",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ }
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "stackMode": "VERTICAL"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 169
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "position": "&"
+ },
+ "type": "INSTANCE",
+ "name": "AccordionItem",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "textData": {
+ "characters": "Is it styled?"
+ }
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 56
+ },
+ "stackMode": "VERTICAL"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 175
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "position": "'"
+ },
+ "type": "INSTANCE",
+ "name": "AccordionItem",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "textData": {
+ "characters": "Is it animated?"
+ }
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 112
+ },
+ "stackMode": "VERTICAL"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 428
+ },
+ "position": "&@#"
+ },
+ "type": "SYMBOL",
+ "name": "Accordion",
+ "size": {
+ "x": 440,
+ "y": 168
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 690,
+ "m10": 0,
+ "m11": 1,
+ "m12": 254
+ },
+ "stackMode": "VERTICAL",
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 212
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "position": "\""
+ },
+ "type": "FRAME",
+ "name": "Div AccordionContent",
+ "size": {
+ "x": 443.79998779296875,
+ "y": 36
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 56
+ },
+ "stackMode": "VERTICAL"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 213
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 212
+ },
+ "position": "!O"
+ },
+ "type": "FRAME",
+ "name": "Div",
+ "size": {
+ "x": 443.800048828125,
+ "y": 36
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": -0.000030517578125,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "stackMode": "HORIZONTAL",
+ "stackPrimarySizing": "FIXED",
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 214
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 213
+ },
+ "position": "#"
+ },
+ "type": "TEXT",
+ "name": "Yes. It adheres to the WAI-ARIA design pattern.",
+ "textData": {
+ "characters": "Yes. It adheres to the WAI-ARIA design pattern."
+ },
+ "fontSize": 16,
+ "size": {
+ "x": 443.800048828125,
+ "y": 20
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 250
+ },
+ "position": "\""
+ },
+ "type": "SYMBOL",
+ "name": "State=Open",
+ "size": {
+ "x": 440,
+ "y": 92
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 20,
+ "m10": 0,
+ "m11": 1,
+ "m12": 96
+ },
+ "stackMode": "VERTICAL"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 252
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "position": "!"
+ },
+ "type": "FRAME",
+ "name": "H3",
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "stackMode": "VERTICAL"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 253
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 252
+ },
+ "position": "!O"
+ },
+ "type": "FRAME",
+ "name": "Button",
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": -0.000030517578125,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "stackMode": "HORIZONTAL",
+ "stackPrimarySizing": "FIXED",
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 254
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 253
+ },
+ "position": "#"
+ },
+ "type": "TEXT",
+ "name": "Text",
+ "textData": {
+ "characters": "Is it accessible?"
+ },
+ "fontSize": 16,
+ "size": {
+ "x": 424,
+ "y": 24
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 16
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 255
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 253
+ },
+ "position": "%"
+ },
+ "type": "INSTANCE",
+ "name": "Chevron Down",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 94
+ }
+ ]
+ }
+ }
+ ]
+ },
+ "size": {
+ "x": 16,
+ "y": 16
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 424,
+ "m10": 0,
+ "m11": 1,
+ "m12": 20
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 256
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "position": "\""
+ },
+ "type": "FRAME",
+ "name": "Div",
+ "size": {
+ "x": 440,
+ "y": 36
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 56
+ },
+ "stackMode": "VERTICAL"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 257
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 256
+ },
+ "position": "!O"
+ },
+ "type": "FRAME",
+ "name": "Div",
+ "size": {
+ "x": 440,
+ "y": 36
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": -0.000030517578125,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "stackMode": "HORIZONTAL",
+ "stackPrimarySizing": "FIXED",
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 258
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 257
+ },
+ "position": "#"
+ },
+ "type": "TEXT",
+ "name": "Text",
+ "textData": {
+ "characters": "Yes. It adheres to the WAI-ARIA design pattern."
+ },
+ "fontSize": 14,
+ "size": {
+ "x": 440,
+ "y": 20
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 283
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 408
+ },
+ "position": "!"
+ },
+ "type": "INSTANCE",
+ "name": "Accordion",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ }
+ ]
+ },
+ "overriddenSymbolID": {
+ "sessionID": 7,
+ "localID": 251
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 254
+ }
+ ]
+ },
+ "fontSize": 16
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 258
+ }
+ ]
+ },
+ "fontSize": 14
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 169
+ },
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "fontSize": 16
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 175
+ },
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "fontSize": 16
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 204
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 100,
+ "m10": 0,
+ "m11": 1,
+ "m12": 100
+ },
+ "stackMode": "VERTICAL",
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 94,
+ "localID": 5438
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "position": "\""
+ },
+ "type": "VECTOR",
+ "name": "Icon",
+ "size": {
+ "x": 14,
+ "y": 8
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 5,
+ "m10": 0,
+ "m11": 1,
+ "m12": 8
+ }
+ }
+]
diff --git a/packages/fig/tests/instance-overrides/fixtures/accordion-source-closure.json b/packages/fig/tests/instance-overrides/fixtures/accordion-source-closure.json
new file mode 100644
index 000000000..3594810e7
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/fixtures/accordion-source-closure.json
@@ -0,0 +1,6094 @@
+[
+ {
+ "guid": {
+ "sessionID": 4,
+ "localID": 482
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "position": "!"
+ },
+ "type": "FRAME",
+ "name": "H3 AccordionTrigger",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "stackMode": "VERTICAL",
+ "stackChildAlignSelf": "STRETCH",
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"button\",\"attr\":{\"id\":\"radix-:r4:\"}}",
+ "key": "f2w-data"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728858416,
+ "createdAt": 1725829928
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 4,
+ "localID": 483
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 91
+ },
+ "position": "#"
+ },
+ "type": "TEXT",
+ "name": "Text",
+ "styleIdForText": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 5
+ }
+ },
+ "fontSize": 16,
+ "textAlignVertical": "CENTER",
+ "lineHeight": {
+ "value": 24,
+ "units": "PIXELS"
+ },
+ "fontName": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": "Geist-Regular"
+ },
+ "textData": {
+ "characters": "Is it accessible?",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ },
+ "derivedTextData": {
+ "layoutSize": {
+ "x": 424,
+ "y": 24
+ },
+ "baselines": [
+ {
+ "position": {
+ "x": 0,
+ "y": 17.600000381469727
+ },
+ "width": 117.28125,
+ "lineY": 3.814697322468419e-7,
+ "lineHeight": 24,
+ "lineAscent": 14,
+ "firstCharacter": 0,
+ "endCharacter": 17
+ }
+ ],
+ "glyphs": [
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 0,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 0,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 4.3125,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 1,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 12.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 2,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 22,
+ "position": {
+ "x": 16.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 3,
+ "advance": 0.24400001764297485,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 20.0625,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 4,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 26.375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 5,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 24,
+ "position": {
+ "x": 30.375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 6,
+ "advance": 0.5700000524520874,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 25,
+ "position": {
+ "x": 39.34375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 7,
+ "advance": 0.5520000457763672,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 25,
+ "position": {
+ "x": 48.09375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 8,
+ "advance": 0.5520000457763672,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 56.84375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 9,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 65.84375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 10,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 74.25,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 11,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 22,
+ "position": {
+ "x": 82.421875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 12,
+ "advance": 0.24400001764297485,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 27,
+ "position": {
+ "x": 85.921875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 13,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 28,
+ "position": {
+ "x": 95.40625,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 14,
+ "advance": 0.2840000092983246,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 99.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 15,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 29,
+ "position": {
+ "x": 108.234375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 16,
+ "advance": 0.5649999976158142,
+ "rotation": 0
+ }
+ ],
+ "fontMetaData": [
+ {
+ "key": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": ""
+ },
+ "fontLineHeight": 1.2400000095367432,
+ "fontDigest": {
+ "0": 154,
+ "1": 83,
+ "2": 21,
+ "3": 9,
+ "4": 228,
+ "5": 231,
+ "6": 104,
+ "7": 233,
+ "8": 16,
+ "9": 45,
+ "10": 17,
+ "11": 245,
+ "12": 215,
+ "13": 210,
+ "14": 147,
+ "15": 227,
+ "16": 240,
+ "17": 77,
+ "18": 156,
+ "19": 100
+ },
+ "fontStyle": "NORMAL",
+ "fontWeight": 400
+ }
+ ],
+ "truncationStartIndex": -1,
+ "truncatedHeight": -1,
+ "logicalIndexToCharacterOffsetMap": [
+ 0, 4.3125, 12.796875, 16.796875, 20.0625, 26.375, 30.375, 39.34375, 48.09375, 56.84375,
+ 65.84375, 74.25, 82.421875, 85.921875, 95.40625, 99.796875, 108.234375
+ ],
+ "derivedLines": [
+ {
+ "directionality": "LTR"
+ }
+ ]
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "textUserLayoutVersion": 4,
+ "hyperlink": {},
+ "fontVariations": [],
+ "textBidiVersion": 1,
+ "emojiImageSet": "APPLE",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 424,
+ "y": 24
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 16
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "OUTSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.035100001841783524,
+ "g": 0.035100001841783524,
+ "b": 0.042899999767541885,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 57
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "stackChildPrimaryGrow": 1,
+ "autoRename": false,
+ "textTracking": 0,
+ "textAutoResize": "HEIGHT",
+ "variableConsumptionMap": {
+ "entries": []
+ },
+ "parameterConsumptionMap": {
+ "entries": []
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 91
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 482
+ },
+ "position": "!O"
+ },
+ "type": "FRAME",
+ "name": "Button",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": -0.000030517578125,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 307,
+ "stackVerticalPadding": 16,
+ "stackPrimarySizing": "FIXED",
+ "stackPrimaryAlignItems": "SPACE_BETWEEN",
+ "stackCounterAlignItems": "CENTER",
+ "stackPaddingBottom": 16,
+ "stackChildAlignSelf": "STRETCH",
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE",
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 55
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_TOP"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 55
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_BOTTOM"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 55
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_TOP"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 55
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_BOTTOM"
+ }
+ ]
+ },
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728858416,
+ "createdAt": 1725829928
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 94,
+ "localID": 5467
+ },
+ "position": "I=OOOOOOOOOOOOOOOOOOOP#}}}}}}}f"
+ },
+ "type": "SYMBOL",
+ "name": "Chevron Down",
+ "userFacingVersion": "184:887",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "184:887",
+ "sectionStatusInfo": {
+ "status": "NONE",
+ "lastUpdateUnixTimestamp": 1725828300,
+ "prevStatus": "NONE"
+ },
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 24,
+ "y": 24
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 484,
+ "m10": 0,
+ "m11": 1,
+ "m12": 164
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL"
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 35,
+ "styleID": 0
+ }
+ ],
+ "frameMaskDisabled": false,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728562470,
+ "createdAt": 1725828300
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 95
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 91
+ },
+ "position": "%"
+ },
+ "type": "INSTANCE",
+ "name": "Chevron Down",
+ "userFacingVersion": "7:0",
+ "componentPropRefs": [
+ {
+ "defID": {
+ "sessionID": 206,
+ "localID": 1
+ },
+ "componentPropNodeField": "OVERRIDDEN_SYMBOL_ID"
+ }
+ ],
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 93
+ }
+ ]
+ },
+ "strokePaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.035100001841783524,
+ "g": 0.035100001841783524,
+ "b": 0.042899999767541885,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 57
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 94
+ }
+ ]
+ },
+ "size": {
+ "x": 16,
+ "y": 16
+ },
+ "proportionsConstrained": true
+ }
+ ],
+ "uniformScaleFactor": 1
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 94,
+ "localID": 5438
+ }
+ ]
+ },
+ "size": {
+ "x": 9.333333969116211,
+ "y": 5.333333492279053
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 3.3333332538604736,
+ "m10": 0,
+ "m11": 1,
+ "m12": 5.333333492279053
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "ODD",
+ "commandsBlob": 36,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "propsAreBubbled": true,
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 16,
+ "y": 16
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 424,
+ "m10": 0,
+ "m11": 1,
+ "m12": 20
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL"
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 37,
+ "styleID": 0
+ }
+ ],
+ "proportionsConstrained": true,
+ "frameMaskDisabled": false,
+ "derivedSymbolDataLayoutVersion": 1,
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "propRefValue": {
+ "defId": {
+ "sessionID": 206,
+ "localID": 1
+ }
+ }
+ },
+ "dataType": "PROP_REF",
+ "resolvedDataType": "SYMBOL_ID"
+ },
+ "variableField": "OVERRIDDEN_SYMBOL_ID"
+ }
+ ]
+ },
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1725830095,
+ "createdAt": 1725829928
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 250
+ },
+ "position": "!"
+ },
+ "type": "SYMBOL",
+ "name": "State=Closed",
+ "userFacingVersion": "206:15",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "206:15",
+ "componentPropDefs": [
+ {
+ "id": {
+ "sessionID": 206,
+ "localID": 1
+ },
+ "parentPropDefId": {
+ "sessionID": 206,
+ "localID": 0
+ }
+ }
+ ],
+ "variantPropSpecs": [
+ {
+ "propDefId": {
+ "sessionID": 3479705717,
+ "localID": 100804006
+ },
+ "value": "Closed"
+ }
+ ],
+ "sectionStatusInfo": {
+ "status": "NONE",
+ "lastUpdateUnixTimestamp": 1725829928,
+ "prevStatus": "NONE"
+ },
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 20,
+ "m10": 0,
+ "m11": 1,
+ "m12": 20
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "strokePaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.8941176533699036,
+ "g": 0.8941176533699036,
+ "b": 0.9058823585510254,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 72
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 38,
+ "styleID": 0
+ }
+ ],
+ "strokeGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 39,
+ "styleID": 0
+ }
+ ],
+ "borderBottomWeight": 1,
+ "borderStrokeWeightsIndependent": true,
+ "horizontalConstraint": "STRETCH",
+ "stackMode": "VERTICAL",
+ "prototypeInteractions": [
+ {
+ "id": {
+ "sessionID": 11,
+ "localID": 87
+ },
+ "event": {
+ "interactionType": "ON_CLICK"
+ },
+ "actions": [
+ {
+ "transitionNodeID": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "transitionType": "SMART_ANIMATE",
+ "transitionDuration": 0.30000001192092896,
+ "easingType": "OUT_CUBIC",
+ "connectionType": "INTERNAL_NODE",
+ "navigationType": "SWAP_STATE",
+ "easingFunction": [0, 0, 0.5799999833106995, 1],
+ "transitionResetVideoPosition": false
+ }
+ ],
+ "isDeleted": false,
+ "stateManagementVersion": 1
+ }
+ ],
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"div\"}",
+ "key": "f2w-data"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728858544,
+ "createdAt": 1725829928
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 163
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "position": "%"
+ },
+ "type": "INSTANCE",
+ "name": "AccordionItem",
+ "userFacingVersion": "7:2",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "size": {
+ "x": 424,
+ "y": 24
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 91
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 56
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 95
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 37,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 95
+ },
+ {
+ "sessionID": 94,
+ "localID": 5438
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "ODD",
+ "commandsBlob": 36,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 213
+ }
+ ]
+ },
+ "size": {
+ "x": 443.800048828125,
+ "y": 36
+ }
+ }
+ ],
+ "propsAreBubbled": true,
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "strokePaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.8941176533699036,
+ "g": 0.8941176533699036,
+ "b": 0.9058823585510254,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 72
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 38,
+ "styleID": 0
+ }
+ ],
+ "strokeGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 39,
+ "styleID": 0
+ }
+ ],
+ "borderBottomWeight": 1,
+ "borderStrokeWeightsIndependent": true,
+ "stackMode": "VERTICAL",
+ "prototypeInteractions": [
+ {
+ "id": {
+ "sessionID": 11,
+ "localID": 87
+ },
+ "event": {
+ "interactionType": "ON_CLICK"
+ },
+ "actions": [
+ {
+ "transitionNodeID": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "transitionType": "SMART_ANIMATE",
+ "transitionDuration": 0.30000001192092896,
+ "easingType": "OUT_CUBIC",
+ "connectionType": "INTERNAL_NODE",
+ "navigationType": "SWAP_STATE",
+ "easingFunction": [0, 0, 0.5799999833106995, 1],
+ "transitionResetVideoPosition": false
+ }
+ ],
+ "isDeleted": false,
+ "stateManagementVersion": 1
+ }
+ ],
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"div\"}",
+ "key": "f2w-data"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 1,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728858569,
+ "createdAt": 1725829969
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 169
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "position": "&"
+ },
+ "type": "INSTANCE",
+ "name": "AccordionItem",
+ "userFacingVersion": "7:2",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "textData": {
+ "characters": "Is it styled?",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ },
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "derivedTextData": {
+ "layoutSize": {
+ "x": 424,
+ "y": 24
+ },
+ "baselines": [
+ {
+ "position": {
+ "x": 0,
+ "y": 17.600000381469727
+ },
+ "width": 85.28125,
+ "lineY": 3.814697322468419e-7,
+ "lineHeight": 24,
+ "lineAscent": 14,
+ "firstCharacter": 0,
+ "endCharacter": 13
+ }
+ ],
+ "glyphs": [
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 0,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 0,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 4.3125,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 1,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 12.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 2,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 22,
+ "position": {
+ "x": 16.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 3,
+ "advance": 0.24400001764297485,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 20.0625,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 4,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 26.375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 5,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 30.375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 6,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 38.375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 7,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 40,
+ "position": {
+ "x": 44.6875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 8,
+ "advance": 0.5370000004768372,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 28,
+ "position": {
+ "x": 53.28125,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 9,
+ "advance": 0.2840000092983246,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 57.671875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 10,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 41,
+ "position": {
+ "x": 66.671875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 11,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 29,
+ "position": {
+ "x": 76.234375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 12,
+ "advance": 0.5649999976158142,
+ "rotation": 0
+ }
+ ],
+ "fontMetaData": [
+ {
+ "key": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": ""
+ },
+ "fontLineHeight": 1.2400000095367432,
+ "fontDigest": {
+ "0": 154,
+ "1": 83,
+ "2": 21,
+ "3": 9,
+ "4": 228,
+ "5": 231,
+ "6": 104,
+ "7": 233,
+ "8": 16,
+ "9": 45,
+ "10": 17,
+ "11": 245,
+ "12": 215,
+ "13": 210,
+ "14": 147,
+ "15": 227,
+ "16": 240,
+ "17": 77,
+ "18": 156,
+ "19": 100
+ },
+ "fontStyle": "NORMAL",
+ "fontWeight": 400
+ }
+ ],
+ "truncationStartIndex": -1,
+ "truncatedHeight": -1,
+ "logicalIndexToCharacterOffsetMap": [
+ 0, 4.3125, 12.796875, 16.796875, 20.0625, 26.375, 30.375, 38.375, 44.6875, 53.28125,
+ 57.671875, 66.671875, 76.234375
+ ],
+ "derivedLines": [
+ {
+ "directionality": "LTR"
+ }
+ ]
+ },
+ "size": {
+ "x": 424,
+ "y": 24
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 91
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 56
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 95
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 37,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 95
+ },
+ {
+ "sessionID": 94,
+ "localID": 5438
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "ODD",
+ "commandsBlob": 36,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 213
+ }
+ ]
+ },
+ "size": {
+ "x": 443.800048828125,
+ "y": 36
+ }
+ }
+ ],
+ "propsAreBubbled": true,
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 56
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "strokePaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.8941176533699036,
+ "g": 0.8941176533699036,
+ "b": 0.9058823585510254,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 72
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 38,
+ "styleID": 0
+ }
+ ],
+ "strokeGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 39,
+ "styleID": 0
+ }
+ ],
+ "borderBottomWeight": 1,
+ "borderStrokeWeightsIndependent": true,
+ "stackMode": "VERTICAL",
+ "prototypeInteractions": [
+ {
+ "id": {
+ "sessionID": 11,
+ "localID": 87
+ },
+ "event": {
+ "interactionType": "ON_CLICK"
+ },
+ "actions": [
+ {
+ "transitionNodeID": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "transitionType": "SMART_ANIMATE",
+ "transitionDuration": 0.30000001192092896,
+ "easingType": "OUT_CUBIC",
+ "connectionType": "INTERNAL_NODE",
+ "navigationType": "SWAP_STATE",
+ "easingFunction": [0, 0, 0.5799999833106995, 1],
+ "transitionResetVideoPosition": false
+ }
+ ],
+ "isDeleted": false,
+ "stateManagementVersion": 1
+ }
+ ],
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"div\"}",
+ "key": "f2w-data"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 1,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728858569,
+ "createdAt": 1725829969
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 175
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "position": "'"
+ },
+ "type": "INSTANCE",
+ "name": "AccordionItem",
+ "userFacingVersion": "7:2",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "textData": {
+ "characters": "Is it animated?",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ },
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "derivedTextData": {
+ "layoutSize": {
+ "x": 424,
+ "y": 24
+ },
+ "baselines": [
+ {
+ "position": {
+ "x": 0,
+ "y": 17.600000381469727
+ },
+ "width": 108.28125,
+ "lineY": 3.814697322468419e-7,
+ "lineHeight": 24,
+ "lineAscent": 14,
+ "firstCharacter": 0,
+ "endCharacter": 15
+ }
+ ],
+ "glyphs": [
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 0,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 0,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 4.3125,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 1,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 12.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 2,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 22,
+ "position": {
+ "x": 16.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 3,
+ "advance": 0.24400001764297485,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 20.0625,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 4,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 26.375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 5,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 24,
+ "position": {
+ "x": 30.375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 6,
+ "advance": 0.5700000524520874,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 42,
+ "position": {
+ "x": 39.421875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 7,
+ "advance": 0.581000030040741,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 22,
+ "position": {
+ "x": 48.71875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 8,
+ "advance": 0.24400001764297485,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 43,
+ "position": {
+ "x": 52.390625,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 9,
+ "advance": 0.8770000338554382,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 24,
+ "position": {
+ "x": 66.265625,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 10,
+ "advance": 0.5700000524520874,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 74.59375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 11,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 80.671875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 12,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 41,
+ "position": {
+ "x": 89.671875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 13,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 29,
+ "position": {
+ "x": 99.234375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 14,
+ "advance": 0.5649999976158142,
+ "rotation": 0
+ }
+ ],
+ "fontMetaData": [
+ {
+ "key": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": ""
+ },
+ "fontLineHeight": 1.2400000095367432,
+ "fontDigest": {
+ "0": 154,
+ "1": 83,
+ "2": 21,
+ "3": 9,
+ "4": 228,
+ "5": 231,
+ "6": 104,
+ "7": 233,
+ "8": 16,
+ "9": 45,
+ "10": 17,
+ "11": 245,
+ "12": 215,
+ "13": 210,
+ "14": 147,
+ "15": 227,
+ "16": 240,
+ "17": 77,
+ "18": 156,
+ "19": 100
+ },
+ "fontStyle": "NORMAL",
+ "fontWeight": 400
+ }
+ ],
+ "truncationStartIndex": -1,
+ "truncatedHeight": -1,
+ "logicalIndexToCharacterOffsetMap": [
+ 0, 4.3125, 12.796875, 16.796875, 20.0625, 26.375, 30.375, 39.421875, 48.71875,
+ 52.390625, 66.265625, 74.59375, 80.671875, 89.671875, 99.234375
+ ],
+ "derivedLines": [
+ {
+ "directionality": "LTR"
+ }
+ ]
+ },
+ "size": {
+ "x": 424,
+ "y": 24
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 91
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 56
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 95
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 37,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 95
+ },
+ {
+ "sessionID": 94,
+ "localID": 5438
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "ODD",
+ "commandsBlob": 36,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 213
+ }
+ ]
+ },
+ "size": {
+ "x": 443.800048828125,
+ "y": 36
+ }
+ }
+ ],
+ "propsAreBubbled": true,
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 112
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "strokePaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.8941176533699036,
+ "g": 0.8941176533699036,
+ "b": 0.9058823585510254,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 72
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 38,
+ "styleID": 0
+ }
+ ],
+ "strokeGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 39,
+ "styleID": 0
+ }
+ ],
+ "borderBottomWeight": 1,
+ "borderStrokeWeightsIndependent": true,
+ "stackMode": "VERTICAL",
+ "prototypeInteractions": [
+ {
+ "id": {
+ "sessionID": 11,
+ "localID": 87
+ },
+ "event": {
+ "interactionType": "ON_CLICK"
+ },
+ "actions": [
+ {
+ "transitionNodeID": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "transitionType": "SMART_ANIMATE",
+ "transitionDuration": 0.30000001192092896,
+ "easingType": "OUT_CUBIC",
+ "connectionType": "INTERNAL_NODE",
+ "navigationType": "SWAP_STATE",
+ "easingFunction": [0, 0, 0.5799999833106995, 1],
+ "transitionResetVideoPosition": false
+ }
+ ],
+ "isDeleted": false,
+ "stateManagementVersion": 1
+ }
+ ],
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"div\"}",
+ "key": "f2w-data"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 1,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728858569,
+ "createdAt": 1725829969
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 428
+ },
+ "position": "&@#"
+ },
+ "type": "SYMBOL",
+ "name": "Accordion",
+ "userFacingVersion": "206:352",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "206:352",
+ "sectionStatusInfo": {
+ "status": "NONE",
+ "lastUpdateUnixTimestamp": 1725829969,
+ "prevStatus": "NONE"
+ },
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 168
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 690,
+ "m10": 0,
+ "m11": 1,
+ "m12": 254
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "horizontalConstraint": "CENTER",
+ "stackMode": "VERTICAL",
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"div\"}",
+ "key": "f2w-data"
+ }
+ ],
+ "verticalConstraint": "CENTER",
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE",
+ "symbolLinks": [
+ {
+ "uri": "https://ui.shadcn.com/docs/components/accordion"
+ }
+ ],
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728858575,
+ "createdAt": 1725829969
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 212
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "position": "\""
+ },
+ "type": "FRAME",
+ "name": "Div AccordionContent",
+ "visible": false,
+ "opacity": 1,
+ "size": {
+ "x": 443.79998779296875,
+ "y": 36
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 56
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "stackMode": "VERTICAL",
+ "stackChildAlignSelf": "STRETCH",
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"button\",\"attr\":{\"id\":\"radix-:r4:\"}}",
+ "key": "f2w-data"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1725830448,
+ "createdAt": 1725830352
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 213
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 212
+ },
+ "position": "!O"
+ },
+ "type": "FRAME",
+ "name": "Div",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 443.800048828125,
+ "y": 36
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": -0.000030517578125,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 307,
+ "stackPrimarySizing": "FIXED",
+ "stackPrimaryAlignItems": "SPACE_BETWEEN",
+ "stackCounterAlignItems": "CENTER",
+ "stackPaddingBottom": 16,
+ "stackChildAlignSelf": "STRETCH",
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE",
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 64
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_BOTTOM"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 64
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_BOTTOM"
+ }
+ ]
+ },
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1725830416,
+ "createdAt": 1725830352
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 214
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 213
+ },
+ "position": "#"
+ },
+ "type": "TEXT",
+ "name": "Yes. It adheres to the WAI-ARIA design pattern.",
+ "styleIdForText": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 100
+ }
+ },
+ "fontSize": 16,
+ "textAlignVertical": "CENTER",
+ "lineHeight": {
+ "value": 24,
+ "units": "PIXELS"
+ },
+ "fontName": {
+ "family": "Geist",
+ "style": "Medium",
+ "postscript": "Geist-Medium"
+ },
+ "textData": {
+ "characters": "Yes. It adheres to the WAI-ARIA design pattern.",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ },
+ "derivedTextData": {
+ "layoutSize": {
+ "x": 443.800048828125,
+ "y": 20
+ },
+ "baselines": [
+ {
+ "position": {
+ "x": 0,
+ "y": 14.899999618530273
+ },
+ "width": 301.423828125,
+ "lineY": -3.814697322468419e-7,
+ "lineHeight": 20,
+ "lineAscent": 12,
+ "firstCharacter": 0,
+ "endCharacter": 47
+ }
+ ],
+ "glyphs": [
+ {
+ "commandsBlob": 44,
+ "position": {
+ "x": 0,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 0,
+ "advance": 0.6300000548362732,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 8.12109375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 1,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 15.99609375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 2,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 45,
+ "position": {
+ "x": 23.419921875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 3,
+ "advance": 0.2070000171661377,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 26.318359375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 4,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 29.818359375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 5,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 33.03125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 6,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 38.5546875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 7,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 24,
+ "position": {
+ "x": 42.0546875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 8,
+ "advance": 0.5700000524520874,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 41,
+ "position": {
+ "x": 49.90234375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 9,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 46,
+ "position": {
+ "x": 57.9140625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 10,
+ "advance": 0.581000030040741,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 65.84375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 11,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 47,
+ "position": {
+ "x": 73.71875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 12,
+ "advance": 0.38200002908706665,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 78.640625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 13,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 86.515625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 14,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 93.939453125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 15,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 97.439453125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 16,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 48,
+ "position": {
+ "x": 102.7578125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 17,
+ "advance": 0.5790000557899475,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 110.865234375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 18,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 114.365234375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 19,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 46,
+ "position": {
+ "x": 119.888671875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 20,
+ "advance": 0.581000030040741,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 127.818359375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 21,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 135.76171875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 22,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 49,
+ "position": {
+ "x": 139.26171875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 23,
+ "advance": 0.9110000729560852,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 50,
+ "position": {
+ "x": 151.033203125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 24,
+ "advance": 0.6700000166893005,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 160.412109375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 25,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 51,
+ "position": {
+ "x": 164.185546875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 26,
+ "advance": 0.42500001192092896,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 50,
+ "position": {
+ "x": 170.1328125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 27,
+ "advance": 0.6700000166893005,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 30,
+ "position": {
+ "x": 179.51171875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 28,
+ "advance": 0.6720000505447388,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 188.91796875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 29,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 50,
+ "position": {
+ "x": 192.69140625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 30,
+ "advance": 0.6700000166893005,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 202.0703125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 31,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 41,
+ "position": {
+ "x": 205.5703125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 32,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 213.9375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 33,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 221.8125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 34,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 22,
+ "position": {
+ "x": 228.962890625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 35,
+ "advance": 0.24400001764297485,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 31,
+ "position": {
+ "x": 232.380859375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 36,
+ "advance": 0.597000002861023,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 42,
+ "position": {
+ "x": 240.734375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 37,
+ "advance": 0.581000030040741,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 248.869140625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 38,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 52,
+ "position": {
+ "x": 252.369140625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 39,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 24,
+ "position": {
+ "x": 260.736328125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 40,
+ "advance": 0.5700000524520874,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 53,
+ "position": {
+ "x": 268.0234375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 41,
+ "advance": 0.6970000267028809,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 277.580078125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 43,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 47,
+ "position": {
+ "x": 285.455078125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 44,
+ "advance": 0.38200002908706665,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 42,
+ "position": {
+ "x": 290.390625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 45,
+ "advance": 0.581000030040741,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 45,
+ "position": {
+ "x": 298.525390625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 46,
+ "advance": 0.2070000171661377,
+ "rotation": 0
+ }
+ ],
+ "fontMetaData": [
+ {
+ "key": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": ""
+ },
+ "fontLineHeight": 1.2400000095367432,
+ "fontDigest": {
+ "0": 154,
+ "1": 83,
+ "2": 21,
+ "3": 9,
+ "4": 228,
+ "5": 231,
+ "6": 104,
+ "7": 233,
+ "8": 16,
+ "9": 45,
+ "10": 17,
+ "11": 245,
+ "12": 215,
+ "13": 210,
+ "14": 147,
+ "15": 227,
+ "16": 240,
+ "17": 77,
+ "18": 156,
+ "19": 100
+ },
+ "fontStyle": "NORMAL",
+ "fontWeight": 400
+ }
+ ],
+ "truncationStartIndex": -1,
+ "truncatedHeight": -1,
+ "logicalIndexToCharacterOffsetMap": [
+ 0, 8.12109375, 15.99609375, 23.419921875, 26.318359375, 29.818359375, 33.03125, 38.5546875,
+ 42.0546875, 49.90234375, 57.9140625, 65.84375, 73.71875, 78.640625, 86.515625, 93.939453125,
+ 97.439453125, 102.7578125, 110.865234375, 114.365234375, 119.888671875, 127.818359375,
+ 135.76171875, 139.26171875, 151.033203125, 160.412109375, 164.185546875, 170.1328125,
+ 179.51171875, 188.91796875, 192.69140625, 202.0703125, 205.5703125, 213.9375, 221.8125,
+ 228.962890625, 232.380859375, 240.734375, 248.869140625, 252.369140625, 260.736328125,
+ 268.0234375, 272.8017578125, 277.580078125, 285.455078125, 290.390625, 298.525390625
+ ],
+ "derivedLines": [
+ {
+ "directionality": "LTR"
+ }
+ ]
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "textUserLayoutVersion": 4,
+ "hyperlink": {},
+ "fontVariations": [],
+ "textBidiVersion": 1,
+ "emojiImageSet": "APPLE",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 443.800048828125,
+ "y": 20
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "OUTSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.035100001841783524,
+ "g": 0.035100001841783524,
+ "b": 0.042899999767541885,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 57
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "stackChildPrimaryGrow": 1,
+ "autoRename": true,
+ "textTracking": 0,
+ "textAutoResize": "HEIGHT"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 250
+ },
+ "position": "\""
+ },
+ "type": "SYMBOL",
+ "name": "State=Open",
+ "userFacingVersion": "206:16",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "206:16",
+ "componentPropDefs": [
+ {
+ "id": {
+ "sessionID": 206,
+ "localID": 2
+ },
+ "parentPropDefId": {
+ "sessionID": 206,
+ "localID": 0
+ }
+ }
+ ],
+ "variantPropSpecs": [
+ {
+ "propDefId": {
+ "sessionID": 3479705717,
+ "localID": 100804006
+ },
+ "value": "Open"
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 92
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 20,
+ "m10": 0,
+ "m11": 1,
+ "m12": 96
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "strokePaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.8941176533699036,
+ "g": 0.8941176533699036,
+ "b": 0.9058823585510254,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 72
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 56,
+ "styleID": 0
+ }
+ ],
+ "strokeGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 57,
+ "styleID": 0
+ }
+ ],
+ "borderBottomWeight": 1,
+ "borderStrokeWeightsIndependent": true,
+ "horizontalConstraint": "STRETCH",
+ "stackMode": "VERTICAL",
+ "prototypeInteractions": [
+ {
+ "id": {
+ "sessionID": 11,
+ "localID": 88
+ },
+ "event": {
+ "interactionType": "ON_CLICK"
+ },
+ "actions": [
+ {
+ "transitionNodeID": {
+ "sessionID": 7,
+ "localID": 156
+ },
+ "transitionType": "SMART_ANIMATE",
+ "transitionDuration": 0.30000001192092896,
+ "easingType": "OUT_CUBIC",
+ "connectionType": "INTERNAL_NODE",
+ "navigationType": "SWAP_STATE",
+ "easingFunction": [0, 0, 0.5799999833106995, 1]
+ }
+ ],
+ "isDeleted": false,
+ "stateManagementVersion": 1
+ }
+ ],
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"div\"}",
+ "key": "f2w-data"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1734433457,
+ "createdAt": 1725830427
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 252
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "position": "!"
+ },
+ "type": "FRAME",
+ "name": "H3",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "stackMode": "VERTICAL",
+ "stackChildAlignSelf": "STRETCH",
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"button\",\"attr\":{\"id\":\"radix-:r4:\"}}",
+ "key": "f2w-data"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1734433457,
+ "createdAt": 1725830427
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 253
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 252
+ },
+ "position": "!O"
+ },
+ "type": "FRAME",
+ "name": "Button",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 56
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": -0.000030517578125,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 307,
+ "stackVerticalPadding": 16,
+ "stackPrimarySizing": "FIXED",
+ "stackPrimaryAlignItems": "SPACE_BETWEEN",
+ "stackCounterAlignItems": "CENTER",
+ "stackPaddingBottom": 16,
+ "stackChildAlignSelf": "STRETCH",
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE",
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 55
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_TOP"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 55
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_BOTTOM"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 55
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_TOP"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 55
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_BOTTOM"
+ }
+ ]
+ },
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1734433457,
+ "createdAt": 1725830427
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 254
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 253
+ },
+ "position": "#"
+ },
+ "type": "TEXT",
+ "name": "Text",
+ "styleIdForText": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 5
+ }
+ },
+ "fontSize": 16,
+ "textAlignVertical": "CENTER",
+ "lineHeight": {
+ "value": 24,
+ "units": "PIXELS"
+ },
+ "fontName": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": "Geist-Regular"
+ },
+ "textData": {
+ "characters": "Is it accessible?",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ },
+ "derivedTextData": {
+ "layoutSize": {
+ "x": 424,
+ "y": 24
+ },
+ "baselines": [
+ {
+ "position": {
+ "x": 0,
+ "y": 17.600000381469727
+ },
+ "width": 117.28125,
+ "lineY": 3.814697322468419e-7,
+ "lineHeight": 24,
+ "lineAscent": 14,
+ "firstCharacter": 0,
+ "endCharacter": 17
+ }
+ ],
+ "glyphs": [
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 0,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 0,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 4.3125,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 1,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 12.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 2,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 22,
+ "position": {
+ "x": 16.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 3,
+ "advance": 0.24400001764297485,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 20.0625,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 4,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 26.375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 5,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 24,
+ "position": {
+ "x": 30.375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 6,
+ "advance": 0.5700000524520874,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 25,
+ "position": {
+ "x": 39.34375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 7,
+ "advance": 0.5520000457763672,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 25,
+ "position": {
+ "x": 48.09375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 8,
+ "advance": 0.5520000457763672,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 56.84375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 9,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 65.84375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 10,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 74.25,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 11,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 22,
+ "position": {
+ "x": 82.421875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 12,
+ "advance": 0.24400001764297485,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 27,
+ "position": {
+ "x": 85.921875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 13,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 28,
+ "position": {
+ "x": 95.40625,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 14,
+ "advance": 0.2840000092983246,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 99.796875,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 15,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 29,
+ "position": {
+ "x": 108.234375,
+ "y": 17.600000381469727
+ },
+ "fontSize": 16,
+ "firstCharacter": 16,
+ "advance": 0.5649999976158142,
+ "rotation": 0
+ }
+ ],
+ "fontMetaData": [
+ {
+ "key": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": ""
+ },
+ "fontLineHeight": 1.2400000095367432,
+ "fontDigest": {
+ "0": 154,
+ "1": 83,
+ "2": 21,
+ "3": 9,
+ "4": 228,
+ "5": 231,
+ "6": 104,
+ "7": 233,
+ "8": 16,
+ "9": 45,
+ "10": 17,
+ "11": 245,
+ "12": 215,
+ "13": 210,
+ "14": 147,
+ "15": 227,
+ "16": 240,
+ "17": 77,
+ "18": 156,
+ "19": 100
+ },
+ "fontStyle": "NORMAL",
+ "fontWeight": 400
+ }
+ ],
+ "truncationStartIndex": -1,
+ "truncatedHeight": -1,
+ "logicalIndexToCharacterOffsetMap": [
+ 0, 4.3125, 12.796875, 16.796875, 20.0625, 26.375, 30.375, 39.34375, 48.09375, 56.84375,
+ 65.84375, 74.25, 82.421875, 85.921875, 95.40625, 99.796875, 108.234375
+ ],
+ "derivedLines": [
+ {
+ "directionality": "LTR"
+ }
+ ]
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "textUserLayoutVersion": 4,
+ "hyperlink": {},
+ "fontVariations": [],
+ "textBidiVersion": 1,
+ "emojiImageSet": "APPLE",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 424,
+ "y": 24
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 16
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "OUTSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.035100001841783524,
+ "g": 0.035100001841783524,
+ "b": 0.042899999767541885,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 57
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "stackChildPrimaryGrow": 1,
+ "autoRename": false,
+ "textTracking": 0,
+ "textAutoResize": "HEIGHT",
+ "variableConsumptionMap": {
+ "entries": []
+ },
+ "parameterConsumptionMap": {
+ "entries": []
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 255
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 253
+ },
+ "position": "%"
+ },
+ "type": "INSTANCE",
+ "name": "Chevron Down",
+ "userFacingVersion": "7:0",
+ "componentPropRefs": [
+ {
+ "defID": {
+ "sessionID": 206,
+ "localID": 2
+ },
+ "componentPropNodeField": "OVERRIDDEN_SYMBOL_ID"
+ }
+ ],
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 94
+ }
+ ]
+ },
+ "size": {
+ "x": 16,
+ "y": 16
+ },
+ "proportionsConstrained": true
+ }
+ ],
+ "uniformScaleFactor": 1
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 94,
+ "localID": 5438
+ }
+ ]
+ },
+ "size": {
+ "x": 9.333333969116211,
+ "y": 5.333333492279053
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 3.3333332538604736,
+ "m10": 0,
+ "m11": 1,
+ "m12": 5.333333492279053
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "ODD",
+ "commandsBlob": 36,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "propsAreBubbled": true,
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 16,
+ "y": 16
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 424,
+ "m10": 0,
+ "m11": 1,
+ "m12": 20
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL"
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 37,
+ "styleID": 0
+ }
+ ],
+ "proportionsConstrained": true,
+ "frameMaskDisabled": false,
+ "derivedSymbolDataLayoutVersion": 1,
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "propRefValue": {
+ "defId": {
+ "sessionID": 206,
+ "localID": 2
+ }
+ }
+ },
+ "dataType": "PROP_REF",
+ "resolvedDataType": "SYMBOL_ID"
+ },
+ "variableField": "OVERRIDDEN_SYMBOL_ID"
+ }
+ ]
+ },
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1734433457,
+ "createdAt": 1725830427
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 256
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "position": "\""
+ },
+ "type": "FRAME",
+ "name": "Div",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 36
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 56
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "stackMode": "VERTICAL",
+ "stackChildAlignSelf": "STRETCH",
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"button\",\"attr\":{\"id\":\"radix-:r4:\"}}",
+ "key": "f2w-data"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728858423,
+ "createdAt": 1725830427
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 257
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 256
+ },
+ "position": "!O"
+ },
+ "type": "FRAME",
+ "name": "Div",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 36
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": -0.000030517578125,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 307,
+ "stackPrimarySizing": "FIXED",
+ "stackPrimaryAlignItems": "SPACE_BETWEEN",
+ "stackCounterAlignItems": "CENTER",
+ "stackPaddingBottom": 16,
+ "stackChildAlignSelf": "STRETCH",
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE",
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 64
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_BOTTOM"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 64
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_BOTTOM"
+ }
+ ]
+ },
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728858423,
+ "createdAt": 1725830427
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 258
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 257
+ },
+ "position": "#"
+ },
+ "type": "TEXT",
+ "name": "Text",
+ "styleIdForText": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 100
+ }
+ },
+ "fontSize": 14,
+ "textAlignVertical": "CENTER",
+ "lineHeight": {
+ "value": 20,
+ "units": "PIXELS"
+ },
+ "fontName": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": "Geist-Regular"
+ },
+ "textData": {
+ "characters": "Yes. It adheres to the WAI-ARIA design pattern.",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ },
+ "derivedTextData": {
+ "layoutSize": {
+ "x": 440,
+ "y": 20
+ },
+ "baselines": [
+ {
+ "position": {
+ "x": 0,
+ "y": 14.899999618530273
+ },
+ "width": 301.423828125,
+ "lineY": -3.814697322468419e-7,
+ "lineHeight": 20,
+ "lineAscent": 12,
+ "firstCharacter": 0,
+ "endCharacter": 47
+ }
+ ],
+ "glyphs": [
+ {
+ "commandsBlob": 44,
+ "position": {
+ "x": 0,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 0,
+ "advance": 0.6300000548362732,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 8.12109375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 1,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 15.99609375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 2,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 45,
+ "position": {
+ "x": 23.419921875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 3,
+ "advance": 0.2070000171661377,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 26.318359375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 4,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 29.818359375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 5,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 33.03125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 6,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 38.5546875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 7,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 24,
+ "position": {
+ "x": 42.0546875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 8,
+ "advance": 0.5700000524520874,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 41,
+ "position": {
+ "x": 49.90234375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 9,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 46,
+ "position": {
+ "x": 57.9140625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 10,
+ "advance": 0.581000030040741,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 65.84375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 11,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 47,
+ "position": {
+ "x": 73.71875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 12,
+ "advance": 0.38200002908706665,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 78.640625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 13,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 86.515625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 14,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 93.939453125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 15,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 97.439453125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 16,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 48,
+ "position": {
+ "x": 102.7578125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 17,
+ "advance": 0.5790000557899475,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 110.865234375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 18,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 23,
+ "position": {
+ "x": 114.365234375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 19,
+ "advance": 0.39500001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 46,
+ "position": {
+ "x": 119.888671875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 20,
+ "advance": 0.581000030040741,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 127.818359375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 21,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 135.76171875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 22,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 49,
+ "position": {
+ "x": 139.26171875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 23,
+ "advance": 0.9110000729560852,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 50,
+ "position": {
+ "x": 151.033203125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 24,
+ "advance": 0.6700000166893005,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 160.412109375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 25,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 51,
+ "position": {
+ "x": 164.185546875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 26,
+ "advance": 0.42500001192092896,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 50,
+ "position": {
+ "x": 170.1328125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 27,
+ "advance": 0.6700000166893005,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 30,
+ "position": {
+ "x": 179.51171875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 28,
+ "advance": 0.6720000505447388,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 19,
+ "position": {
+ "x": 188.91796875,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 29,
+ "advance": 0.27000001072883606,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 50,
+ "position": {
+ "x": 192.69140625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 30,
+ "advance": 0.6700000166893005,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 202.0703125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 31,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 41,
+ "position": {
+ "x": 205.5703125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 32,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 213.9375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 33,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 20,
+ "position": {
+ "x": 221.8125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 34,
+ "advance": 0.5300000309944153,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 22,
+ "position": {
+ "x": 228.962890625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 35,
+ "advance": 0.24400001764297485,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 31,
+ "position": {
+ "x": 232.380859375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 36,
+ "advance": 0.597000002861023,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 42,
+ "position": {
+ "x": 240.734375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 37,
+ "advance": 0.581000030040741,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 21,
+ "position": {
+ "x": 248.869140625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 38,
+ "advance": 0.25,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 52,
+ "position": {
+ "x": 252.369140625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 39,
+ "advance": 0.5980000495910645,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 24,
+ "position": {
+ "x": 260.736328125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 40,
+ "advance": 0.5700000524520874,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 53,
+ "position": {
+ "x": 268.0234375,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 41,
+ "advance": 0.6970000267028809,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 26,
+ "position": {
+ "x": 277.580078125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 43,
+ "advance": 0.5670000314712524,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 47,
+ "position": {
+ "x": 285.455078125,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 44,
+ "advance": 0.38200002908706665,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 42,
+ "position": {
+ "x": 290.390625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 45,
+ "advance": 0.581000030040741,
+ "rotation": 0
+ },
+ {
+ "commandsBlob": 45,
+ "position": {
+ "x": 298.525390625,
+ "y": 14.899999618530273
+ },
+ "fontSize": 14,
+ "firstCharacter": 46,
+ "advance": 0.2070000171661377,
+ "rotation": 0
+ }
+ ],
+ "fontMetaData": [
+ {
+ "key": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": ""
+ },
+ "fontLineHeight": 1.2400000095367432,
+ "fontDigest": {
+ "0": 154,
+ "1": 83,
+ "2": 21,
+ "3": 9,
+ "4": 228,
+ "5": 231,
+ "6": 104,
+ "7": 233,
+ "8": 16,
+ "9": 45,
+ "10": 17,
+ "11": 245,
+ "12": 215,
+ "13": 210,
+ "14": 147,
+ "15": 227,
+ "16": 240,
+ "17": 77,
+ "18": 156,
+ "19": 100
+ },
+ "fontStyle": "NORMAL",
+ "fontWeight": 400
+ }
+ ],
+ "truncationStartIndex": -1,
+ "truncatedHeight": -1,
+ "logicalIndexToCharacterOffsetMap": [
+ 0, 8.12109375, 15.99609375, 23.419921875, 26.318359375, 29.818359375, 33.03125, 38.5546875,
+ 42.0546875, 49.90234375, 57.9140625, 65.84375, 73.71875, 78.640625, 86.515625, 93.939453125,
+ 97.439453125, 102.7578125, 110.865234375, 114.365234375, 119.888671875, 127.818359375,
+ 135.76171875, 139.26171875, 151.033203125, 160.412109375, 164.185546875, 170.1328125,
+ 179.51171875, 188.91796875, 192.69140625, 202.0703125, 205.5703125, 213.9375, 221.8125,
+ 228.962890625, 232.380859375, 240.734375, 248.869140625, 252.369140625, 260.736328125,
+ 268.0234375, 272.8017578125, 277.580078125, 285.455078125, 290.390625, 298.525390625
+ ],
+ "derivedLines": [
+ {
+ "directionality": "LTR"
+ }
+ ]
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "textUserLayoutVersion": 4,
+ "hyperlink": {},
+ "fontVariations": [],
+ "textBidiVersion": 1,
+ "emojiImageSet": "APPLE",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 20
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "OUTSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.035100001841783524,
+ "g": 0.035100001841783524,
+ "b": 0.042899999767541885,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 57
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "stackChildPrimaryGrow": 1,
+ "autoRename": false,
+ "textTracking": 0,
+ "textAutoResize": "HEIGHT",
+ "variableConsumptionMap": {
+ "entries": []
+ },
+ "parameterConsumptionMap": {
+ "entries": []
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 283
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 408
+ },
+ "position": "!"
+ },
+ "type": "INSTANCE",
+ "name": "Accordion",
+ "userFacingVersion": "7:126",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 186
+ },
+ "symbolOverrides": [
+ {
+ "overriddenSymbolID": {
+ "sessionID": 7,
+ "localID": 251
+ },
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ }
+ ]
+ }
+ },
+ {
+ "styleIdForText": {
+ "guid": {
+ "sessionID": 4294967295,
+ "localID": 4294967295
+ }
+ },
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 254
+ }
+ ]
+ },
+ "fontSize": 16,
+ "lineHeight": {
+ "value": 24,
+ "units": "PIXELS"
+ },
+ "fontName": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": "Geist-Regular"
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "fontVariations": [],
+ "textTracking": 0,
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ }
+ },
+ {
+ "styleIdForText": {
+ "guid": {
+ "sessionID": 4294967295,
+ "localID": 4294967295
+ }
+ },
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 258
+ }
+ ]
+ },
+ "fontSize": 14,
+ "lineHeight": {
+ "value": 20,
+ "units": "PIXELS"
+ },
+ "fontName": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": "Geist-Regular"
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "fontVariations": [],
+ "textTracking": 0,
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 138
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 147
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "LINE_HEIGHT"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 138
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 147
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "LINE_HEIGHT"
+ }
+ ]
+ }
+ },
+ {
+ "styleIdForText": {
+ "guid": {
+ "sessionID": 4294967295,
+ "localID": 4294967295
+ }
+ },
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 169
+ },
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "fontSize": 16,
+ "lineHeight": {
+ "value": 24,
+ "units": "PIXELS"
+ },
+ "fontName": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": "Geist-Regular"
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "fontVariations": [],
+ "textTracking": 0,
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ }
+ },
+ {
+ "styleIdForText": {
+ "guid": {
+ "sessionID": 4294967295,
+ "localID": 4294967295
+ }
+ },
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 175
+ },
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "fontSize": 16,
+ "lineHeight": {
+ "value": 24,
+ "units": "PIXELS"
+ },
+ "fontName": {
+ "family": "Geist",
+ "style": "Regular",
+ "postscript": "Geist-Regular"
+ },
+ "fontVariantCommonLigatures": true,
+ "fontVariantContextualLigatures": true,
+ "letterSpacing": {
+ "value": 0,
+ "units": "PERCENT"
+ },
+ "fontVersion": "",
+ "fontVariations": [],
+ "textTracking": 0,
+ "variableConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 128
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "STRING"
+ },
+ "variableField": "FONT_FAMILY"
+ },
+ {
+ "variableData": {
+ "value": {
+ "fontStyleValue": {
+ "asFloat": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 145
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ },
+ "dataType": "FONT_STYLE",
+ "resolvedDataType": "FONT_STYLE"
+ },
+ "variableField": "FONT_STYLE"
+ },
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 136
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "FONT_SIZE"
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 92
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 56,
+ "styleID": 0
+ }
+ ],
+ "strokeGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 57,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 253
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 56
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 254
+ }
+ ]
+ },
+ "size": {
+ "x": 424,
+ "y": 24
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 255
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 37,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 255
+ },
+ {
+ "sessionID": 94,
+ "localID": 5438
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "ODD",
+ "commandsBlob": 36,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 257
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 36
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 163
+ },
+ {
+ "sessionID": 7,
+ "localID": 258
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 20
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 169
+ }
+ ]
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 92
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 38,
+ "styleID": 0
+ }
+ ],
+ "strokeGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 39,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 169
+ },
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "size": {
+ "x": 424,
+ "y": 24
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 169
+ },
+ {
+ "sessionID": 7,
+ "localID": 91
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 56
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 169
+ },
+ {
+ "sessionID": 7,
+ "localID": 95
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 37,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 169
+ },
+ {
+ "sessionID": 7,
+ "localID": 95
+ },
+ {
+ "sessionID": 94,
+ "localID": 5438
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "ODD",
+ "commandsBlob": 36,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 175
+ }
+ ]
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 148
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 38,
+ "styleID": 0
+ }
+ ],
+ "strokeGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 39,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 175
+ },
+ {
+ "sessionID": 4,
+ "localID": 483
+ }
+ ]
+ },
+ "size": {
+ "x": 424,
+ "y": 24
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 175
+ },
+ {
+ "sessionID": 7,
+ "localID": 91
+ }
+ ]
+ },
+ "size": {
+ "x": 440,
+ "y": 56
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 175
+ },
+ {
+ "sessionID": 7,
+ "localID": 95
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 37,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 175
+ },
+ {
+ "sessionID": 7,
+ "localID": 95
+ },
+ {
+ "sessionID": 94,
+ "localID": 5438
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "ODD",
+ "commandsBlob": 36,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 440,
+ "y": 204
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 100,
+ "m10": 0,
+ "m11": 1,
+ "m12": 100
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "horizontalConstraint": "CENTER",
+ "stackMode": "VERTICAL",
+ "pluginData": [
+ {
+ "pluginID": "",
+ "value": "{\"tag\":\"div\"}",
+ "key": "f2w-data"
+ }
+ ],
+ "verticalConstraint": "CENTER",
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 1,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE",
+ "symbolLinks": [
+ {
+ "uri": "https://ui.shadcn.com/docs/components/accordion"
+ }
+ ],
+ "editInfo": {
+ "userId": "369886839823206492",
+ "lastEditedAt": 1728849298,
+ "createdAt": 1725830659
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 94,
+ "localID": 5438
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "position": "\""
+ },
+ "type": "VECTOR",
+ "name": "Icon",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 14,
+ "y": 8
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 5,
+ "m10": 0,
+ "m11": 1,
+ "m12": 8
+ },
+ "strokeWeight": 2,
+ "strokeAlign": "CENTER",
+ "strokeCap": "ROUND",
+ "strokeJoin": "ROUND",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.035100001841783524,
+ "g": 0.035100001841783524,
+ "b": 0.042899999767541885,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 57
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "ODD",
+ "commandsBlob": 928,
+ "styleID": 0
+ }
+ ],
+ "horizontalConstraint": "SCALE",
+ "verticalConstraint": "SCALE",
+ "vectorData": {
+ "vectorNetworkBlob": 927,
+ "normalizedSize": {
+ "x": 14,
+ "y": 8
+ }
+ }
+ }
+]
diff --git a/packages/fig/tests/instance-overrides/fixtures/name-provenance.json b/packages/fig/tests/instance-overrides/fixtures/name-provenance.json
new file mode 100644
index 000000000..cc64ae03a
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/fixtures/name-provenance.json
@@ -0,0 +1,320 @@
+{
+ "oracle": {
+ "names": {
+ "page": "293147:1802",
+ "component": "293147:1803",
+ "instances": [
+ {
+ "id": "293147:1804",
+ "name": "Original",
+ "overrides": []
+ },
+ {
+ "id": "293147:1805",
+ "name": "Original",
+ "overrides": [
+ {
+ "id": "293147:1805",
+ "overriddenFields": ["name"]
+ }
+ ]
+ },
+ {
+ "id": "293147:1806",
+ "name": "Custom",
+ "overrides": [
+ {
+ "id": "293147:1806",
+ "overriddenFields": ["name"]
+ }
+ ]
+ }
+ ]
+ },
+ "variants": {
+ "page": "293150:1807",
+ "set": "293150:1810",
+ "components": ["293150:1808", "293150:1809", "293150:1811"],
+ "before": [
+ {
+ "id": "293150:1812",
+ "name": "Control",
+ "overrides": []
+ },
+ {
+ "id": "293150:1813",
+ "name": "Custom",
+ "overrides": [
+ {
+ "id": "293150:1813",
+ "overriddenFields": ["name"]
+ }
+ ]
+ }
+ ],
+ "variant": [
+ {
+ "id": "293150:1812",
+ "name": "Control",
+ "overrides": []
+ },
+ {
+ "id": "293150:1813",
+ "name": "Custom",
+ "overrides": [
+ {
+ "id": "293150:1813",
+ "overriddenFields": ["name"]
+ }
+ ]
+ }
+ ],
+ "unrelated": [
+ {
+ "id": "293150:1812",
+ "name": "Other",
+ "overrides": []
+ },
+ {
+ "id": "293150:1813",
+ "name": "Custom",
+ "overrides": [
+ {
+ "id": "293150:1813",
+ "overriddenFields": ["name"]
+ }
+ ]
+ }
+ ]
+ }
+ },
+ "records": [
+ {
+ "guid": {
+ "sessionID": 293147,
+ "localID": 1803
+ },
+ "type": "SYMBOL",
+ "name": "Original",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293147,
+ "localID": 1802
+ },
+ "position": "!"
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 293147,
+ "localID": 1804
+ },
+ "type": "INSTANCE",
+ "name": "Original",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293147,
+ "localID": 1802
+ },
+ "position": "\""
+ },
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 293147,
+ "localID": 1803
+ },
+ "symbolOverrides": [],
+ "uniformScaleFactor": 1
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 293147,
+ "localID": 1805
+ },
+ "type": "INSTANCE",
+ "name": "Original",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293147,
+ "localID": 1802
+ },
+ "position": "#"
+ },
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 293147,
+ "localID": 1803
+ },
+ "symbolOverrides": [
+ {
+ "name": "Original",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293147,
+ "localID": 1803
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 293147,
+ "localID": 1806
+ },
+ "type": "INSTANCE",
+ "name": "Custom",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293147,
+ "localID": 1802
+ },
+ "position": "$"
+ },
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 293147,
+ "localID": 1803
+ },
+ "symbolOverrides": [
+ {
+ "name": "Custom",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293147,
+ "localID": 1803
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1808
+ },
+ "type": "SYMBOL",
+ "name": "State=Closed",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1810
+ },
+ "position": "!"
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1809
+ },
+ "type": "SYMBOL",
+ "name": "State=Open",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1810
+ },
+ "position": "\""
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1810
+ },
+ "type": "FRAME",
+ "name": "Control",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1807
+ },
+ "position": "#"
+ },
+ "isStateGroup": true
+ },
+ {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1811
+ },
+ "type": "SYMBOL",
+ "name": "Other",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1807
+ },
+ "position": "$"
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1812
+ },
+ "type": "INSTANCE",
+ "name": "Other",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1807
+ },
+ "position": "%"
+ },
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 293150,
+ "localID": 1811
+ },
+ "symbolOverrides": [],
+ "uniformScaleFactor": 1
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1813
+ },
+ "type": "INSTANCE",
+ "name": "Custom",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293150,
+ "localID": 1807
+ },
+ "position": "&"
+ },
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 293150,
+ "localID": 1811
+ },
+ "symbolOverrides": [
+ {
+ "name": "Custom",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293150,
+ "localID": 1811
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ }
+ }
+ ]
+}
diff --git a/packages/fig/tests/instance-overrides/fixtures/saved-swap-paths.json b/packages/fig/tests/instance-overrides/fixtures/saved-swap-paths.json
new file mode 100644
index 000000000..c66297f58
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/fixtures/saved-swap-paths.json
@@ -0,0 +1,504 @@
+[
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1259
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1258
+ },
+ "position": "!"
+ },
+ "type": "SYMBOL",
+ "name": "Source",
+ "size": {
+ "x": 100,
+ "y": 40
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "opacity": 1
+ },
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1260
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1259
+ },
+ "position": "!"
+ },
+ "type": "TEXT",
+ "name": "Label",
+ "size": {
+ "x": 71,
+ "y": 15
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "opacity": 1,
+ "textData": {
+ "characters": "Source label",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1261
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1258
+ },
+ "position": "\""
+ },
+ "type": "SYMBOL",
+ "name": "Replacement",
+ "size": {
+ "x": 160,
+ "y": 64
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 240,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "opacity": 1
+ },
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1262
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1261
+ },
+ "position": "!"
+ },
+ "type": "TEXT",
+ "name": "Label",
+ "size": {
+ "x": 105,
+ "y": 15
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "opacity": 1,
+ "textData": {
+ "characters": "Replacement label",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1263
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1258
+ },
+ "position": "#"
+ },
+ "type": "INSTANCE",
+ "name": "Untouched swap",
+ "size": {
+ "x": 160,
+ "y": 64
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 150
+ },
+ "opacity": 1,
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 10965,
+ "localID": 1261
+ },
+ "symbolOverrides": [
+ {
+ "name": "Untouched swap",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 10965,
+ "localID": 1261
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1266
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1258
+ },
+ "position": "$"
+ },
+ "type": "INSTANCE",
+ "name": "Edited swap",
+ "size": {
+ "x": 120,
+ "y": 50
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 250
+ },
+ "opacity": 0.6000000238418579,
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 10965,
+ "localID": 1261
+ },
+ "symbolOverrides": [
+ {
+ "name": "Edited swap",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 10965,
+ "localID": 1261
+ }
+ ]
+ },
+ "opacity": 0.6000000238418579,
+ "size": {
+ "x": 120,
+ "y": 50
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 10965,
+ "localID": 1262
+ }
+ ]
+ },
+ "textData": {
+ "characters": "Edited label",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1269
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1258
+ },
+ "position": "%"
+ },
+ "type": "SYMBOL",
+ "name": "Host",
+ "size": {
+ "x": 100,
+ "y": 100
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 500,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "opacity": 1
+ },
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1270
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1269
+ },
+ "position": "!"
+ },
+ "type": "INSTANCE",
+ "name": "Source",
+ "size": {
+ "x": 100,
+ "y": 40
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "opacity": 1,
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 10965,
+ "localID": 1259
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 10965,
+ "localID": 1260
+ }
+ ]
+ },
+ "textData": {
+ "characters": "Inherited edit",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1272
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1258
+ },
+ "position": "&"
+ },
+ "type": "INSTANCE",
+ "name": "Nested swap",
+ "size": {
+ "x": 100,
+ "y": 100
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 350
+ },
+ "opacity": 1,
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 10965,
+ "localID": 1269
+ },
+ "symbolOverrides": [
+ {
+ "name": "Nested swap",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 10965,
+ "localID": 1269
+ }
+ ]
+ }
+ },
+ {
+ "overriddenSymbolID": {
+ "sessionID": 10965,
+ "localID": 1261
+ },
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 10965,
+ "localID": 1270
+ }
+ ]
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 10965,
+ "localID": 1270
+ },
+ {
+ "sessionID": 10965,
+ "localID": 1262
+ }
+ ]
+ },
+ "overrideLevel": 1,
+ "textData": {
+ "characters": "Inherited edit",
+ "lines": [
+ {
+ "lineType": "PLAIN",
+ "styleId": 0,
+ "indentationLevel": 0,
+ "sourceDirectionality": "AUTO",
+ "listStartOffset": 0,
+ "isFirstLineOfList": false
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1276
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 10965,
+ "localID": 1258
+ },
+ "position": "'"
+ },
+ "type": "INSTANCE",
+ "name": "Nested assignment",
+ "size": {
+ "x": 100,
+ "y": 100
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 450
+ },
+ "opacity": 1,
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 10965,
+ "localID": 1269
+ },
+ "symbolOverrides": [
+ {
+ "name": "Nested assignment",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 10965,
+ "localID": 1269
+ }
+ ]
+ }
+ },
+ {
+ "overriddenSymbolID": {
+ "sessionID": 10965,
+ "localID": 1261
+ },
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 10965,
+ "localID": 1270
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 1
+ }
+ }
+]
diff --git a/packages/fig/tests/instance-overrides/fixtures/stale-chevron-override.json b/packages/fig/tests/instance-overrides/fixtures/stale-chevron-override.json
new file mode 100644
index 000000000..a7aa0e5ba
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/fixtures/stale-chevron-override.json
@@ -0,0 +1,107 @@
+[
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 94,
+ "localID": 5467
+ },
+ "position": "I=OOOOOOOOOOOOOOOOOOOP#}}}}}}}f"
+ },
+ "type": "SYMBOL",
+ "name": "Chevron Down"
+ },
+ {
+ "guid": {
+ "sessionID": 7,
+ "localID": 95
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 91
+ },
+ "position": "%"
+ },
+ "type": "INSTANCE",
+ "name": "Chevron Down",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 93
+ }
+ ]
+ },
+ "strokePaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.035100001841783524,
+ "g": 0.035100001841783524,
+ "b": 0.042899999767541885,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "colorVar": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 4,
+ "localID": 57
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "COLOR"
+ }
+ }
+ ]
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 7,
+ "localID": 94
+ }
+ ]
+ },
+ "size": {
+ "x": 16,
+ "y": 16
+ },
+ "proportionsConstrained": true
+ }
+ ],
+ "uniformScaleFactor": 1
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 94,
+ "localID": 5438
+ },
+ "parentIndex": {
+ "guid": {
+ "sessionID": 7,
+ "localID": 94
+ },
+ "position": "\""
+ },
+ "type": "VECTOR",
+ "name": "Icon"
+ }
+]
diff --git a/packages/fig/tests/instance-overrides/gold/fixtures/README.md b/packages/fig/tests/instance-overrides/gold/fixtures/README.md
new file mode 100644
index 000000000..66498927d
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/gold/fixtures/README.md
@@ -0,0 +1,17 @@
+# `gold-input-layout.json`
+
+Read-only Figma Plugin API capture from the original Gold Preview file, with `figma.fileKey`
+verified before querying each exact node ID. Coordinates are relative to the parent. The input
+instance's Tags container uses effective padding `(7.126753, 5.345065)` and spacing `3.563377`,
+not the source values `(8, 6)` and `4`. The saved child positions reflect that scaling.
+
+Initial imported geometry and the recomputed badge/placeholder positions are covered separately.
+This is property evidence, not a pixel comparison or an export/reopen acceptance result. No Figma
+nodes were changed during capture.
+
+## Shared nested scale fixture
+
+The document and browser visual tests share
+[`nested-layout-scale.json`](../../../../../tests/fixtures/nested-layout-scale.json).
+Its [provenance and acceptance limits](../../../../../tests/fixtures/nested-layout-scale.md)
+live alongside the fixture.
diff --git a/packages/fig/tests/instance-overrides/gold/fixtures/gold-input-layout.json b/packages/fig/tests/instance-overrides/gold/fixtures/gold-input-layout.json
new file mode 100644
index 000000000..7ac365c42
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/gold/fixtures/gold-input-layout.json
@@ -0,0 +1,49 @@
+{
+ "fileKey": "NmoHzskYNiSKOaRX14bMdw",
+ "nodes": [
+ {
+ "id": "1:3503",
+ "name": "Input",
+ "x": 49,
+ "y": 521,
+ "width": 393.5667419433594,
+ "height": 39.3802604675293,
+ "paddingLeft": 8.908441543579102,
+ "paddingTop": 0,
+ "itemSpacing": 0
+ },
+ {
+ "id": "I1:3503;4188:18912;4188:19312",
+ "name": "Tags",
+ "x": 0,
+ "y": 0,
+ "width": 277.3519592285156,
+ "height": 39.3802604675293,
+ "paddingLeft": 7.126753330230713,
+ "paddingTop": 5.345065116882324,
+ "itemSpacing": 3.5633766651153564
+ },
+ {
+ "id": "I1:3503;4188:18912;4275:72192",
+ "name": "Badge",
+ "x": 7.126753330230713,
+ "y": 5.345065116882324,
+ "width": 85.32389831542969,
+ "height": 28.69013023376465,
+ "paddingLeft": 0,
+ "paddingTop": 0,
+ "itemSpacing": 0
+ },
+ {
+ "id": "I1:3503;4188:18912;4188:19287",
+ "name": "Content",
+ "x": 0,
+ "y": 0,
+ "width": 374.8589782714844,
+ "height": 39.3802604675293,
+ "paddingLeft": 0,
+ "paddingTop": 0,
+ "itemSpacing": 0
+ }
+ ]
+}
diff --git a/packages/fig/tests/instance-overrides/gold/layout.test.ts b/packages/fig/tests/instance-overrides/gold/layout.test.ts
new file mode 100644
index 000000000..b054332e4
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/gold/layout.test.ts
@@ -0,0 +1,34 @@
+import { expect, test } from 'bun:test'
+
+import { readFixtureArrayBuffer } from '#fig-tests/helpers/fig-fixtures'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import { parseFigBuffer } from '@open-pencil/fig'
+import { nodeChangeToProps } from '@open-pencil/fig/node-change'
+
+test('omitted primary sizing is Hug only for auto-layout; explicit Fixed remains Fixed', () => {
+ expect(nodeChangeToProps({ type: 'FRAME', stackMode: 'HORIZONTAL' }, []).primaryAxisSizing).toBe(
+ 'HUG'
+ )
+ expect(
+ nodeChangeToProps({ type: 'FRAME', stackMode: 'VERTICAL', stackPrimarySizing: 'FIXED' }, [])
+ .primaryAxisSizing
+ ).toBe('FIXED')
+ expect(nodeChangeToProps({ type: 'FRAME' }, []).primaryAxisSizing).toBe('FIXED')
+})
+
+test('Gold date picker retains Figma Hug primary sizing when the saved field is omitted', async () => {
+ const { nodeChanges, blobs } = parseFigBuffer(readFixtureArrayBuffer('gold-preview.fig'))
+ const diagnostics: unknown[] = []
+ const root = interpretInstance(nodeChanges, '1:3516', {
+ derivedBounds: true,
+ onUnresolvedProperty: (diagnostic) => diagnostics.push(diagnostic)
+ })
+ const inline = root.children.find((node) => node.properties.name === 'Inline')
+ if (!inline) throw new Error('Missing Inline')
+ // Live Figma oracle: both nodes report primaryAxisSizingMode=AUTO.
+ for (const node of [root, inline]) {
+ expect(node.properties.stackPrimarySizing).toBeUndefined()
+ expect(nodeChangeToProps(node.properties, blobs).primaryAxisSizing).toBe('HUG')
+ }
+})
diff --git a/packages/fig/tests/instance-overrides/gold/saved-layout.test.ts b/packages/fig/tests/instance-overrides/gold/saved-layout.test.ts
new file mode 100644
index 000000000..4d365451c
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/gold/saved-layout.test.ts
@@ -0,0 +1,24 @@
+import { expect, test } from 'bun:test'
+
+import { readFixtureArrayBuffer } from '#fig-tests/helpers/fig-fixtures'
+import { interpretInstance, resolveOccurrencePath } from '#fig/instance-overrides/interpret'
+
+import { parseFigBuffer } from '@open-pencil/fig'
+import { nodeChangeToProps, stringToGuid } from '@open-pencil/fig/node-change'
+
+import oracle from './fixtures/gold-input-layout.json'
+
+test('Gold saved input geometry matches the independent Figma capture before layout', async () => {
+ const { nodeChanges, blobs } = parseFigBuffer(readFixtureArrayBuffer('gold-preview.fig'))
+ const input = interpretInstance(nodeChanges, '1:3503', { derivedBounds: true })
+ for (const expected of oracle.nodes) {
+ const path = expected.id.split(';').slice(1).map(stringToGuid)
+ const occurrence = resolveOccurrencePath(input, path)
+ const props = nodeChangeToProps(occurrence.properties, blobs)
+ for (const field of ['x', 'y', 'width', 'height'] as const) {
+ expect(props[field], `${expected.id}.${field}`).toBeCloseTo(expected[field], 4)
+ }
+ }
+ // Runtime padding/spacing and post-layout geometry are not accepted by this test.
+ // The capture's effective metrics remain the oracle for that pending fix.
+})
diff --git a/packages/fig/tests/instance-overrides/materialize.test.ts b/packages/fig/tests/instance-overrides/materialize.test.ts
new file mode 100644
index 000000000..2bffdedb4
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/materialize.test.ts
@@ -0,0 +1,134 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import {
+ interpretComponent,
+ interpretInstance,
+ type MissingComponentDiagnostic
+} from '#fig/instance-overrides/interpret'
+import { materializeInstance } from '#fig/instance-overrides/materialize-instance'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import fixture from './fixtures/accordion-source-closure.json'
+
+function setup() {
+ const occurrence = interpretInstance(fixture as NodeChange[], '7:283', {
+ onUnresolvedProperty: (diagnostic) => {
+ expect(diagnostic.reason).toBe('missing-target')
+ }
+ })
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const components = new Map<string, string>()
+ function visit(node: typeof occurrence): void {
+ if (node.mainComponentId && !components.has(node.mainComponentId)) {
+ components.set(node.mainComponentId, graph.createNode('COMPONENT', page.id).id)
+ }
+ node.children.forEach(visit)
+ }
+ visit(occurrence)
+ return { occurrence, graph, page, components }
+}
+
+test('materializes separate occurrence nodes with direct component identities and resolved text', () => {
+ const { occurrence, graph, page, components } = setup()
+ const result = materializeInstance(graph, page.id, occurrence, components)
+ expect(result.root.type).toBe('INSTANCE')
+ expect(result.root.componentId).toBe(components.get('7:186'))
+ const labels = [...result.nodes].filter(([source]) => source.sourceId === '4:483')
+ expect(labels).toHaveLength(2)
+ expect(labels.map(([, node]) => node.text)).toEqual(['Is it styled?', 'Is it animated?'])
+ expect(labels[0][1].id).not.toBe(labels[1][1].id)
+ expect(graph.getChildren(result.root.id).map((node) => node.componentId)).toEqual([
+ components.get('7:251'),
+ components.get('7:156'),
+ components.get('7:156')
+ ])
+ for (const node of result.nodes.values()) expect(node.source.id).toBeNull()
+})
+
+test('materialization does not share editable paint payloads with interpreted occurrences', () => {
+ const { occurrence, graph, page, components } = setup()
+ occurrence.properties.fillPaints = [
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true
+ }
+ ]
+ const before = structuredClone(occurrence)
+ const first = materializeInstance(graph, page.id, occurrence, components)
+ const second = materializeInstance(graph, page.id, occurrence, components)
+ const fill = first.root.fills[0]
+ if (!fill?.color) throw new Error('Missing materialized fill')
+ fill.color.r = 0
+ expect(second.root.fills[0].color?.r).toBe(1)
+ expect(occurrence).toEqual(before)
+})
+
+test('rejects an invalid late descendant without creating a partial tree', () => {
+ const { occurrence, graph, page, components } = setup()
+ occurrence.children[2].properties.type = 'DOCUMENT'
+ const count = graph.nodes.size
+ expect(() => materializeInstance(graph, page.id, occurrence, components)).toThrow(
+ 'Cannot materialize DOCUMENT'
+ )
+ expect(graph.nodes.size).toBe(count)
+})
+
+test('rejects cyclic occurrence input before mutating the destination', () => {
+ const { occurrence, graph, page, components } = setup()
+ occurrence.children.push(occurrence)
+ const count = graph.nodes.size
+ expect(() => materializeInstance(graph, page.id, occurrence, components)).toThrow(
+ 'Repeated or cyclic'
+ )
+ expect(graph.nodes.size).toBe(count)
+})
+
+test('rejects missing components before creating occurrence nodes', () => {
+ const { occurrence, graph, page } = setup()
+ const count = graph.nodes.size
+ expect(() => materializeInstance(graph, page.id, occurrence, new Map())).toThrow(
+ 'Missing materialized component'
+ )
+ expect(graph.nodes.size).toBe(count)
+})
+
+// Figma keeps an instance whose main component was deleted, with its saved reference.
+test('an instance of a deleted component stays a childless instance when acknowledged', () => {
+ const changes = [
+ { guid: guid(1, 4), type: 'SYMBOL' },
+ {
+ guid: guid(2, 4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1, 4), position: '!' },
+ name: 'Orphan',
+ size: { x: 10, y: 10 },
+ symbolData: {
+ symbolID: guid(9, 4),
+ symbolOverrides: [{ guidPath: { guids: [guid(8, 4)] }, opacity: 0.5 }]
+ }
+ }
+ ] as NodeChange[]
+ expect(() => interpretComponent(changes, '4:1')).toThrow('Missing source node 4:9')
+ const missing: MissingComponentDiagnostic[] = []
+ const component = interpretComponent(changes, '4:1', {
+ onMissingComponent: (diagnostic) => missing.push(diagnostic)
+ })
+ expect(missing).toEqual([{ ownerId: '4:2', componentId: '4:9' }])
+ const orphan = component.children[0]
+ expect(orphan.mainComponentId).toBeNull()
+ expect(orphan.children).toEqual([])
+ expect(orphan.properties.symbolData?.symbolID).toEqual(guid(9, 4))
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const materialized = materializeInstance(graph, page.id, component, new Map())
+ const node = graph.getChildren(materialized.root.id)[0]
+ expect(node.type).toBe('INSTANCE')
+ expect(node.componentId).toBeNull()
+ expect(node.childIds).toEqual([])
+})
diff --git a/packages/fig/tests/instance-overrides/path.test.ts b/packages/fig/tests/instance-overrides/path.test.ts
new file mode 100644
index 000000000..edaa8d191
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/path.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, test } from 'bun:test'
+
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import fixture from './fixtures/accordion-instance-paths.json'
+
+// Reduced from shadcn Figma kit (Community), Accordion 7:283.
+// Figma oracle: second/third text occurrences use source 4:483, but read
+// "Is it styled?" / "Is it animated?". First item selects component 7:251.
+const changes = fixture as NodeChange[]
+
+function descendants(node: ReturnType<typeof interpretInstance>): (typeof node)[] {
+ return [node, ...node.children.flatMap(descendants)]
+}
+
+describe('instance-path interpretation', () => {
+ test('preserves repeated source occurrences, nested text and outer typography', () => {
+ const before = structuredClone(changes)
+ const result = interpretInstance(changes, '7:283')
+ expect(result.mainComponentId).toBe('7:186')
+ expect(result.children.map((node) => node.sourceId)).toEqual(['7:163', '7:169', '7:175'])
+ expect(result.children.map((node) => node.mainComponentId)).toEqual(['7:251', '7:156', '7:156'])
+ const second = descendants(result.children[1]).find((node) => node.sourceId === '4:483')
+ const third = descendants(result.children[2]).find((node) => node.sourceId === '4:483')
+ expect(second?.properties.textData?.characters).toBe('Is it styled?')
+ expect(third?.properties.textData?.characters).toBe('Is it animated?')
+ expect(second?.properties.fontSize).toBe(16)
+ expect(third?.properties.fontSize).toBe(16)
+ // Expansion retains occurrence bounds. Figma's 92px final height is a
+ // subsequent Hug-layout result, not the structural swap operation.
+ expect(result.children[0].properties.size).toEqual({ x: 440, y: 56 })
+ expect(result.children[0].properties.name).toBe('AccordionItem')
+ expect(second).not.toBe(third)
+ expect(descendants(result.children[0]).some((node) => node.sourceId === '7:254')).toBe(true)
+ expect(changes).toEqual(before)
+ })
+
+ test('does not depend on archive declaration order', () => {
+ expect(interpretInstance([...changes].reverse(), '7:283')).toEqual(
+ interpretInstance(changes, '7:283')
+ )
+ })
+
+ test('rejects cyclic component expansion', () => {
+ expect(() =>
+ interpretInstance(
+ [
+ {
+ guid: { sessionID: 1, localID: 1 },
+ type: 'INSTANCE',
+ symbolData: { symbolID: { sessionID: 1, localID: 1 } }
+ }
+ ],
+ '1:1'
+ )
+ ).toThrow('Cyclic component expansion')
+ })
+})
diff --git a/packages/fig/tests/instance-overrides/retirement-counterexamples.test.ts b/packages/fig/tests/instance-overrides/retirement-counterexamples.test.ts
new file mode 100644
index 000000000..b2164d0bb
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/retirement-counterexamples.test.ts
@@ -0,0 +1,32 @@
+import { expect, test } from 'bun:test'
+
+import { expectPathError } from '#fig-tests/helpers/errors'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const guid = (localID: number) => ({ sessionID: 1, localID })
+for (const similarity of ['equal-values', 'equal-fields', 'matching-suffix'] as const) {
+ test(`missing paths remain errors despite ${similarity}`, () => {
+ const common =
+ similarity === 'matching-suffix'
+ ? { guidPath: { guids: [guid(99), guid(3)] }, opacity: 0.5 }
+ : { guidPath: { guids: [guid(99)] }, opacity: 0.5 }
+ const liveBySimilarity = {
+ 'equal-values': { guidPath: { guids: [guid(3)] }, opacity: 0.5 },
+ 'equal-fields': { guidPath: { guids: [guid(3)] }, opacity: 1 },
+ 'matching-suffix': { guidPath: { guids: [guid(3), guid(3)] }, opacity: 0.5 }
+ }
+ const live = liveBySimilarity[similarity]
+ const records: NodeChange[] = [
+ { guid: guid(1), type: 'SYMBOL' },
+ { guid: guid(3), type: 'FRAME', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ symbolData: { symbolID: guid(1), symbolOverrides: [common, live] }
+ }
+ ]
+ expectPathError(() => interpretInstance(records, '1:4'), 'missing-target')
+ })
+}
diff --git a/packages/fig/tests/instance-overrides/root-key.test.ts b/packages/fig/tests/instance-overrides/root-key.test.ts
new file mode 100644
index 000000000..70b11713e
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/root-key.test.ts
@@ -0,0 +1,148 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('explicit swaps preserve references owned by the enclosing component', () => {
+ const refs = [{ defID: guid(80), componentPropNodeField: 'VISIBLE' }]
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '!' },
+ componentPropRefs: refs,
+ symbolData: { symbolID: guid(3) }
+ },
+ { guid: guid(3), type: 'SYMBOL' },
+ { guid: guid(4), type: 'SYMBOL' },
+ {
+ guid: guid(5),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [{ guidPath: { guids: [guid(2)] }, overriddenSymbolID: guid(4) }]
+ }
+ }
+ ] as NodeChange[]
+ const child = interpretInstance(changes, '1:5').children[0]
+ expect(child.mainComponentId).toBe('1:4')
+ expect(child.properties.componentPropRefs).toEqual(refs)
+ expect(child.properties.componentPropRefs).not.toBe(refs)
+})
+
+test('binding swaps retain source-root claims without mapping old children into the replacement', () => {
+ const changes = [
+ {
+ guid: guid(1),
+ type: 'SYMBOL',
+ componentPropDefs: [
+ { id: guid(80), initialValue: { guidValue: guid(3) }, type: 'INSTANCE_SWAP', name: 'Icon' }
+ ]
+ },
+ {
+ guid: guid(2),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '!' },
+ componentPropRefs: [{ defID: guid(80), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }],
+ symbolData: {
+ symbolID: guid(3),
+ symbolOverrides: [{ guidPath: { guids: [guid(90)] }, opacity: 0.4 }]
+ }
+ },
+ { guid: guid(3), type: 'SYMBOL', overrideKey: guid(90) },
+ { guid: guid(4), type: 'SYMBOL', overrideKey: guid(91) },
+ {
+ guid: guid(5),
+ type: 'INSTANCE',
+ symbolData: { symbolID: guid(1) },
+ componentPropAssignments: [{ defID: guid(80), value: { guidValue: guid(4) } }]
+ }
+ ] as NodeChange[]
+ const child = interpretInstance(changes, '1:5').children[0]
+ expect(child.mainComponentId).toBe('1:4')
+ expect(child.properties.opacity).toBe(0.4)
+ expect(child.propertyClaims[0].path).toEqual([guid(90)])
+})
+
+test('component root-key assignments configure children before expansion', () => {
+ const changes = [
+ {
+ guid: guid(1),
+ overrideKey: guid(90),
+ type: 'SYMBOL',
+ componentPropDefs: [
+ { id: guid(80), name: 'Label', type: 'TEXT', initialValue: { textValue: 'Default' } }
+ ]
+ },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1), position: '!' },
+ componentPropRefs: [{ defID: guid(80), componentPropNodeField: 'TEXT_DATA' }]
+ },
+ {
+ guid: guid(2),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [
+ {
+ guidPath: { guids: [guid(90)] },
+ componentPropAssignments: [{ defID: guid(80), value: { textValue: 'Assigned' } }]
+ }
+ ]
+ }
+ }
+ ] as NodeChange[]
+ expect(interpretInstance(changes, '1:2').children[0].properties.textData?.characters).toBe(
+ 'Assigned'
+ )
+})
+
+test('a root-key swap replaces the component rather than resolving a child', () => {
+ const changes = [
+ { guid: guid(1), overrideKey: guid(90), type: 'SYMBOL' },
+ { guid: guid(3), overrideKey: guid(91), type: 'SYMBOL', name: 'Replacement' },
+ {
+ guid: guid(4),
+ type: 'TEXT',
+ parentIndex: { guid: guid(3), position: '!' },
+ textData: { characters: 'New' }
+ },
+ {
+ guid: guid(2),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [{ guidPath: { guids: [guid(90)] }, overriddenSymbolID: guid(3) }]
+ }
+ }
+ ] as NodeChange[]
+ const result = interpretInstance(changes, '1:2')
+ expect(result.mainComponentId).toBe('1:3')
+ expect(result.children[0].properties.textData?.characters).toBe('New')
+})
+
+test('component overrideKey addresses the root while placed instance size remains authoritative', () => {
+ const changes = [
+ { guid: guid(1), overrideKey: guid(90), type: 'SYMBOL', size: { x: 100, y: 40 } },
+ {
+ guid: guid(2),
+ type: 'INSTANCE',
+ size: { x: 50, y: 20 },
+ symbolData: {
+ symbolID: guid(1),
+ uniformScaleFactor: 0.5,
+ symbolOverrides: [
+ { guidPath: { guids: [guid(90)] }, size: { x: 100, y: 40 }, opacity: 0.4 }
+ ]
+ }
+ }
+ ] as NodeChange[]
+ const result = interpretInstance(changes, '1:2')
+ expect(result.properties.opacity).toBe(0.4)
+ expect(result.properties.size).toEqual({ x: 50, y: 20 })
+})
diff --git a/packages/fig/tests/instance-overrides/saved-name-provenance.test.ts b/packages/fig/tests/instance-overrides/saved-name-provenance.test.ts
new file mode 100644
index 000000000..8ddf1dbbd
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/saved-name-provenance.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from 'bun:test'
+
+import fixture from './fixtures/name-provenance.json'
+
+// Records are reduced from Figma's actual Save local copy canvas payloads.
+test('saved name claims distinguish explicit equal names and component-set defaults', () => {
+ const [plain, equal, custom] = fixture.oracle.names.instances
+ const record = (id: string) =>
+ fixture.records.find((n) => `${n.guid.sessionID}:${n.guid.localID}` === id)
+ expect(record(plain.id)?.symbolData?.symbolOverrides).toEqual([])
+ expect(record(equal.id)?.symbolData?.symbolOverrides[0]?.name).toBe('Original')
+ expect(record(custom.id)?.symbolData?.symbolOverrides[0]?.name).toBe('Custom')
+ const set = record(fixture.oracle.variants.set)
+ expect(set?.isStateGroup).toBe(true)
+ expect(set?.name).toBe('Control')
+ expect(fixture.oracle.variants.variant.map((n) => n.name)).toEqual(['Control', 'Custom'])
+ expect(fixture.oracle.variants.unrelated.map((n) => n.name)).toEqual(['Other', 'Custom'])
+})
diff --git a/packages/fig/tests/instance-overrides/saved-swaps.test.ts b/packages/fig/tests/instance-overrides/saved-swaps.test.ts
new file mode 100644
index 000000000..a240721fc
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/saved-swaps.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from 'bun:test'
+
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import fixture from './fixtures/saved-swap-paths.json'
+
+// Figma Save local copy capture; live oracle recorded before saving.
+// Only the probe's source nodes and semantic fields are retained here.
+const changes = fixture as NodeChange[]
+
+describe('Figma-authored saved swaps', () => {
+ test('uses the replacement default for an untouched top-level swap', () => {
+ const result = interpretInstance(changes, '10965:1263')
+ expect(result.mainComponentId).toBe('10965:1261')
+ expect(result.properties.size).toEqual({ x: 160, y: 64 })
+ expect(result.children[0].properties.textData?.characters).toBe('Replacement label')
+ })
+
+ test('reads explicit retained size, opacity and text rather than inferring preservation', () => {
+ const result = interpretInstance(changes, '10965:1266')
+ expect(result.properties.size).toEqual({ x: 120, y: 50 })
+ expect(result.properties.opacity).toBeCloseTo(0.6)
+ expect(result.children[0].properties.textData?.characters).toBe('Edited label')
+ })
+
+ test('replays preserved inherited text onto the replacement child path', () => {
+ const result = interpretInstance(changes, '10965:1272').children[0]
+ expect(result.sourceId).toBe('10965:1270')
+ expect(result.properties.size).toEqual({ x: 100, y: 40 })
+ expect(result.mainComponentId).toBe('10965:1261')
+ expect(result.children[0].sourceId).toBe('10965:1262')
+ expect(result.children[0].properties.textData?.characters).toBe('Inherited edit')
+ })
+
+ test('does not carry old text to a replacement when the saved override is absent', () => {
+ const result = interpretInstance(changes, '10965:1276').children[0]
+ expect(result.properties.size).toEqual({ x: 100, y: 40 })
+ expect(result.mainComponentId).toBe('10965:1261')
+ expect(result.children[0].properties.textData?.characters).toBe('Replacement label')
+ })
+})
diff --git a/packages/fig/tests/instance-overrides/source-closure.test.ts b/packages/fig/tests/instance-overrides/source-closure.test.ts
new file mode 100644
index 000000000..bb2e6f099
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/source-closure.test.ts
@@ -0,0 +1,42 @@
+import { expect, test } from 'bun:test'
+
+import {
+ interpretInstance,
+ type InstanceOccurrence,
+ type InstancePathDiagnostic
+} from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import fixture from './fixtures/accordion-source-closure.json'
+
+function texts(node: InstanceOccurrence): string[] {
+ return [
+ ...(node.properties.type === 'TEXT' ? [node.properties.textData?.characters ?? ''] : []),
+ ...node.children.flatMap(texts)
+ ]
+}
+
+test('full Accordion source records preserve independent labels while reporting stale overrides', () => {
+ const diagnostics: InstancePathDiagnostic[] = []
+ const result = interpretInstance(fixture as NodeChange[], '7:283', {
+ onUnresolvedProperty: (diagnostic) => diagnostics.push(diagnostic)
+ })
+ expect(result.children.map((node) => node.mainComponentId)).toEqual(['7:251', '7:156', '7:156'])
+ expect(result.children.map((node) => texts(node)[0])).toEqual([
+ 'Is it accessible?',
+ 'Is it styled?',
+ 'Is it animated?'
+ ])
+ // The first item is swapped to 7:251, which has no 7:95 occurrence; only the two
+ // triggers that exist in the result report the stale 7:93 path.
+ expect(diagnostics).toHaveLength(2)
+ for (const diagnostic of diagnostics) {
+ expect(diagnostic).toEqual({
+ ownerId: '7:95',
+ mainComponentId: '7:94',
+ path: [{ sessionID: 7, localID: 93 }],
+ reason: 'missing-target'
+ })
+ }
+})
diff --git a/packages/fig/tests/instance-overrides/stale-path.test.ts b/packages/fig/tests/instance-overrides/stale-path.test.ts
new file mode 100644
index 000000000..e16e0bd18
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/stale-path.test.ts
@@ -0,0 +1,118 @@
+import { expect, test } from 'bun:test'
+
+import { expectPathError } from '#fig-tests/helpers/errors'
+import { guid } from '#fig-tests/helpers/guid'
+import { interpretInstance, type InstancePathDiagnostic } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import fixture from './fixtures/stale-chevron-override.json'
+
+test('reports stale property overrides and leaves the actual replacement vector untouched', () => {
+ const diagnostics: InstancePathDiagnostic[] = []
+ const root = interpretInstance(fixture as NodeChange[], '7:95', {
+ onUnresolvedProperty: (diagnostic) => diagnostics.push(diagnostic)
+ })
+ expect(diagnostics).toEqual([
+ {
+ ownerId: '7:95',
+ mainComponentId: '7:94',
+ path: [{ sessionID: 7, localID: 93 }],
+ reason: 'missing-target'
+ }
+ ])
+ expect(root.children[0].sourceId).toBe('94:5438')
+ expect(root.children[0].properties.strokePaints).toBeUndefined()
+})
+
+test('diagnostic mode still rejects unresolved structural overrides', () => {
+ const changes = structuredClone(fixture) as NodeChange[]
+ const owner = changes.find((node) => node.guid?.sessionID === 7 && node.guid.localID === 95)
+ if (!owner) throw new Error('Missing fixture owner')
+ owner.symbolData = {
+ symbolID: { sessionID: 7, localID: 94 },
+ symbolOverrides: [
+ {
+ guidPath: { guids: [{ sessionID: 7, localID: 93 }] },
+ overriddenSymbolID: { sessionID: 7, localID: 94 }
+ }
+ ]
+ } as NodeChange['symbolData']
+ const diagnostics: InstancePathDiagnostic[] = []
+ expectPathError(
+ () =>
+ interpretInstance(changes, '7:95', {
+ onUnresolvedProperty: (diagnostic) => diagnostics.push(diagnostic)
+ }),
+ 'missing-target'
+ )
+ expect(diagnostics).toEqual([])
+})
+
+// Actual shadcn records: the old 7:93 path is retained on instance 7:95,
+// while component 7:94 contains vector 94:5438. No inferred correspondence.
+test('reports the declaring owner and stale path instead of applying it to another vector', () => {
+ expect(() => interpretInstance(fixture as NodeChange[], '7:95')).toThrow(
+ 'Override declared by 7:95, path [7:93]: Expected one instance-path target for 7:93; found 0'
+ )
+})
+
+// Preline's `_header/navbar` keeps a swap addressing a layer the component no longer has,
+// while the replacement it names is still present. Figma opens that file, so a swap whose
+// target is gone reports like any other stale record rather than refusing the document.
+test('reports a swap whose target layer is gone instead of refusing the file', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'SYMBOL', name: 'navbar' },
+ { guid: guid(2), type: 'FRAME', name: 'kept', parentIndex: { guid: guid(1), position: '!' } },
+ { guid: guid(3), type: 'SYMBOL', name: 'replacement' },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ name: 'navbar instance',
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [{ guidPath: { guids: [guid(99)] }, overriddenSymbolID: guid(3) }]
+ }
+ }
+ ]
+ const diagnostics: InstancePathDiagnostic[] = []
+ const root = interpretInstance(changes, '1:4', {
+ onUnresolvedAssignment: (diagnostic) => diagnostics.push(diagnostic)
+ })
+
+ expect(diagnostics).toHaveLength(1)
+ expect(diagnostics[0].reason).toBe('missing-target')
+ expect(root.children.map((child) => child.properties.name)).toEqual(['kept'])
+})
+
+test('an ambiguous swap address is a wrong path, not a stale one', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'SYMBOL', name: 'navbar' },
+ {
+ guid: guid(2),
+ type: 'FRAME',
+ name: 'a',
+ overrideKey: guid(7),
+ parentIndex: { guid: guid(1), position: '!' }
+ },
+ {
+ guid: guid(3),
+ type: 'FRAME',
+ name: 'b',
+ overrideKey: guid(7),
+ parentIndex: { guid: guid(1), position: '"' }
+ },
+ { guid: guid(5), type: 'SYMBOL', name: 'replacement' },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [{ guidPath: { guids: [guid(7)] }, overriddenSymbolID: guid(5) }]
+ }
+ }
+ ]
+ expect(() =>
+ interpretInstance(changes, '1:4', { onUnresolvedAssignment: () => undefined })
+ ).toThrow('found 2')
+})
diff --git a/packages/fig/tests/instance-overrides/swap-name.test.ts b/packages/fig/tests/instance-overrides/swap-name.test.ts
new file mode 100644
index 000000000..c8486ce8b
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/swap-name.test.ts
@@ -0,0 +1,30 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+// Live Figma swapComponent probe: untouched name follows replacement, custom name stays.
+test('a nested swap adopts the replacement name when no instance name is supplied', () => {
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL', name: 'Original' },
+ { guid: guid(2), type: 'SYMBOL', name: 'Replacement' },
+ { guid: guid(3), type: 'SYMBOL' },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(3), position: '!' },
+ symbolData: { symbolID: guid(1) }
+ },
+ {
+ guid: guid(5),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(3),
+ symbolOverrides: [{ guidPath: { guids: [guid(4)] }, overriddenSymbolID: guid(2) }]
+ }
+ }
+ ] as NodeChange[]
+ expect(interpretInstance(changes, '1:5').children[0].properties.name).toBe('Replacement')
+})
diff --git a/packages/fig/tests/instance-overrides/swap-provenance.test.ts b/packages/fig/tests/instance-overrides/swap-provenance.test.ts
new file mode 100644
index 000000000..80991cce4
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/swap-provenance.test.ts
@@ -0,0 +1,177 @@
+import { expect, test } from 'bun:test'
+
+import { expectPathError } from '#fig-tests/helpers/errors'
+import { guid } from '#fig-tests/helpers/guid'
+import { interpretInstance, resolveOccurrencePath } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('a saved swap applies replacement bindings before explicit root and child claims', () => {
+ const property = guid(90)
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(3),
+ type: 'SYMBOL',
+ opacity: 1,
+ componentPropDefs: [
+ { id: property, name: 'Label', type: 'TEXT', initialValue: { textValue: 'Default' } }
+ ]
+ },
+ {
+ guid: guid(4),
+ type: 'TEXT',
+ parentIndex: { guid: guid(3), position: '!' },
+ textData: { characters: 'Default' },
+ componentPropRefs: [{ defID: property, componentPropNodeField: 'TEXT_DATA' }]
+ },
+ { guid: guid(5), type: 'SYMBOL' },
+ {
+ guid: guid(6),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(5), position: '!' },
+ symbolData: { symbolID: guid(1) }
+ },
+ {
+ guid: guid(8),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(5),
+ symbolOverrides: [
+ {
+ guidPath: { guids: [guid(6)] },
+ overriddenSymbolID: guid(3),
+ componentPropAssignments: [{ defID: property, value: { textValue: 'Assigned' } }],
+ opacity: 0.4
+ },
+ { guidPath: { guids: [guid(6), guid(4)] }, textData: { characters: 'Explicit' } }
+ ]
+ }
+ }
+ ] as NodeChange[]
+ const result = interpretInstance(changes, '1:8')
+ const swapped = result.children[0]
+ expect(swapped.mainComponentId).toBe('1:3')
+ expect(swapped.properties.opacity).toBe(0.4)
+ expect(swapped.children[0].properties.textData?.characters).toBe('Explicit')
+ expect(swapped.children[0].bindingClaims).toEqual([
+ { definitionId: property, field: 'textData', origin: 'assignment' }
+ ])
+ expect(result.propertyClaims).toEqual([
+ { declaredBy: '1:8', path: [guid(6)], properties: { opacity: 0.4 } },
+ {
+ declaredBy: '1:8',
+ path: [guid(6), guid(4)],
+ properties: { textData: { characters: 'Explicit' } }
+ }
+ ])
+ for (const claim of result.propertyClaims) {
+ expect(() => resolveOccurrencePath(result, claim.path)).not.toThrow()
+ }
+})
+
+test('an outer swap retires inherited claims against removed descendants', () => {
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1), position: '!' },
+ textData: { characters: 'Original' }
+ },
+ { guid: guid(3), type: 'SYMBOL' },
+ {
+ guid: guid(4),
+ type: 'TEXT',
+ parentIndex: { guid: guid(3), position: '!' },
+ textData: { characters: 'Replacement' }
+ },
+ { guid: guid(5), type: 'SYMBOL' },
+ {
+ guid: guid(6),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(5), position: '!' },
+ symbolData: { symbolID: guid(1) }
+ },
+ {
+ guid: guid(7),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(5),
+ symbolOverrides: [
+ { guidPath: { guids: [guid(6), guid(2)] }, textData: { characters: 'Old explicit' } }
+ ]
+ }
+ },
+ {
+ guid: guid(8),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(7),
+ symbolOverrides: [{ guidPath: { guids: [guid(6)] }, overriddenSymbolID: guid(3) }]
+ }
+ }
+ ] as NodeChange[]
+ const result = interpretInstance(changes, '1:8')
+ expect(result.children[0].children[0].properties.textData?.characters).toBe('Replacement')
+ expect(result.propertyClaims).toEqual([])
+ for (const claim of result.propertyClaims)
+ expect(() => resolveOccurrencePath(result, claim.path)).not.toThrow()
+ expect(interpretInstance(changes, '1:7').propertyClaims).toHaveLength(1)
+})
+
+// material3 List: an outer owner swaps a list item to another variant, and the item's own
+// saved swap of a trailing checkbox still addresses the original variant's child.
+test('an outer swap retires an inherited nested swap against the replaced component', () => {
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL', name: 'Checkbox' },
+ { guid: guid(2), type: 'SYMBOL', name: 'Switch' },
+ { guid: guid(10), type: 'SYMBOL', name: 'Item with checkbox' },
+ { guid: guid(11), type: 'FRAME', parentIndex: { guid: guid(10), position: '!' } },
+ {
+ guid: guid(12),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(11), position: '!' },
+ symbolData: { symbolID: guid(1) }
+ },
+ { guid: guid(20), type: 'SYMBOL', name: 'Item without checkbox' },
+ {
+ guid: guid(21),
+ type: 'TEXT',
+ parentIndex: { guid: guid(20), position: '!' },
+ textData: { characters: 'Plain' }
+ },
+ { guid: guid(30), type: 'SYMBOL', name: 'List' },
+ {
+ guid: guid(31),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(30), position: '!' },
+ symbolData: {
+ symbolID: guid(10),
+ symbolOverrides: [{ guidPath: { guids: [guid(12)] }, overriddenSymbolID: guid(2) }]
+ }
+ },
+ {
+ guid: guid(40),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(30),
+ symbolOverrides: [{ guidPath: { guids: [guid(31)] }, overriddenSymbolID: guid(20) }]
+ }
+ }
+ ] as NodeChange[]
+ const item = interpretInstance(changes, '1:40').children[0]
+ expect(item.mainComponentId).toBe('1:20')
+ expect(item.children[0].properties.textData?.characters).toBe('Plain')
+ // Without the outer swap the nested swap still applies.
+ expect(interpretInstance(changes, '1:31').children[0].children[0].mainComponentId).toBe('1:2')
+ // A nested swap that never resolved anywhere remains an error.
+ const broken = structuredClone(changes)
+ const inner = broken.find((node) => node.guid?.localID === 31)
+ if (!inner?.symbolData) throw new Error('Missing inner instance')
+ inner.symbolData = {
+ symbolID: guid(10),
+ symbolOverrides: [{ guidPath: { guids: [guid(99)] }, overriddenSymbolID: guid(2) }]
+ } as NodeChange['symbolData']
+ expectPathError(() => interpretInstance(broken, '1:40'), 'missing-target')
+})
diff --git a/packages/fig/tests/instance-overrides/swapped-paint-claims.test.ts b/packages/fig/tests/instance-overrides/swapped-paint-claims.test.ts
new file mode 100644
index 000000000..765e742f0
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/swapped-paint-claims.test.ts
@@ -0,0 +1,104 @@
+import { expect, test } from 'bun:test'
+
+import { expectPathError } from '#fig-tests/helpers/errors'
+import { guid } from '#fig-tests/helpers/guid'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('binding swap ignores known removed-child paint claims without discarding unswapped source claims', () => {
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'VECTOR',
+ parentIndex: { guid: guid(1), position: '!' },
+ fillPaints: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ },
+ { guid: guid(3), type: 'SYMBOL' },
+ {
+ guid: guid(4),
+ type: 'VECTOR',
+ parentIndex: { guid: guid(3), position: '!' },
+ fillPaints: [{ type: 'SOLID', color: { r: 0, g: 0, b: 1, a: 1 }, opacity: 1, visible: true }]
+ },
+ {
+ guid: guid(5),
+ type: 'SYMBOL',
+ componentPropDefs: [
+ { id: guid(90), name: 'Icon', type: 'INSTANCE_SWAP', initialValue: { guidValue: guid(1) } }
+ ]
+ },
+ {
+ guid: guid(6),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(5), position: '!' },
+ componentPropRefs: [{ defID: guid(90), componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }],
+ derivedSymbolData: [{ guidPath: { guids: [guid(2)] }, size: { x: 16, y: 16 } }],
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [{ guidPath: { guids: [guid(2)] }, fillPaints: [] }]
+ }
+ },
+ { guid: guid(7), type: 'INSTANCE', symbolData: { symbolID: guid(5) } },
+ {
+ guid: guid(8),
+ type: 'INSTANCE',
+ derivedSymbolData: [{ guidPath: { guids: [guid(6), guid(2)] }, size: { x: 24, y: 24 } }],
+ symbolData: { symbolID: guid(5) },
+ componentPropAssignments: [{ defID: guid(90), value: { guidValue: guid(3) } }]
+ }
+ ] as NodeChange[]
+ expect(interpretInstance(changes, '1:7').children[0].children[0].properties.fillPaints).toEqual(
+ []
+ )
+ const original = changes.find((node) => node.guid?.localID === 6)
+ if (!original?.symbolData) throw new Error('Missing source instance')
+ const malformed = structuredClone(changes)
+ const malformedSource = malformed.find((node) => node.guid?.localID === 6)
+ if (!malformedSource?.symbolData) throw new Error('Missing malformed source')
+ malformedSource.symbolData = {
+ ...malformedSource.symbolData,
+ symbolOverrides: [{ guidPath: { guids: [guid(999)] }, fillPaints: [] }]
+ } as NodeChange['symbolData']
+ expectPathError(() => interpretInstance(malformed, '1:8'), 'missing-target')
+ const swapped = interpretInstance(changes, '1:8', { derivedBounds: true }).children[0]
+ expect(swapped.children[0].derivedSize).toBeUndefined()
+ expect(
+ interpretInstance(changes, '1:7', { derivedBounds: true }).children[0].children[0].derivedSize
+ ).toEqual({ x: 16, y: 16 })
+ malformedSource.symbolData = structuredClone(original.symbolData)
+ malformedSource.derivedSymbolData = [
+ { guidPath: { guids: [guid(999)] }, size: { x: 16, y: 16 } }
+ ] as NodeChange['derivedSymbolData']
+ expectPathError(
+ () => interpretInstance(malformed, '1:8', { derivedBounds: true }),
+ 'missing-target'
+ )
+ const ambiguousSource = structuredClone(changes)
+ ambiguousSource.push({
+ guid: guid(9),
+ type: 'VECTOR',
+ overrideKey: guid(2),
+ parentIndex: { guid: guid(1), position: '"' }
+ } as NodeChange)
+ expect(() => interpretInstance(ambiguousSource, '1:8', { derivedBounds: true })).toThrow(
+ 'found 0'
+ )
+ expect(swapped.mainComponentId).toBe('1:3')
+ const malformedOuter = structuredClone(changes)
+ const outer = malformedOuter.find((node) => node.guid?.localID === 8)
+ if (!outer) throw new Error('Missing outer instance')
+ outer.derivedSymbolData = [
+ { guidPath: { guids: [guid(6), guid(999)] }, size: { x: 24, y: 24 } }
+ ] as NodeChange['derivedSymbolData']
+ expectPathError(
+ () => interpretInstance(malformedOuter, '1:8', { derivedBounds: true }),
+ 'missing-target'
+ )
+ expect(swapped.children[0].sourceId).toBe('1:4')
+ expect(swapped.children[0].properties.fillPaints?.[0]?.color?.b).toBe(1)
+ expect(interpretInstance(changes, '1:7').children[0].children[0].properties.fillPaints).toEqual(
+ []
+ )
+})
diff --git a/packages/fig/tests/instance-overrides/text-provenance.test.ts b/packages/fig/tests/instance-overrides/text-provenance.test.ts
new file mode 100644
index 000000000..416c68fec
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/text-provenance.test.ts
@@ -0,0 +1,37 @@
+import { expect, test } from 'bun:test'
+
+import { invalidateInheritedTextData } from '#fig/instance-overrides/text-provenance'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+for (const patch of [
+ { fontSize: 20 },
+ { fontName: { family: 'Other', style: 'Regular' } },
+ { styleIdForText: { guid: { sessionID: 1, localID: 2 } } },
+ { textData: { characters: 'Same', characterStyleIDs: [1] } }
+]) {
+ test(`invalidates inherited glyphs for ${Object.keys(patch)[0]} changes`, () => {
+ const source: NodeChange = {
+ textData: { characters: 'Same' },
+ fontSize: 14,
+ derivedTextData: { layoutSize: { x: 40, y: 20 } }
+ }
+ invalidateInheritedTextData(source, patch)
+ expect(source.derivedTextData).toBeUndefined()
+ })
+}
+test('preserves caches for identical shaping, paint-only patches and explicit replacement data', () => {
+ const source: NodeChange = {
+ textData: { characters: 'Same' },
+ fontSize: 14,
+ derivedTextData: { layoutSize: { x: 40, y: 20 } }
+ }
+ for (const patch of [
+ { fontSize: 14 },
+ { fillPaints: [] },
+ { textData: { characters: 'Other' }, derivedTextData: { layoutSize: { x: 80, y: 20 } } }
+ ]) {
+ invalidateInheritedTextData(source, patch)
+ expect(source.derivedTextData?.layoutSize).toEqual({ x: 40, y: 20 })
+ }
+})
diff --git a/packages/fig/tests/instance-overrides/unresolved-assignments.test.ts b/packages/fig/tests/instance-overrides/unresolved-assignments.test.ts
new file mode 100644
index 000000000..ae1104a70
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/unresolved-assignments.test.ts
@@ -0,0 +1,50 @@
+import { expect, test } from 'bun:test'
+
+import { expectPathError } from '#fig-tests/helpers/errors'
+import { guid } from '#fig-tests/helpers/guid'
+import {
+ interpretInstance,
+ type InstanceAssignmentDiagnostic
+} from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+test('missing assignment targets require explicit partial-evaluation acknowledgement', () => {
+ const changes = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1), position: '!' },
+ textData: { characters: 'Unchanged' }
+ },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [
+ {
+ guidPath: { guids: [guid(99)] },
+ componentPropAssignments: [{ defID: guid(90), value: { textValue: 'Do not guess' } }]
+ }
+ ]
+ }
+ }
+ ] as NodeChange[]
+ expectPathError(() => interpretInstance(changes, '1:3'), 'missing-target')
+ const diagnostics: InstanceAssignmentDiagnostic[] = []
+ const result = interpretInstance(changes, '1:3', {
+ onUnresolvedAssignment: (d) => diagnostics.push(d)
+ })
+ expect(result.children[0].properties.textData?.characters).toBe('Unchanged')
+ expect(diagnostics).toEqual([
+ {
+ ownerId: '1:3',
+ mainComponentId: '1:1',
+ reason: 'missing-target',
+ path: [guid(99)],
+ assignments: [{ defID: guid(90), value: { textValue: 'Do not guess' } }]
+ }
+ ])
+})
diff --git a/packages/fig/tests/canvas-guides.test.ts b/packages/fig/tests/node-change/canvas-guides.test.ts
similarity index 100%
rename from packages/fig/tests/canvas-guides.test.ts
rename to packages/fig/tests/node-change/canvas-guides.test.ts
diff --git a/packages/fig/tests/node-change/clone.test.ts b/packages/fig/tests/node-change/clone.test.ts
new file mode 100644
index 000000000..703a05b82
--- /dev/null
+++ b/packages/fig/tests/node-change/clone.test.ts
@@ -0,0 +1,52 @@
+import { expect, test } from 'bun:test'
+
+import { cloneRecord } from '#fig/node-change/clone'
+
+test('a cloned record shares no mutable data with its source', () => {
+ const source = {
+ name: 'Node',
+ size: { x: 1, y: 2 },
+ fillPaints: [{ color: { r: 1, g: 0, b: 0, a: 1 }, stops: [{ position: 0 }] }],
+ textData: { characters: 'Hello', styleOverrideTable: [{ fontSize: 12 }] }
+ }
+ const copy = cloneRecord(source)
+ expect(copy).toEqual(source)
+ copy.size.x = 9
+ copy.fillPaints[0].color.r = 0
+ copy.fillPaints[0].stops[0].position = 1
+ copy.textData.styleOverrideTable[0].fontSize = 99
+ expect(source.size.x).toBe(1)
+ expect(source.fillPaints[0].color.r).toBe(1)
+ expect(source.fillPaints[0].stops[0].position).toBe(0)
+ expect(source.textData.styleOverrideTable[0].fontSize).toBe(12)
+})
+
+/** Blob payloads are bytes, not objects to walk field by field. */
+test('a byte buffer is copied as a buffer', () => {
+ const source = { bytes: new Uint8Array([1, 2, 3]) }
+ const copy = cloneRecord(source)
+ expect(copy.bytes).toBeInstanceOf(Uint8Array)
+ expect([...copy.bytes]).toEqual([1, 2, 3])
+ copy.bytes[0] = 9
+ expect(source.bytes[0]).toBe(1)
+})
+
+test('primitives, null and undefined survive unchanged', () => {
+ expect(cloneRecord({ a: null, b: undefined, c: 0, d: '', e: false })).toEqual({
+ a: null,
+ b: undefined,
+ c: 0,
+ d: '',
+ e: false
+ })
+})
+
+/** Anything that is not plain data goes through the structured algorithm instead. */
+test('a non-plain object is cloned structurally', () => {
+ const source = { when: new Date(0), which: new Map([['a', 1]]) }
+ const copy = cloneRecord(source)
+ expect(copy.when).toBeInstanceOf(Date)
+ expect(copy.when).not.toBe(source.when)
+ expect(copy.which.get('a')).toBe(1)
+ expect(copy.which).not.toBe(source.which)
+})
diff --git a/packages/fig/tests/export.test.ts b/packages/fig/tests/node-change/export.test.ts
similarity index 87%
rename from packages/fig/tests/export.test.ts
rename to packages/fig/tests/node-change/export.test.ts
index e55bcbaeb..917c99ee2 100644
--- a/packages/fig/tests/export.test.ts
+++ b/packages/fig/tests/node-change/export.test.ts
@@ -1,15 +1,15 @@
import { describe, expect, test } from 'bun:test'
-import { SceneGraph } from '@open-pencil/scene-graph'
-import type { GUID } from '@open-pencil/scene-graph/primitives'
-
import {
buildComponentPropIndex,
fractionalPosition,
mapToFigmaType,
sceneNodeToKiwi,
type FigNodeChangeExportRuntime
-} from '../src/node-change'
+} from '#fig/node-change/index'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+import type { GUID } from '@open-pencil/scene-graph/primitives'
describe('@open-pencil/fig SceneGraph export policy', () => {
test('maps node types and sibling positions deterministically', () => {
@@ -17,6 +17,15 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
expect([0, 93, 94, 188].map(fractionalPosition)).toEqual(['!', '~', '~!', '~~!'])
})
+ test('exports one ordering scheme when preserved and generated siblings are mixed', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const node = graph.createNode('RECTANGLE', page.id)
+ node.source.orderKey = 'z'
+ const change = sceneNodeToKiwi(node, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])
+ expect(change[0]?.parentIndex?.position).toBe(fractionalPosition(0))
+ })
+
test('reuses an export-scoped component property definition index', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
@@ -30,22 +39,11 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
componentPropertyAssignments: { '1:100': 'Override' }
})
const serialize = (definitions?: ReturnType<typeof buildComponentPropIndex>) =>
- sceneNodeToKiwi(
- instance,
- { sessionID: 1, localID: 1 },
- 0,
- { value: 2 },
- graph,
- [],
- new Map(),
- undefined,
- undefined,
- undefined,
- undefined,
- new Set(),
- undefined,
- definitions
- )[0].componentPropAssignments
+ sceneNodeToKiwi(instance, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [], {
+ nodeIdToGuid: new Map(),
+ assignedGuidValues: new Set(),
+ componentPropertyDefinitionsById: definitions
+ })[0].componentPropAssignments
const definitions = buildComponentPropIndex(graph)
expect(definitions.get('1:100')).toBe(component.componentPropertyDefinitions[0])
@@ -127,13 +125,11 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
{ value: 2 },
graph,
blobs,
- undefined,
- new Map([['Inter|Regular', new Uint8Array([1, 2, 3])]]),
- undefined,
- new Map(),
- undefined,
- undefined,
- runtime
+ {
+ fontDigestMap: new Map([['Inter|Regular', new Uint8Array([1, 2, 3])]]),
+ glyphBlobMap: new Map(),
+ runtime
+ }
)
expect(change.derivedTextData?.glyphs).toHaveLength(1)
@@ -193,35 +189,12 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
localIdCounter,
graph,
[],
- nodeIdToGuid,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- propertyIdToGuid
+ { nodeIdToGuid, propertyIdToGuid }
)
- const slotChange = sceneNodeToKiwi(
- slot,
- componentChange.guid,
- 0,
- localIdCounter,
- graph,
- [],
+ const slotChange = sceneNodeToKiwi(slot, componentChange.guid, 0, localIdCounter, graph, [], {
nodeIdToGuid,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
propertyIdToGuid
- )[0]
+ })[0]
expect(componentChange.componentPropDefs?.[0].id).toEqual(
slotChange.componentPropRefs?.[0].defID
@@ -251,16 +224,7 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
localIdCounter,
graph,
[],
- nodeIdToGuid,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- propertyIdToGuid
+ { nodeIdToGuid, propertyIdToGuid }
)
const [buttonChange] = sceneNodeToKiwi(
button,
@@ -269,16 +233,7 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
localIdCounter,
graph,
[],
- nodeIdToGuid,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- propertyIdToGuid
+ { nodeIdToGuid, propertyIdToGuid }
)
expect(buttonChange.componentPropDefs?.[0].initialValue).toEqual({ guidValue: iconChange.guid })
diff --git a/packages/fig/tests/font-features.test.ts b/packages/fig/tests/node-change/font-features.test.ts
similarity index 96%
rename from packages/fig/tests/font-features.test.ts
rename to packages/fig/tests/node-change/font-features.test.ts
index c0f700efb..79e340527 100644
--- a/packages/fig/tests/font-features.test.ts
+++ b/packages/fig/tests/node-change/font-features.test.ts
@@ -1,8 +1,8 @@
import { expect, test } from 'bun:test'
-import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { applyFontFeaturesToKiwi, convertFontFeatures } from '#fig/node-change/font/features'
-import { applyFontFeaturesToKiwi, convertFontFeatures } from '../src/node-change/font/features'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
function apply(features: { tag: string; enabled: boolean }[]) {
const nc: NodeChange = { type: 'TEXT' }
diff --git a/packages/fig/tests/node-change.test.ts b/packages/fig/tests/node-change/index.test.ts
similarity index 99%
rename from packages/fig/tests/node-change.test.ts
rename to packages/fig/tests/node-change/index.test.ts
index 87a1b3358..21c92e759 100644
--- a/packages/fig/tests/node-change.test.ts
+++ b/packages/fig/tests/node-change/index.test.ts
@@ -1,7 +1,5 @@
import { describe, expect, test } from 'bun:test'
-import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'
-
import {
applyStyleRefsToFields,
buildStyleOverrideTable,
@@ -17,7 +15,9 @@ import {
mapTextDecoration,
nodeChangeToProps,
setVariableColorResolver
-} from '../src/node-change'
+} from '#fig/node-change/index'
+
+import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'
describe('@open-pencil/fig NodeChange policy', () => {
test('converts normalized text values', () => {
diff --git a/packages/fig/tests/node-change/instance-geometry.test.ts b/packages/fig/tests/node-change/instance-geometry.test.ts
new file mode 100644
index 000000000..0f2896cd1
--- /dev/null
+++ b/packages/fig/tests/node-change/instance-geometry.test.ts
@@ -0,0 +1,44 @@
+import { expect, test } from 'bun:test'
+
+import type { DerivedSymbolOverride } from '#fig/instance-overrides/types'
+import { snapshotInstanceGeometry } from '#fig/node-change/instance-geometry'
+
+import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../helpers/assert'
+
+function fixture() {
+ const graph = new SceneGraph()
+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id)
+ const source = graph.createNode('RECTANGLE', component.id, { width: 10, height: 20 })
+ const owner = expectDefined(graph.createInstance(component.id, graph.getPages()[0].id))
+ return { graph, source, owner }
+}
+
+test('geometry snapshots merge retained fields without authoring claims or mutating retained data', () => {
+ const { graph, source, owner } = fixture()
+ const guidPath = { guids: [stringToGuid(source.id)] }
+ const retained: DerivedSymbolOverride[] = [
+ { guidPath, fontSize: 12 },
+ { guidPath, size: { x: 1, y: 1 } },
+ { fontSize: 24 }
+ ]
+ const before = structuredClone(retained)
+ const result = snapshotInstanceGeometry(graph, owner, stringToGuid, retained, (node) => ({
+ size: { x: node.width, y: node.height }
+ }))
+ expect(result).toEqual([{ fontSize: 24 }, { guidPath, fontSize: 12, size: { x: 10, y: 20 } }])
+ expect(retained).toEqual(before)
+ expect(owner.instanceOverrides.self.size).toBe(0)
+})
+
+test('geometry snapshots reject ambiguous occurrence addresses', () => {
+ const { graph, source, owner } = fixture()
+ graph.createNode('RECTANGLE', owner.id, { componentId: source.id })
+ expect(() =>
+ snapshotInstanceGeometry(graph, owner, stringToGuid, [], (node) => ({
+ size: { x: node.width, y: node.height }
+ }))
+ ).toThrow('Ambiguous instance geometry address')
+})
diff --git a/packages/fig/tests/source-metadata.test.ts b/packages/fig/tests/source-metadata.test.ts
index 1ab91bf96..bc2eb0447 100644
--- a/packages/fig/tests/source-metadata.test.ts
+++ b/packages/fig/tests/source-metadata.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, test } from 'bun:test'
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { effectiveFigmaRawNodeFields, effectiveFigmaSourcePayload } from '#fig/source-metadata'
-import { effectiveFigmaRawNodeFields, effectiveFigmaSourcePayload } from '../src/source-metadata'
+import { SceneGraph } from '@open-pencil/scene-graph'
describe('@open-pencil/fig source metadata policy', () => {
test('filters only raw fields made stale by normalized edits', () => {
diff --git a/packages/fig/tests/vector-style-fills.test.ts b/packages/fig/tests/vector-style-fills.test.ts
index 4237b2285..f02195a15 100644
--- a/packages/fig/tests/vector-style-fills.test.ts
+++ b/packages/fig/tests/vector-style-fills.test.ts
@@ -1,17 +1,16 @@
import { describe, expect, test } from 'bun:test'
-import type { Paint } from '@open-pencil/kiwi/fig/codec'
-import type { Fill } from '@open-pencil/scene-graph'
-import { SceneGraph } from '@open-pencil/scene-graph'
-import { scaleGeometryPaths } from '@open-pencil/scene-graph/copy'
-
-import { resolveDsdGeometry } from '../src/instance-overrides/derived-symbol-data/geometry'
import {
resolveGeometryPaths,
resolveStyleOverrideFills,
sceneNodeToKiwi,
type StyleOverride
-} from '../src/node-change'
+} from '#fig/node-change/index'
+
+import type { Paint } from '@open-pencil/kiwi/fig/codec'
+import type { Fill } from '@open-pencil/scene-graph'
+import { SceneGraph } from '@open-pencil/scene-graph'
+import { scaleGeometryPaths } from '@open-pencil/scene-graph/copy'
function solidFill(r: number, g: number, b: number): Fill {
return {
@@ -44,66 +43,6 @@ function quadraticCommandsBlob(): Uint8Array {
}
describe('vector geometry style fills', () => {
- test('scales derived zero-height vector networks for dashed instance strokes', () => {
- const graph = new SceneGraph()
- const target = graph.createNode('VECTOR', graph.getPages()[0].id, {
- width: 99,
- height: 0,
- vectorNetwork: {
- vertices: [
- { x: 0, y: 0 },
- { x: 99, y: 0 }
- ],
- segments: [
- {
- start: 0,
- end: 1,
- tangentStart: { x: 0, y: 0 },
- tangentEnd: { x: 0, y: 0 }
- }
- ],
- regions: []
- }
- })
-
- const geometry = resolveDsdGeometry({ size: { x: 421, y: 0 } }, target, [])
-
- expect(geometry.vectorNetwork?.vertices[1]?.x).toBe(421)
- expect(geometry.vectorNetwork?.vertices[1]?.y).toBe(0)
- })
-
- test('scales derived vector networks around their geometry origin', () => {
- const graph = new SceneGraph()
- const target = graph.createNode('VECTOR', graph.getPages()[0].id, {
- width: 10,
- height: 10,
- vectorNetwork: {
- vertices: [
- { x: 5, y: 7 },
- { x: 15, y: 17 }
- ],
- segments: [
- {
- start: 0,
- end: 1,
- tangentStart: { x: 1, y: 2 },
- tangentEnd: { x: 3, y: 4 }
- }
- ],
- regions: []
- }
- })
-
- const geometry = resolveDsdGeometry({ size: { x: 20, y: 30 } }, target, [])
-
- expect(geometry.vectorNetwork?.vertices).toEqual([
- { x: 5, y: 7 },
- { x: 25, y: 37 }
- ])
- expect(geometry.vectorNetwork?.segments[0]?.tangentStart).toEqual({ x: 2, y: 6 })
- expect(geometry.vectorNetwork?.segments[0]?.tangentEnd).toEqual({ x: 6, y: 12 })
- })
-
test('resolves per-path paints without retaining transport style IDs', () => {
const orange: Paint = {
type: 'SOLID',
@@ -130,35 +69,6 @@ describe('vector geometry style fills', () => {
expect(paths[0]).not.toHaveProperty('styleID')
})
- test('resolves style fills from derived instance geometry', () => {
- const graph = new SceneGraph()
- const target = graph.createNode('VECTOR', graph.getPages()[0].id)
- const geometry = resolveDsdGeometry(
- {
- fillGeometry: [{ windingRule: 'NONZERO', commandsBlob: 0, styleID: 3 }],
- vectorData: {
- styleOverrideTable: [
- {
- styleID: 3,
- fillPaints: [
- {
- type: 'SOLID',
- color: { r: 1, g: 0.32, b: 0, a: 1 },
- opacity: 1,
- visible: true
- }
- ]
- }
- ]
- }
- },
- target,
- [moveCommandsBlob(0, 0)]
- )
-
- expect(geometry.fillGeometry?.[0]?.fills?.[0]?.color.g).toBeCloseTo(0.32)
- })
-
test('generates fresh style overrides when serializing current path fills', () => {
const graph = new SceneGraph()
const vector = graph.createNode('VECTOR', graph.getPages()[0].id, {
diff --git a/packages/kiwi/src/schema-runtime/bb.ts b/packages/kiwi/src/schema-runtime/bb.ts
index 63961715d..ab3367773 100644
--- a/packages/kiwi/src/schema-runtime/bb.ts
+++ b/packages/kiwi/src/schema-runtime/bb.ts
@@ -163,6 +163,9 @@ export class ByteBuffer {
}
writeByteArray(value: Uint8Array): void {
+ if (!(value instanceof Uint8Array) && !Array.isArray(value)) {
+ throw new Error('Expected byte array')
+ }
this.writeVarUint(value.length)
let index = this.length
this._growBy(value.length)
diff --git a/packages/kiwi/tests/schema-runtime.test.ts b/packages/kiwi/tests/schema-runtime.test.ts
index 416598869..571fd74ae 100644
--- a/packages/kiwi/tests/schema-runtime.test.ts
+++ b/packages/kiwi/tests/schema-runtime.test.ts
@@ -20,6 +20,16 @@ interface RuntimeMessage {
| RuntimeMessage[]
}
+test('rejects malformed byte fields without corrupting buffer length', () => {
+ const buffer = new ByteBuffer()
+ expect(() => Reflect.apply(buffer.writeByteArray, buffer, [{ 0: 42 }])).toThrow(
+ 'Expected byte array'
+ )
+ expect(buffer.length).toBe(0)
+ buffer.writeByteArray(new Uint8Array([42]))
+ expect(buffer.toUint8Array()).toEqual(new Uint8Array([1, 42]))
+})
+
const schemaText = `
package Example;
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index afdd8d186..24ee69189 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -8,6 +8,8 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice
- Reparenting preserves child world positions; groups preserve them too. Sort children geometrically before creating auto-layout. Consumers such as layer trees must react to reparenting rather than retaining stale child references.
- Use the copy helpers in `packages/scene-graph/src/copy.ts` for nested values (fills, strokes, effects); never hand-copy node properties.
- Instance children map to component children through `componentId`; runtime overrides use the structured `InstanceOverrideState` (`self` and `descendants` maps) in `packages/scene-graph/src/instance-overrides.ts`.
+- A bound numeric field records its unit conversion in `variableBindingScales`; preserve it through clone, copy, and transfer so a binding keeps meaning in its new scope. Core reconciles bindings and layout together in `packages/core/src/layout/variables.ts`, which the editor and the Figma API both call rather than reimplementing.
+- `componentScale` records an occurrence's coordinates relative to its component definition. Shared rescaling lives in `packages/scene-graph/src/scaling/`; Core's Figma API delegates there instead of scaling nodes itself.
- Shared primitives that format packages need live here: color conversion and management under `@open-pencil/scene-graph/color` and text/layout direction under `@open-pencil/scene-graph/text-direction`.
- Vector network types live here; the reverse-engineered `vectorNetworkBlob` codecs live in `packages/core/src/vector/`.
- `packages/scene-graph/src/checkpoint.ts` owns transaction checkpoint recovery, including hierarchy and indexes; Core's atomic tool execution relies on it.
diff --git a/packages/scene-graph/src/buffered-events.ts b/packages/scene-graph/src/buffered-events.ts
new file mode 100644
index 000000000..f6ae570be
--- /dev/null
+++ b/packages/scene-graph/src/buffered-events.ts
@@ -0,0 +1,64 @@
+import { createNanoEvents, type Emitter } from 'nanoevents'
+
+import type { SceneGraphEvents } from './types'
+
+export class CommittedGraphEventError extends AggregateError {
+ readonly committed = true
+
+ constructor(errors: readonly unknown[]) {
+ super(errors, 'Committed graph event delivery failed')
+ this.name = 'CommittedGraphEventError'
+ }
+}
+
+/** Stable emitter identity with synchronous, nestable event buffering. */
+export class BufferedSceneEmitter implements Emitter<SceneGraphEvents> {
+ private readonly delegate = createNanoEvents<SceneGraphEvents>()
+ private readonly buffers: Array<Array<() => void>> = []
+
+ get events(): Emitter<SceneGraphEvents>['events'] {
+ return this.delegate.events
+ }
+
+ set events(events: Emitter<SceneGraphEvents>['events']) {
+ this.delegate.events = events
+ }
+
+ on<K extends keyof SceneGraphEvents>(event: K, listener: SceneGraphEvents[K]) {
+ return this.delegate.on(event, listener)
+ }
+
+ emit<K extends keyof SceneGraphEvents>(event: K, ...args: Parameters<SceneGraphEvents[K]>): void {
+ const buffer = this.buffers.at(-1)
+ if (buffer) buffer.push(() => this.delegate.emit(event, ...args))
+ else this.delegate.emit(event, ...args)
+ }
+
+ /** Buffers events, not mutations. Callers own rollback if the action throws. */
+ batch<T>(action: () => T): T {
+ const pending: Array<() => void> = []
+ this.buffers.push(pending)
+ let result: T
+ try {
+ result = action()
+ } catch (error) {
+ this.buffers.pop()
+ throw error
+ }
+ this.buffers.pop()
+ const outer = this.buffers.at(-1)
+ if (outer) outer.push(...pending)
+ else {
+ const errors: unknown[] = []
+ for (const publish of pending) {
+ try {
+ publish()
+ } catch (error) {
+ errors.push(error)
+ }
+ }
+ if (errors.length) throw new CommittedGraphEventError(errors)
+ }
+ return result
+ }
+}
diff --git a/packages/scene-graph/src/components/properties.ts b/packages/scene-graph/src/components/properties.ts
index 19fc334c9..79bfbba0c 100644
--- a/packages/scene-graph/src/components/properties.ts
+++ b/packages/scene-graph/src/components/properties.ts
@@ -1,5 +1,5 @@
import type { SceneGraph } from '../index'
-import { setInstanceOverride } from '../instance-overrides'
+import { getInstanceOverride, setInstanceOverride } from '../instance-overrides'
import { findInstanceAncestor } from '../instances'
import type {
ComponentPropertyDefinition,
@@ -70,10 +70,22 @@ export function findComponentPropertyTargets(
if (!component) return []
const targets: ComponentPropertyTarget[] = []
const visit = (sourceParent: SceneNode, instanceParent: SceneNode): void => {
- for (const [index, childId] of sourceParent.childIds.entries()) {
+ const bySource = new Map<string, SceneNode>()
+ for (const child of graph.getChildren(instanceParent.id)) {
+ const mapped = getInstanceOverride(
+ instance.instanceOverrides,
+ instance.id,
+ child.id,
+ 'sourceComponentId'
+ )
+ const sourceId = typeof mapped === 'string' ? mapped : child.componentId
+ if (!sourceId) continue
+ if (bySource.has(sourceId)) throw new Error(`Ambiguous component-property target ${sourceId}`)
+ bySource.set(sourceId, child)
+ }
+ for (const childId of sourceParent.childIds) {
const source = graph.getNode(childId)
- const targetId = instanceParent.childIds[index]
- const target = targetId ? graph.getNode(targetId) : undefined
+ const target = bySource.get(childId)
if (!source || !target) continue
const reference = source.componentPropertyReferences.find(
(candidate) => candidate.propertyId === propertyId
diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.ts
index 592a664e3..e1a1368b1 100644
--- a/packages/scene-graph/src/copy.ts
+++ b/packages/scene-graph/src/copy.ts
@@ -240,6 +240,8 @@ export function cloneNodeProps(
...(componentId !== null ? { componentId } : {}),
source: createDefaultSourceMetadata(),
boundVariables: { ...src.boundVariables },
+ variableBindingScales: { ...src.variableBindingScales },
+ variableAssignmentScales: { ...src.variableAssignmentScales },
variableModes: { ...src.variableModes },
instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),
componentPropertyAssignments: { ...src.componentPropertyAssignments },
@@ -251,6 +253,8 @@ export function cloneNodeProps(
...rest,
...(componentId !== null ? { componentId } : {}),
boundVariables: { ...src.boundVariables },
+ variableBindingScales: { ...src.variableBindingScales },
+ variableAssignmentScales: { ...src.variableAssignmentScales },
variableModes: { ...src.variableModes },
instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),
fills: copyOpt(src.fills, (value) => markCopySource(value, copyFills(value))),
diff --git a/packages/scene-graph/src/fields/geometry.ts b/packages/scene-graph/src/fields/geometry.ts
new file mode 100644
index 000000000..c96186057
--- /dev/null
+++ b/packages/scene-graph/src/fields/geometry.ts
@@ -0,0 +1,11 @@
+import type { SceneNode } from '../types'
+
+/** Placement/orientation only; dimensions are a separate geometry contract. */
+export const TRANSFORM_FIELDS = [
+ 'x',
+ 'y',
+ 'rotation',
+ 'flipX',
+ 'flipY'
+] as const satisfies readonly (keyof SceneNode)[]
+export const SIZE_FIELDS = ['width', 'height'] as const satisfies readonly (keyof SceneNode)[]
diff --git a/packages/scene-graph/src/fields/text.ts b/packages/scene-graph/src/fields/text.ts
new file mode 100644
index 000000000..bf83bb0a8
--- /dev/null
+++ b/packages/scene-graph/src/fields/text.ts
@@ -0,0 +1,30 @@
+import type { SceneNode } from '../types'
+
+/** Fields shared by shaping, paragraph measurement, and auto-width invalidation. */
+export const TEXT_METRIC_FIELDS = [
+ 'text',
+ 'fontSize',
+ 'fontFamily',
+ 'fontWeight',
+ 'italic',
+ 'letterSpacing',
+ 'styleRuns',
+ 'fontVariations',
+ 'fontFeatures'
+] as const satisfies readonly (keyof SceneNode)[]
+
+export const TEXT_SHAPING_FIELDS = [
+ ...TEXT_METRIC_FIELDS,
+ 'lineHeight',
+ 'textCase',
+ 'textDirection',
+ 'textAlignHorizontal',
+ 'textAlignVertical'
+] as const satisfies readonly (keyof SceneNode)[]
+
+export const TEXT_LAYOUT_FIELDS = [
+ 'width',
+ 'height',
+ 'textAutoResize',
+ 'maxLines'
+] as const satisfies readonly (keyof SceneNode)[]
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 1d135c278..125147313 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -1,11 +1,18 @@
/* eslint-disable max-lines -- SceneGraph exposes a stable facade over domain modules */
export * from './mutation-impact'
+export * from './variables/bindings'
+export { rescaleNodeTree, scaleNodeChanges } from './scaling'
+import { TRANSFORM_FIELDS, SIZE_FIELDS } from './fields/geometry'
+export { TRANSFORM_FIELDS, SIZE_FIELDS } from './fields/geometry'
+export { TEXT_METRIC_FIELDS, TEXT_SHAPING_FIELDS, TEXT_LAYOUT_FIELDS } from './fields/text'
+export * from './transfer'
export * from './instance-overrides'
export * from './images'
export * from './components/properties'
export * from './copy'
export {
copyInstanceComponentProps,
+ findInstanceAncestor,
hasInstanceOverride,
INSTANCE_SYNC_FIELDS,
INSTANCE_SYNC_PROPS,
@@ -34,9 +41,9 @@ export { default as TransformMatrix } from './matrix'
export type { Mat3 } from './matrix'
export { UndoManager, type UndoEntry, type UndoManagerOptions } from './undo'
-import { createNanoEvents } from 'nanoevents'
-
import { removeStaleBindings } from './bindings'
+export { CommittedGraphEventError } from './buffered-events'
+import { BufferedSceneEmitter } from './buffered-events'
import { cloneNodeProps } from './copy'
import { bindNodeEvents } from './events'
import * as HitTest from './hit-test'
@@ -53,8 +60,6 @@ import { normalizeVectorNetwork } from './vector-network'
export type { GUID, Color, Size, Vector } from './primitives'
export * from './types'
-import type { Emitter } from 'nanoevents'
-
import {
getAbsolutePosition,
getNodeLocalMatrix,
@@ -68,7 +73,6 @@ import type {
EnabledLibraryBinding,
NodeType,
SceneGraphEventHandlers,
- SceneGraphEvents,
SceneNode,
SourceMetadata,
Variable,
@@ -117,7 +121,7 @@ export class SceneGraph {
figSchemaDeflated: Uint8Array | null = null
documentColorSpace: DocumentColorSpace = 'srgb'
enabledLibraries = new Map<string, EnabledLibraryBinding>()
- readonly emitter: Emitter<SceneGraphEvents> = createNanoEvents()
+ readonly emitter = new BufferedSceneEmitter()
private absPosCache = new Map<string, Vector>()
private previewMutationDepth = 0
private previewObservers: NodePreviewObserver[] = []
@@ -252,6 +256,10 @@ export class SceneGraph {
return Variables.resolveNumberVariableForNode(this, nodeId, variableId)
}
+ resolveStringVariableForNode(nodeId: string, variableId: string): string | undefined {
+ return Variables.resolveStringVariableForNode(this, nodeId, variableId)
+ }
+
getVariablesForCollection(collectionId: string): Variable[] {
return Variables.getVariablesForCollection(this, collectionId)
}
@@ -335,6 +343,11 @@ export class SceneGraph {
this.emitter.emit('node:created', node)
return node
}
+ /** Publish synchronous graph events only after the supplied mutation succeeds. */
+ withBufferedEvents<T>(action: () => T): T {
+ return this.emitter.batch(action)
+ }
+
createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {
const node = createDefaultNode(() => this.generateNodeId(), type, overrides)
this.nodes.get(parentId)?.childIds.push(node.id)
@@ -357,13 +370,8 @@ export class SceneGraph {
static GLYPH_AFFECTING_KEYS: ReadonlySet<string> = GLYPH_AFFECTING_KEYS
static LAYOUT_AFFECTING_KEYS: ReadonlySet<string> = new Set([
- 'x',
- 'y',
- 'width',
- 'height',
- 'rotation',
- 'flipX',
- 'flipY',
+ ...TRANSFORM_FIELDS,
+ ...SIZE_FIELDS,
'layoutMode',
'layoutDirection',
'itemSpacing',
@@ -488,7 +496,7 @@ export class SceneGraph {
}
}
if (node.type === 'TEXT') invalidateTextCaches(node, changes)
- if (this.sourceMetadataPreservationDepth === 0) {
+ if (this.sourceMetadataPreservationDepth === 0 && !this.isApplyingLayout) {
markSourceFieldsEdited(node, Object.keys(changes))
}
if (changes.vectorNetwork) {
diff --git a/packages/scene-graph/src/instance-overrides.ts b/packages/scene-graph/src/instance-overrides.ts
index a10552946..8b880a5f7 100644
--- a/packages/scene-graph/src/instance-overrides.ts
+++ b/packages/scene-graph/src/instance-overrides.ts
@@ -89,6 +89,33 @@ export function cloneInstanceOverrideState(state: InstanceOverrideState): Instan
}
}
+export interface InstanceOverrideReferenceMapper {
+ node: (id: string) => string
+ variable: (id: string) => string
+}
+
+/** Remap runtime identities only; ordinary strings and source-format payloads stay opaque. */
+export function remapInstanceOverrideState(
+ state: InstanceOverrideState,
+ references: InstanceOverrideReferenceMapper
+): InstanceOverrideState {
+ const remapValue = (field: string, value: unknown): unknown => {
+ if (typeof value !== 'string') return structuredClone(value)
+ if (field === 'componentId' || field === 'sourceComponentId') return references.node(value)
+ if (field.startsWith('boundVariables/')) return references.variable(value)
+ return value
+ }
+ const fields = (entries: ReadonlyMap<string, unknown>) =>
+ new Map([...entries].map(([field, value]) => [field, remapValue(field, value)]))
+ const descendants = new Map<string, Map<string, unknown>>()
+ for (const [id, entries] of state.descendants) {
+ const mapped = references.node(id)
+ if (descendants.has(mapped)) throw new Error(`Duplicate remapped override target ${mapped}`)
+ descendants.set(mapped, fields(entries))
+ }
+ return { self: fields(state.self), descendants }
+}
+
export function getInstanceOverride(
state: InstanceOverrideState,
instanceId: string,
diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.ts
index 5466a2f8e..cc8d4ee29 100644
--- a/packages/scene-graph/src/instances.ts
+++ b/packages/scene-graph/src/instances.ts
@@ -1,311 +1,30 @@
import type { SceneGraph, SceneNode } from './'
-import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from './copy'
import type { NodeCloneMode } from './copy'
import {
clearInstanceOverrides,
getInstanceOverride,
hasInstanceOverride as hasNodeInstanceOverride,
- setInstanceOverride,
- type InstanceOverrideState
+ setInstanceOverride
} from './instance-overrides'
+import { INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS } from './instances/fields'
+import {
+ bindingProtection,
+ cloneChildrenWithMapping,
+ copyProp,
+ enclosingInstanceOverrideFields,
+ isProtectedSyncField,
+ sourceInTargetCoordinates,
+ syncBindingFields,
+ syncChildren,
+ updateSyncedProps
+} from './instances/sync'
export type { NodeCloneMode } from './copy'
-
-export const INSTANCE_SYNC_TEXT_PROPS = [
- 'name',
- 'text',
- 'fontSize',
- 'fontWeight',
- 'fontFamily',
- 'textDirection'
-] as const
-
-export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [
- 'width',
- 'height',
- 'minWidth',
- 'maxWidth',
- 'minHeight',
- 'maxHeight',
- 'fills',
- 'strokes',
- 'effects',
- 'opacity',
- 'cornerRadius',
- 'topLeftRadius',
- 'topRightRadius',
- 'bottomRightRadius',
- 'bottomLeftRadius',
- 'independentCorners',
- 'layoutMode',
- 'layoutDirection',
- 'layoutWrap',
- 'primaryAxisAlign',
- 'counterAxisAlign',
- 'primaryAxisSizing',
- 'counterAxisSizing',
- 'itemSpacing',
- 'counterAxisSpacing',
- 'paddingTop',
- 'paddingRight',
- 'paddingBottom',
- 'paddingLeft',
- 'gridTemplateColumns',
- 'gridTemplateRows',
- 'gridColumnGap',
- 'gridRowGap',
- 'gridPosition',
- 'clipsContent',
- 'independentStrokeWeights',
- 'borderTopWeight',
- 'borderRightWeight',
- 'borderBottomWeight',
- 'borderLeftWeight',
- 'boundVariables',
- 'variableModes'
-]
-
-export const INSTANCE_SYNC_FIELDS = [...INSTANCE_SYNC_PROPS, ...INSTANCE_SYNC_TEXT_PROPS] as const
-
-function setSceneProp<K extends keyof SceneNode>(
- target: Partial<SceneNode>,
- key: K,
- value: SceneNode[K]
-): void {
- target[key] = value
-}
-
-function copyProp(
- target: Partial<SceneNode> | SceneNode,
- source: SceneNode,
- key: keyof SceneNode
-): void {
- if (key === 'fills') {
- setSceneProp(target, key, copyFills(source.fills))
- } else if (key === 'strokes') {
- setSceneProp(target, key, copyStrokes(source.strokes))
- } else if (key === 'effects') {
- setSceneProp(target, key, copyEffects(source.effects))
- } else if (key === 'styleRuns') {
- setSceneProp(target, key, copyStyleRuns(source.styleRuns))
- } else if (key === 'boundVariables') {
- // Shallow copy the binding map — values are variable IDs (strings), not objects
- setSceneProp(target, key, { ...source.boundVariables })
- } else if (key === 'variableModes') {
- setSceneProp(target, key, { ...source.variableModes })
- } else if (key === 'gridPosition') {
- // Shallow copy the grid position object — all fields are primitives
- setSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null)
- } else {
- const value = source[key]
- setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value)
- }
-}
-
-function cloneChildrenWithMapping(
- graph: SceneGraph,
- sourceParentId: string,
- destParentId: string,
- mode: NodeCloneMode = 'deep'
-): void {
- // Guard against cloning a subtree into itself or its own descendant. Without this,
- // a self-referential or cyclic component (e.g. an INSTANCE whose componentId points
- // to an ancestor) causes unbounded recursion and eventual stack overflow / OOM.
- if (sourceParentId === destParentId || graph.isDescendant(destParentId, sourceParentId)) return
-
- const sourceParent = graph.nodes.get(sourceParentId)
- if (!sourceParent) return
-
- for (const childId of sourceParent.childIds) {
- const src = graph.nodes.get(childId)
- if (!src) continue
-
- const clone = graph.createNode(src.type, destParentId, cloneNodeProps(src, childId, mode))
-
- if (src.childIds.length > 0) {
- cloneChildrenWithMapping(graph, childId, clone.id, mode)
- }
- }
-}
-
-function linkMatchedChild(
- overrides: InstanceOverrideState,
- instParentId: string,
- instChild: SceneNode,
- compChildId: string
-): void {
- if (instChild.type === 'INSTANCE') {
- setInstanceOverride(overrides, instParentId, instChild.id, 'sourceComponentId', compChildId)
- } else {
- instChild.componentId = compChildId
- }
-}
-
-function matchFallbackChildren(
- graph: SceneGraph,
- compParent: SceneNode,
- instParent: SceneNode,
- instParentId: string,
- overrides: InstanceOverrideState,
- instChildMap: Map<string, SceneNode>,
- usedInstChildIds: Set<string>
-): void {
- const fallbackByType = new Map<SceneNode['type'], Map<string, SceneNode[]>>()
- const remainingCandidateCount = new Map<SceneNode['type'], number>()
- const unmatchedComponentCount = new Map<SceneNode['type'], number>()
- for (const compChildId of compParent.childIds) {
- if (instChildMap.has(compChildId)) continue
- const child = graph.nodes.get(compChildId)
- if (child) {
- unmatchedComponentCount.set(child.type, (unmatchedComponentCount.get(child.type) ?? 0) + 1)
- }
- }
- for (const childId of instParent.childIds) {
- const child = graph.nodes.get(childId)
- if (!child || usedInstChildIds.has(child.id)) continue
- remainingCandidateCount.set(child.type, (remainingCandidateCount.get(child.type) ?? 0) + 1)
- let byName = fallbackByType.get(child.type)
- if (!byName) {
- byName = new Map()
- fallbackByType.set(child.type, byName)
- }
- const queue = byName.get(child.name)
- if (queue) queue.push(child)
- else byName.set(child.name, [child])
- }
-
- // Match by name and type with FIFO queues to preserve sibling order in linear time.
- for (const compChildId of compParent.childIds) {
- if (instChildMap.has(compChildId)) continue
- const compChild = graph.nodes.get(compChildId)
- if (!compChild) continue
- const candidatesByName = fallbackByType.get(compChild.type)
- const candidateCount = remainingCandidateCount.get(compChild.type) ?? 0
- if (candidateCount > (unmatchedComponentCount.get(compChild.type) ?? 0)) continue
- const match = candidatesByName?.get(compChild.name)?.shift()
- if (!match) continue
- remainingCandidateCount.set(compChild.type, candidateCount - 1)
- instChildMap.set(compChildId, match)
- usedInstChildIds.add(match.id)
- linkMatchedChild(overrides, instParentId, match, compChildId)
- }
-}
-
-function sortInstanceChildren(
- graph: SceneGraph,
- instParent: SceneNode,
- instParentId: string,
- compChildOrder: string[],
- overrides: InstanceOverrideState
-): void {
- const orderMap = new Map<string, number>()
- for (let i = 0; i < compChildOrder.length; i++) orderMap.set(compChildOrder[i], i)
-
- const ranks = new Map<string, number>()
- for (let index = 0; index < instParent.childIds.length; index++) {
- const childId = instParent.childIds[index]
- const node = graph.nodes.get(childId)
- const source = node
- ? getInstanceOverride(overrides, instParentId, node.id, 'sourceComponentId')
- : undefined
- const mapped = typeof source === 'string' ? source : node?.componentId
- const componentIndex = mapped ? orderMap.get(mapped) : undefined
- ranks.set(childId, componentIndex ?? compChildOrder.length + index)
- }
- instParent.childIds.sort((left, right) => (ranks.get(left) ?? 0) - (ranks.get(right) ?? 0))
-}
-
-/** True when syncing `compParentId` into `instParentId` would form a cycle. */
-function isCyclicSync(graph: SceneGraph, compParentId: string, instParentId: string): boolean {
- return compParentId === instParentId || graph.isDescendant(instParentId, compParentId)
-}
-
-function syncChildren(
- graph: SceneGraph,
- compParentId: string,
- instParentId: string,
- overrides: InstanceOverrideState
-): void {
- // Guard against cyclic sync: if the instance parent is inside the component's own
- // subtree, syncing would clone the component into itself — a self-referential cycle
- // that causes unbounded recursion and OOM.
- if (isCyclicSync(graph, compParentId, instParentId)) return
-
- const compParent = graph.nodes.get(compParentId)
- const instParent = graph.nodes.get(instParentId)
- if (!compParent || !instParent) return
-
- const instChildMap = new Map<string, SceneNode>()
- const usedInstChildIds = new Set<string>()
- const compChildIdSet = new Set(compParent.childIds)
-
- // Pass 1: Direct matching via sourceComponentId or componentId
- for (const childId of instParent.childIds) {
- const child = graph.nodes.get(childId)
- if (!child) continue
- const sourceComponentId = getInstanceOverride(
- overrides,
- instParentId,
- child.id,
- 'sourceComponentId'
- )
-
- const mappedComponentId =
- typeof sourceComponentId === 'string' ? sourceComponentId : child.componentId
- if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {
- instChildMap.set(mappedComponentId, child)
- usedInstChildIds.add(child.id)
- }
- }
-
- // Pass 2: Fallback matching for unmatched children (e.g. from Figma imports)
- matchFallbackChildren(
- graph,
- compParent,
- instParent,
- instParentId,
- overrides,
- instChildMap,
- usedInstChildIds
- )
-
- // Pass 3: Clone only genuinely missing component children
- for (const compChildId of compParent.childIds) {
- if (!instChildMap.has(compChildId)) {
- const src = graph.nodes.get(compChildId)
- if (!src) continue
- const clone = graph.createNode(src.type, instParentId, cloneNodeProps(src, compChildId))
- if (src.childIds.length > 0) {
- cloneChildrenWithMapping(graph, compChildId, clone.id)
- }
- instChildMap.set(compChildId, clone)
- usedInstChildIds.add(clone.id)
- }
- }
-
- // Pass 4: Synchronize properties and recurse
- for (const compChildId of compParent.childIds) {
- const compChild = graph.nodes.get(compChildId)
- const instChild = instChildMap.get(compChildId)
- if (!compChild || !instChild) continue
-
- for (const key of INSTANCE_SYNC_FIELDS) {
- if (hasNodeInstanceOverride(overrides, instParentId, instChild.id, key)) continue
-
- copyProp(instChild, compChild, key)
- }
-
- if (
- compChild.childIds.length > 0 &&
- !hasNodeInstanceOverride(overrides, instParentId, instChild.id, 'componentId')
- ) {
- syncChildren(graph, compChildId, instChild.id, overrides)
- }
- }
-
- // Pass 5: Sort instance children to match component child order
- sortInstanceChildren(graph, instParent, instParentId, compParent.childIds, overrides)
-}
+export {
+ INSTANCE_SYNC_FIELDS,
+ INSTANCE_SYNC_PROPS,
+ INSTANCE_SYNC_TEXT_PROPS
+} from './instances/fields'
export function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {
const props: Partial<SceneNode> = {}
@@ -347,6 +66,33 @@ export function populateInstanceChildren(
cloneChildrenWithMapping(graph, componentId, instanceId, mode)
}
+/**
+ * A nested instance's link to the enclosing component's record is its `componentId` when it
+ * was populated by cloning. A swap replaces that field, so keep the correspondence as the
+ * owner's `sourceComponentId` override and record the swap itself; materialized documents
+ * already carry the correspondence and only gain the swap.
+ */
+function recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: string): void {
+ const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined
+ if (!owner) return
+ const existing = getInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ instance.id,
+ 'sourceComponentId'
+ )
+ if (typeof existing !== 'string' && instance.componentId)
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ instance.id,
+ 'sourceComponentId',
+ instance.componentId
+ )
+ setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, 'componentId', componentId)
+ graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })
+}
+
export function swapInstanceComponent(
graph: SceneGraph,
instanceId: string,
@@ -357,10 +103,12 @@ export function swapInstanceComponent(
if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return
const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined
+ recordNestedSwap(graph, instance, componentId)
const updates: Partial<SceneNode> = { componentId }
+ const source = sourceInTargetCoordinates(component, instance.componentScale)
for (const key of INSTANCE_SYNC_PROPS) {
if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key)) continue
- copyProp(updates, component, key)
+ copyProp(updates, source, key)
}
if (!previousComponent || instance.name === previousComponent.name) updates.name = component.name
@@ -385,11 +133,18 @@ export function syncInstances(graph: SceneGraph, componentId: string): void {
syncing.add(componentId)
try {
for (const instance of getInstances(graph, componentId)) {
+ const enclosing = enclosingInstanceOverrideFields(graph, instance)
+ enclosing.push(new Set(instance.instanceOverrides.self.keys()))
+ const protectedField = bindingProtection(enclosing)
+ const source = sourceInTargetCoordinates(component, instance.componentScale)
+ const updates: Partial<SceneNode> = {}
+ syncBindingFields(instance, source, updates, protectedField)
for (const key of INSTANCE_SYNC_PROPS) {
- if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key))
- continue
- copyProp(instance, component, key)
+ if (key === 'boundVariables') continue
+ if (isProtectedSyncField(instance, key, protectedField)) continue
+ copyProp(updates, source, key)
}
+ updateSyncedProps(graph, instance, updates)
syncChildren(graph, component.id, instance.id, instance.instanceOverrides)
}
} finally {
@@ -444,22 +199,6 @@ export function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: st
return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
}
-/*
- * syncInstances) won't clobber them, and — if `nodeId` sits inside an INSTANCE —
- * so the .fig exporter knows to write the diff out as a symbol override. A no-op
- * for fields outside INSTANCE_SYNC_PROPS or nodes with no INSTANCE ancestor.
- */
-export function recordInstanceOverrideValue(
- graph: SceneGraph,
- nodeId: string,
- field: string,
- value: unknown
-): void {
- const instance = findInstanceAncestor(graph, nodeId)
- if (!instance) return
- setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field, value)
- graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
-}
export function recordInstanceOverride(
graph: SceneGraph,
nodeId: string,
diff --git a/packages/scene-graph/src/instances/fields.ts b/packages/scene-graph/src/instances/fields.ts
new file mode 100644
index 000000000..cf392b061
--- /dev/null
+++ b/packages/scene-graph/src/instances/fields.ts
@@ -0,0 +1,67 @@
+import type { SceneNode } from '../'
+
+export const INSTANCE_SYNC_TEXT_PROPS = [
+ 'name',
+ 'text',
+ 'fontSize',
+ 'fontWeight',
+ 'fontFamily',
+ 'textDirection'
+] as const
+
+export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [
+ 'width',
+ 'height',
+ 'minWidth',
+ 'maxWidth',
+ 'minHeight',
+ 'maxHeight',
+ 'fills',
+ 'strokes',
+ 'effects',
+ 'opacity',
+ 'cornerRadius',
+ 'topLeftRadius',
+ 'topRightRadius',
+ 'bottomRightRadius',
+ 'bottomLeftRadius',
+ 'independentCorners',
+ 'layoutMode',
+ 'layoutDirection',
+ 'layoutWrap',
+ 'primaryAxisAlign',
+ 'counterAxisAlign',
+ 'primaryAxisSizing',
+ 'counterAxisSizing',
+ 'itemSpacing',
+ 'counterAxisSpacing',
+ 'paddingTop',
+ 'paddingRight',
+ 'paddingBottom',
+ 'paddingLeft',
+ 'gridTemplateColumns',
+ 'gridTemplateRows',
+ 'gridColumnGap',
+ 'gridRowGap',
+ 'gridPosition',
+ 'clipsContent',
+ 'independentStrokeWeights',
+ 'borderTopWeight',
+ 'borderRightWeight',
+ 'borderBottomWeight',
+ 'borderLeftWeight',
+ 'boundVariables',
+ 'variableModes',
+ // Applied shared styles follow the component unless an instance overrides them.
+ 'fillStyleId',
+ 'strokeStyleId',
+ 'textStyleId',
+ 'effectStyleId',
+ 'gridStyleId'
+]
+
+export const INSTANCE_SYNC_FIELDS = [
+ ...INSTANCE_SYNC_PROPS,
+ ...INSTANCE_SYNC_TEXT_PROPS,
+ 'visible'
+] as const
diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.ts
new file mode 100644
index 000000000..8075b215c
--- /dev/null
+++ b/packages/scene-graph/src/instances/sync.ts
@@ -0,0 +1,393 @@
+// Child cloning and property synchronization shared by instance creation, swap, and sync.
+import { isEqual } from 'es-toolkit/predicate'
+
+import type { SceneGraph, SceneNode } from '../'
+import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from '../copy'
+import type { NodeCloneMode } from '../copy'
+import {
+ getInstanceOverride,
+ hasInstanceOverride as hasNodeInstanceOverride,
+ setInstanceOverride,
+ type InstanceOverrideState
+} from '../instance-overrides'
+import { scaleNodeChanges } from '../scaling/node'
+import { scaleVariableBindingUnits } from '../variables/units'
+import { INSTANCE_SYNC_FIELDS } from './fields'
+
+function setSceneProp<K extends keyof SceneNode>(
+ target: Partial<SceneNode>,
+ key: K,
+ value: SceneNode[K]
+): void {
+ target[key] = value
+}
+
+export function copyProp(
+ target: Partial<SceneNode> | SceneNode,
+ source: SceneNode,
+ key: keyof SceneNode
+): void {
+ if (key === 'fills') {
+ setSceneProp(target, key, copyFills(source.fills))
+ } else if (key === 'strokes') {
+ setSceneProp(target, key, copyStrokes(source.strokes))
+ } else if (key === 'effects') {
+ setSceneProp(target, key, copyEffects(source.effects))
+ } else if (key === 'styleRuns') {
+ setSceneProp(target, key, copyStyleRuns(source.styleRuns))
+ } else if (key === 'boundVariables') {
+ // Shallow copy the binding map — values are variable IDs (strings), not objects
+ setSceneProp(target, key, { ...source.boundVariables })
+ setSceneProp(target, 'variableBindingScales', { ...source.variableBindingScales })
+ } else if (key === 'variableModes') {
+ setSceneProp(target, key, { ...source.variableModes })
+ } else if (key === 'gridPosition') {
+ // Shallow copy the grid position object — all fields are primitives
+ setSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null)
+ } else {
+ const value = source[key]
+ setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value)
+ }
+}
+
+export function bindingProtection(scopes: ReadonlySet<string>[]): (field: string) => boolean {
+ const fields = new Set<string>()
+ for (const scope of scopes) {
+ const perField = [...scope].some((field) => field.startsWith('boundVariables/'))
+ for (const field of scope) {
+ if (field !== 'boundVariables' || !perField) fields.add(field)
+ }
+ }
+ return (field) => fields.has(field)
+}
+
+export function syncBindingFields(
+ target: SceneNode,
+ source: SceneNode,
+ updates: Partial<SceneNode>,
+ protectedField: (field: string) => boolean
+): void {
+ if (protectedField('boundVariables')) return
+ const bindings = { ...source.boundVariables }
+ const scales = { ...source.variableBindingScales }
+ for (const field of new Set([
+ ...Object.keys(source.boundVariables),
+ ...Object.keys(target.boundVariables),
+ ...Object.keys(target.variableBindingScales)
+ ])) {
+ if (!protectedField(`boundVariables/${field}`)) continue
+ if (!Object.hasOwn(target.boundVariables, field)) Reflect.deleteProperty(bindings, field)
+ else bindings[field] = target.boundVariables[field]
+ if (target.variableBindingScales[field] === undefined) Reflect.deleteProperty(scales, field)
+ else scales[field] = target.variableBindingScales[field]
+ }
+ updates.boundVariables = bindings
+ updates.variableBindingScales = scales
+}
+
+export function isProtectedSyncField(
+ node: SceneNode,
+ key: string,
+ protectedField: (field: string) => boolean
+): boolean {
+ return (
+ protectedField(key) ||
+ (key in node.boundVariables &&
+ (protectedField('boundVariables') || protectedField(`boundVariables/${key}`)))
+ )
+}
+
+export function sourceInTargetCoordinates(source: SceneNode, targetScale: number): SceneNode {
+ const factor = targetScale / source.componentScale
+ if (!Number.isFinite(factor) || factor <= 0) throw new Error('Invalid component coordinate scale')
+ if (factor === 1) return source
+ return {
+ ...source,
+ ...scaleNodeChanges(source, factor, true),
+ ...scaleVariableBindingUnits(source, factor)
+ }
+}
+
+export function updateSyncedProps(
+ graph: SceneGraph,
+ target: SceneNode,
+ updates: Partial<SceneNode>
+): void {
+ const changed = Object.fromEntries(
+ Object.entries(updates).filter(
+ ([key, value]) => !isEqual(target[key as keyof SceneNode], value)
+ )
+ ) as Partial<SceneNode>
+ if (Object.keys(changed).length) graph.updateNode(target.id, changed)
+}
+
+function cloneChildInCoordinates(
+ graph: SceneGraph,
+ src: SceneNode,
+ sourceParent: SceneNode,
+ targetParent: SceneNode,
+ mode: NodeCloneMode = 'deep'
+): SceneNode {
+ const componentScale =
+ (src.componentScale * targetParent.componentScale) / sourceParent.componentScale
+ return graph.createNode(src.type, targetParent.id, {
+ ...cloneNodeProps(sourceInTargetCoordinates(src, componentScale), src.id, mode),
+ componentScale
+ })
+}
+
+export function cloneChildrenWithMapping(
+ graph: SceneGraph,
+ sourceParentId: string,
+ destParentId: string,
+ mode: NodeCloneMode = 'deep'
+): void {
+ // Guard against cloning a subtree into itself or its own descendant. Without this,
+ // a self-referential or cyclic component (e.g. an INSTANCE whose componentId points
+ // to an ancestor) causes unbounded recursion and eventual stack overflow / OOM.
+ if (sourceParentId === destParentId || graph.isDescendant(destParentId, sourceParentId)) return
+
+ const sourceParent = graph.nodes.get(sourceParentId)
+ const targetParent = graph.nodes.get(destParentId)
+ if (!sourceParent || !targetParent) return
+
+ for (const childId of sourceParent.childIds) {
+ const src = graph.nodes.get(childId)
+ if (!src) continue
+
+ const clone = cloneChildInCoordinates(graph, src, sourceParent, targetParent, mode)
+
+ if (src.childIds.length > 0) {
+ cloneChildrenWithMapping(graph, childId, clone.id, mode)
+ }
+ }
+}
+
+export function enclosingInstanceOverrideFields(graph: SceneGraph, node: SceneNode): Set<string>[] {
+ const fields: Set<string>[] = []
+ let parent = node.parentId ? graph.nodes.get(node.parentId) : undefined
+ while (parent) {
+ if (parent.type === 'INSTANCE') {
+ fields.push(new Set(parent.instanceOverrides.descendants.get(node.id)?.keys()))
+ }
+ parent = parent.parentId ? graph.nodes.get(parent.parentId) : undefined
+ }
+ return fields
+}
+
+function childBindingProtection(
+ graph: SceneGraph,
+ child: SceneNode,
+ overrides: InstanceOverrideState
+) {
+ const fields = enclosingInstanceOverrideFields(graph, child)
+ fields.push(new Set(overrides.descendants.get(child.id)?.keys()))
+ return bindingProtection(fields)
+}
+
+function linkMatchedChild(
+ overrides: InstanceOverrideState,
+ instParentId: string,
+ instChild: SceneNode,
+ compChildId: string
+): void {
+ if (instChild.type === 'INSTANCE') {
+ setInstanceOverride(overrides, instParentId, instChild.id, 'sourceComponentId', compChildId)
+ } else {
+ instChild.componentId = compChildId
+ }
+}
+
+function matchFallbackChildren(
+ graph: SceneGraph,
+ compParent: SceneNode,
+ instParent: SceneNode,
+ instParentId: string,
+ overrides: InstanceOverrideState,
+ instChildMap: Map<string, SceneNode>,
+ usedInstChildIds: Set<string>
+): void {
+ const fallbackByType = new Map<SceneNode['type'], Map<string, SceneNode[]>>()
+ const remainingCandidateCount = new Map<SceneNode['type'], number>()
+ const unmatchedComponentCount = new Map<SceneNode['type'], number>()
+ for (const compChildId of compParent.childIds) {
+ if (instChildMap.has(compChildId)) continue
+ const child = graph.nodes.get(compChildId)
+ if (child) {
+ unmatchedComponentCount.set(child.type, (unmatchedComponentCount.get(child.type) ?? 0) + 1)
+ }
+ }
+ for (const childId of instParent.childIds) {
+ const child = graph.nodes.get(childId)
+ if (!child || usedInstChildIds.has(child.id)) continue
+ remainingCandidateCount.set(child.type, (remainingCandidateCount.get(child.type) ?? 0) + 1)
+ let byName = fallbackByType.get(child.type)
+ if (!byName) {
+ byName = new Map()
+ fallbackByType.set(child.type, byName)
+ }
+ const queue = byName.get(child.name)
+ if (queue) queue.push(child)
+ else byName.set(child.name, [child])
+ }
+
+ // Match by name and type with FIFO queues to preserve sibling order in linear time.
+ for (const compChildId of compParent.childIds) {
+ if (instChildMap.has(compChildId)) continue
+ const compChild = graph.nodes.get(compChildId)
+ if (!compChild) continue
+ const candidatesByName = fallbackByType.get(compChild.type)
+ const candidateCount = remainingCandidateCount.get(compChild.type) ?? 0
+ if (candidateCount > (unmatchedComponentCount.get(compChild.type) ?? 0)) continue
+ const match = candidatesByName?.get(compChild.name)?.shift()
+ if (!match) continue
+ remainingCandidateCount.set(compChild.type, candidateCount - 1)
+ instChildMap.set(compChildId, match)
+ usedInstChildIds.add(match.id)
+ linkMatchedChild(overrides, instParentId, match, compChildId)
+ }
+}
+
+function sortInstanceChildren(
+ graph: SceneGraph,
+ instParent: SceneNode,
+ instParentId: string,
+ compChildOrder: string[],
+ overrides: InstanceOverrideState
+): void {
+ const orderMap = new Map<string, number>()
+ for (let i = 0; i < compChildOrder.length; i++) orderMap.set(compChildOrder[i], i)
+
+ const ranks = new Map<string, number>()
+ for (let index = 0; index < instParent.childIds.length; index++) {
+ const childId = instParent.childIds[index]
+ const node = graph.nodes.get(childId)
+ const source = node
+ ? getInstanceOverride(overrides, instParentId, node.id, 'sourceComponentId')
+ : undefined
+ const mapped = typeof source === 'string' ? source : node?.componentId
+ const componentIndex = mapped ? orderMap.get(mapped) : undefined
+ ranks.set(childId, componentIndex ?? compChildOrder.length + index)
+ }
+ instParent.childIds.sort((left, right) => (ranks.get(left) ?? 0) - (ranks.get(right) ?? 0))
+}
+
+/** True when syncing `compParentId` into `instParentId` would form a cycle. */
+function isCyclicSync(graph: SceneGraph, compParentId: string, instParentId: string): boolean {
+ return compParentId === instParentId || graph.isDescendant(instParentId, compParentId)
+}
+
+/** Children already linked to a component child by sourceComponentId or componentId. */
+function matchLinkedChildren(
+ graph: SceneGraph,
+ instParent: SceneNode,
+ instParentId: string,
+ overrides: InstanceOverrideState,
+ compChildIdSet: ReadonlySet<string>,
+ instChildMap: Map<string, SceneNode>,
+ usedInstChildIds: Set<string>
+): void {
+ for (const childId of instParent.childIds) {
+ const child = graph.nodes.get(childId)
+ if (!child) continue
+ const sourceComponentId = getInstanceOverride(
+ overrides,
+ instParentId,
+ child.id,
+ 'sourceComponentId'
+ )
+ const mappedComponentId =
+ typeof sourceComponentId === 'string' ? sourceComponentId : child.componentId
+ if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {
+ instChildMap.set(mappedComponentId, child)
+ usedInstChildIds.add(child.id)
+ }
+ }
+}
+
+export function syncChildren(
+ graph: SceneGraph,
+ compParentId: string,
+ instParentId: string,
+ overrides: InstanceOverrideState
+): void {
+ // Guard against cyclic sync: if the instance parent is inside the component's own
+ // subtree, syncing would clone the component into itself — a self-referential cycle
+ // that causes unbounded recursion and OOM.
+ if (isCyclicSync(graph, compParentId, instParentId)) return
+
+ const compParent = graph.nodes.get(compParentId)
+ const instParent = graph.nodes.get(instParentId)
+ if (!compParent || !instParent) return
+
+ const instChildMap = new Map<string, SceneNode>()
+ const usedInstChildIds = new Set<string>()
+ const compChildIdSet = new Set(compParent.childIds)
+
+ // Pass 1: Direct matching via sourceComponentId or componentId
+ matchLinkedChildren(
+ graph,
+ instParent,
+ instParentId,
+ overrides,
+ compChildIdSet,
+ instChildMap,
+ usedInstChildIds
+ )
+
+ // Pass 2: Fallback matching for unmatched children (e.g. from Figma imports)
+ matchFallbackChildren(
+ graph,
+ compParent,
+ instParent,
+ instParentId,
+ overrides,
+ instChildMap,
+ usedInstChildIds
+ )
+
+ // Pass 3: Clone only genuinely missing component children
+ for (const compChildId of compParent.childIds) {
+ if (!instChildMap.has(compChildId)) {
+ const src = graph.nodes.get(compChildId)
+ if (!src) continue
+ const clone = cloneChildInCoordinates(graph, src, compParent, instParent)
+ if (src.childIds.length > 0) {
+ cloneChildrenWithMapping(graph, compChildId, clone.id)
+ }
+ instChildMap.set(compChildId, clone)
+ usedInstChildIds.add(clone.id)
+ }
+ }
+
+ // Pass 4: Synchronize properties and recurse
+ for (const compChildId of compParent.childIds) {
+ const compChild = graph.nodes.get(compChildId)
+ const instChild = instChildMap.get(compChildId)
+ if (!compChild || !instChild) continue
+
+ const protectedField = childBindingProtection(graph, instChild, overrides)
+ const componentScale =
+ (compChild.componentScale * instParent.componentScale) / compParent.componentScale
+ const source = sourceInTargetCoordinates(compChild, componentScale)
+ const updates: Partial<SceneNode> = { componentScale }
+ syncBindingFields(instChild, source, updates, protectedField)
+ for (const key of INSTANCE_SYNC_FIELDS) {
+ if (key === 'boundVariables') continue
+ if (isProtectedSyncField(instChild, key, protectedField)) continue
+
+ copyProp(updates, source, key)
+ }
+ updateSyncedProps(graph, instChild, updates)
+
+ if (
+ compChild.childIds.length > 0 &&
+ !hasNodeInstanceOverride(overrides, instParentId, instChild.id, 'componentId')
+ ) {
+ syncChildren(graph, compChildId, instChild.id, overrides)
+ }
+ }
+
+ // Pass 5: Sort instance children to match component child order
+ sortInstanceChildren(graph, instParent, instParentId, compParent.childIds, overrides)
+}
diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.ts
index 6f1291693..f7abe2bd3 100644
--- a/packages/scene-graph/src/node-defaults.ts
+++ b/packages/scene-graph/src/node-defaults.ts
@@ -159,6 +159,9 @@ export function createDefaultNode(
symbolLinks: [],
variantPropSpecs: [],
boundVariables: {},
+ variableBindingScales: {},
+ variableAssignmentScales: {},
+ componentScale: 1,
variableModes: {},
exportSettings: [],
pluginData: [],
diff --git a/packages/scene-graph/src/scaling/index.ts b/packages/scene-graph/src/scaling/index.ts
new file mode 100644
index 000000000..900216579
--- /dev/null
+++ b/packages/scene-graph/src/scaling/index.ts
@@ -0,0 +1,2 @@
+export { scaleNodeChanges } from './node'
+export { rescaleNodeTree } from './tree'
diff --git a/packages/core/src/figma-api/rescale.ts b/packages/scene-graph/src/scaling/node.ts
similarity index 80%
rename from packages/core/src/figma-api/rescale.ts
rename to packages/scene-graph/src/scaling/node.ts
index 24fbf16d5..5b1b66b33 100644
--- a/packages/core/src/figma-api/rescale.ts
+++ b/packages/scene-graph/src/scaling/node.ts
@@ -1,32 +1,14 @@
+import { scaleGeometryPaths } from '../copy'
import {
- cloneVectorNetwork,
- scaleGeometryPaths,
type Effect,
type Fill,
type GridTrack,
type LayoutGrid,
- type SceneGraph,
type SceneNode,
type Stroke,
type StyleRun
-} from '@open-pencil/scene-graph'
-
-const MIN_SCALE = 0.01
-const RESCALABLE_NODE_TYPES = new Set<SceneNode['type']>([
- 'BOOLEAN_OPERATION',
- 'COMPONENT',
- 'COMPONENT_SET',
- 'ELLIPSE',
- 'FRAME',
- 'GROUP',
- 'INSTANCE',
- 'LINE',
- 'POLYGON',
- 'RECTANGLE',
- 'STAR',
- 'TEXT',
- 'VECTOR'
-])
+} from '../types'
+import { cloneVectorNetwork } from '../vector-network'
function scaledOptional(value: number | null, scale: number): number | null {
return value == null ? null : value * scale
@@ -109,7 +91,7 @@ function scaledVectorNetwork(node: SceneNode, scale: number): SceneNode['vectorN
return network
}
-function scaleNodeChanges(
+export function scaleNodeChanges(
node: SceneNode,
scale: number,
scalePosition: boolean
@@ -159,29 +141,3 @@ function scaleNodeChanges(
strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale)
}
}
-
-/** Scale a node tree from the root node's top-left, matching Figma's Scale tool. */
-export function rescaleNodeTree(graph: SceneGraph, rootId: string, scale: number): void {
- if (!Number.isFinite(scale)) throw new TypeError('Scale must be a finite number')
- if (scale < MIN_SCALE) throw new RangeError(`Scale must be at least ${MIN_SCALE}`)
-
- const root = graph.getNode(rootId)
- if (!root || !RESCALABLE_NODE_TYPES.has(root.type)) {
- throw new Error('rescale() is not supported on this node')
- }
-
- const nodes: SceneNode[] = [root]
- const collect = (node: SceneNode): void => {
- for (const childId of node.childIds) {
- const child = graph.getNode(childId)
- if (!child) continue
- nodes.push(child)
- collect(child)
- }
- }
- collect(root)
-
- for (const node of nodes) {
- graph.updateNode(node.id, scaleNodeChanges(node, scale, node.id !== rootId))
- }
-}
diff --git a/packages/scene-graph/src/scaling/tree.ts b/packages/scene-graph/src/scaling/tree.ts
new file mode 100644
index 000000000..095639ad0
--- /dev/null
+++ b/packages/scene-graph/src/scaling/tree.ts
@@ -0,0 +1,50 @@
+import type { SceneGraph } from '../index'
+import { findInstanceAncestor } from '../instances'
+import type { SceneNode } from '../types'
+import { scaleVariableBindingUnits } from '../variables/units'
+import { scaleNodeChanges } from './node'
+
+const MIN_SCALE = 0.01
+const RESCALABLE_NODE_TYPES = new Set<SceneNode['type']>([
+ 'BOOLEAN_OPERATION',
+ 'COMPONENT',
+ 'COMPONENT_SET',
+ 'ELLIPSE',
+ 'FRAME',
+ 'GROUP',
+ 'INSTANCE',
+ 'LINE',
+ 'POLYGON',
+ 'RECTANGLE',
+ 'STAR',
+ 'TEXT',
+ 'VECTOR'
+])
+
+/** Scale a node tree from the root node's top-left, matching Figma's Scale tool. */
+export function rescaleNodeTree(graph: SceneGraph, rootId: string, scale: number): void {
+ if (!Number.isFinite(scale)) throw new TypeError('Scale must be a finite number')
+ if (scale < MIN_SCALE) throw new RangeError(`Scale must be at least ${MIN_SCALE}`)
+ const root = graph.getNode(rootId)
+ if (!root || !RESCALABLE_NODE_TYPES.has(root.type))
+ throw new Error('rescale() is not supported on this node')
+ const nodes: SceneNode[] = [root]
+ const collect = (node: SceneNode): void => {
+ for (const childId of node.childIds) {
+ const child = graph.getNode(childId)
+ if (!child) continue
+ nodes.push(child)
+ collect(child)
+ }
+ }
+ collect(root)
+ for (const node of nodes) {
+ graph.updateNode(node.id, {
+ ...scaleNodeChanges(node, scale, node.id !== rootId),
+ ...scaleVariableBindingUnits(node, scale),
+ componentScale: findInstanceAncestor(graph, node.id)
+ ? node.componentScale * scale
+ : node.componentScale
+ })
+ }
+}
diff --git a/packages/scene-graph/src/text-picture.ts b/packages/scene-graph/src/text-picture.ts
index 09cf9d172..6d518d7d4 100644
--- a/packages/scene-graph/src/text-picture.ts
+++ b/packages/scene-graph/src/text-picture.ts
@@ -1,3 +1,6 @@
+import { isEqual } from 'es-toolkit/predicate'
+
+import { TEXT_SHAPING_FIELDS, TEXT_LAYOUT_FIELDS } from './fields/text'
import type { SceneNode } from './types'
/**
@@ -5,36 +8,14 @@ import type { SceneNode } from './types'
* because wrapping/layout depends on the box.
*/
export const TEXT_PICTURE_KEYS: ReadonlySet<string> = new Set([
- 'text',
- 'fontSize',
- 'fontFamily',
- 'fontWeight',
- 'italic',
- 'textAlignHorizontal',
- 'textDirection',
- 'textAlignVertical',
- 'lineHeight',
- 'letterSpacing',
+ ...TEXT_SHAPING_FIELDS,
'textDecoration',
- 'textCase',
- 'styleRuns',
'fills',
'width',
'height'
])
-export const GLYPH_AFFECTING_KEYS: ReadonlySet<string> = new Set([
- 'text',
- 'fontSize',
- 'fontFamily',
- 'fontWeight',
- 'italic',
- 'textDirection',
- 'lineHeight',
- 'letterSpacing',
- 'textCase',
- 'styleRuns'
-])
+export const GLYPH_AFFECTING_KEYS: ReadonlySet<string> = new Set(TEXT_SHAPING_FIELDS)
/**
* Shared by SceneGraph.updateNode and updateNodePreview (drag hot path) so the
@@ -46,16 +27,27 @@ export function textCacheInvalidationChanges(
changes: Partial<SceneNode>
): Partial<SceneNode> {
const invalidated: Partial<SceneNode> = {}
- const keys = Object.keys(changes)
+ const keys = Object.keys(changes).filter(
+ (key) => !isEqual(node[key as keyof SceneNode], changes[key as keyof SceneNode])
+ )
if (node.textPicture && keys.some((key) => TEXT_PICTURE_KEYS.has(key)))
invalidated.textPicture = null
- const glyphsInvalidated = keys.some((key) => GLYPH_AFFECTING_KEYS.has(key))
+ const glyphsInvalidated =
+ keys.some((key) => GLYPH_AFFECTING_KEYS.has(key)) ||
+ TEXT_LAYOUT_FIELDS.some((key) => keys.includes(key))
+ if (glyphsInvalidated && !('derivedLayout' in changes)) invalidated.derivedLayout = null
// A successful path-text edit supplies reflowed glyphs in `changes`. Every
// other mutation path must drop stale baked glyphs and path identity rather
// than pair new text/style with old visible outlines.
if (node.derivedTextGlyphs && glyphsInvalidated && !changes.derivedTextGlyphs) {
- invalidated.derivedTextGlyphs = null
- invalidated.textPathData = null
+ // Path-text resize supplies transformed glyphs through the resize workflow. A raw box
+ // preview keeps them until that workflow commits or an actual shaping edit occurs.
+ const onlyPathBoxResize =
+ !!node.textPathData && keys.every((key) => key === 'width' || key === 'height')
+ if (!onlyPathBoxResize) {
+ invalidated.derivedTextGlyphs = null
+ invalidated.textPathData = null
+ }
}
return invalidated
}
diff --git a/packages/scene-graph/src/transfer/apply.ts b/packages/scene-graph/src/transfer/apply.ts
new file mode 100644
index 000000000..ca3a6d2ad
--- /dev/null
+++ b/packages/scene-graph/src/transfer/apply.ts
@@ -0,0 +1,84 @@
+import { isEqual } from 'es-toolkit/predicate'
+
+import type { SceneGraph } from '../index'
+import { variableIdentityReferences } from './identity'
+import type { prepareGraphTransfer } from './plan'
+import { validateTransferReferences } from './validation'
+import { prepareVariableTransfer } from './variables'
+
+export type GraphTransferPlan = ReturnType<typeof prepareGraphTransfer>
+
+function validate(target: SceneGraph, plan: GraphTransferPlan): void {
+ validateTransferReferences(target, plan)
+ const reserved = new Set([
+ ...target.nodes.keys(),
+ ...target.variables.keys(),
+ ...target.variableCollections.keys()
+ ])
+ const claim = (id: string): void => {
+ if (reserved.has(id)) throw new Error(`Transfer identity collision ${id}`)
+ reserved.add(id)
+ }
+ prepareVariableTransfer(
+ plan.variables,
+ plan.collections,
+ variableIdentityReferences(plan.variables, plan.collections)
+ )
+ for (const [id, mode] of plan.activeModes) {
+ if (
+ !plan.collections
+ .find((collection) => collection.id === id)
+ ?.modes.some((entry) => entry.modeId === mode)
+ )
+ throw new Error(`Invalid transferred active mode ${id}:${mode}`)
+ }
+ for (const collection of plan.collections) claim(collection.id)
+ for (const variable of plan.variables) claim(variable.id)
+ const parents = new Set(target.nodes.keys())
+ for (const node of plan.nodes) {
+ claim(node.id)
+ if ('id' in node.props || 'parentId' in node.props || 'childIds' in node.props)
+ throw new Error('Transfer props cannot override hierarchy identity')
+ if (!parents.has(node.parentId)) throw new Error(`Missing transfer parent ${node.parentId}`)
+ parents.add(node.id)
+ }
+ for (const id of [...plan.rootIds, ...plan.dependencyPageIds]) {
+ if (!plan.nodes.some((node) => node.id === id)) throw new Error(`Missing transfer root ${id}`)
+ }
+ for (const node of plan.nodes) {
+ if (node.props.componentId && !parents.has(node.props.componentId))
+ throw new Error(`Missing transfer component ${node.props.componentId}`)
+ }
+ for (const [hash, bytes] of plan.images) {
+ const existing = target.images.get(hash)
+ if (existing && !isEqual(existing, bytes)) throw new Error(`Transfer image collision ${hash}`)
+ }
+}
+
+/** Revalidate at insertion time. Event-delivery failures after commit are not rollback failures. */
+export function applyGraphTransfer(target: SceneGraph, input: GraphTransferPlan): void {
+ const plan = structuredClone(input)
+ validate(target, plan)
+ const imageIds = [...plan.images.keys()].filter((hash) => !target.images.has(hash))
+ target.withBufferedEvents(() => {
+ try {
+ for (const collection of plan.collections) target.addCollection(collection)
+ for (const variable of plan.variables) target.addVariable(variable)
+ for (const [id, mode] of plan.activeModes) target.activeMode.set(id, mode)
+ for (const [hash, bytes] of plan.images)
+ if (!target.images.has(hash)) target.images.set(hash, bytes)
+ for (const node of plan.nodes)
+ target.createNodeWithId(node.id, node.type, node.parentId, { ...node.props, childIds: [] })
+ } catch (error) {
+ for (const node of plan.nodes.toReversed())
+ if (target.getNode(node.id)) target.deleteNode(node.id)
+ for (const variable of plan.variables) target.variables.delete(variable.id)
+ for (const collection of plan.collections) {
+ target.variableCollections.delete(collection.id)
+ target.activeMode.delete(collection.id)
+ }
+ for (const hash of imageIds) target.images.delete(hash)
+ throw error
+ }
+ })
+}
diff --git a/packages/scene-graph/src/transfer/history.ts b/packages/scene-graph/src/transfer/history.ts
new file mode 100644
index 000000000..5192169cd
--- /dev/null
+++ b/packages/scene-graph/src/transfer/history.ts
@@ -0,0 +1,49 @@
+import { cloneNodeProps } from '../copy'
+import type { SceneGraph } from '../index'
+import type { GraphTransferPlan } from './apply'
+
+/** Capture post-placement state for redo; this does not authorize deleting shared resources. */
+export function captureTransferredState(
+ graph: SceneGraph,
+ original: GraphTransferPlan
+): GraphTransferPlan {
+ const requireValue = <T>(value: T | undefined, kind: string, id: string): T => {
+ if (value === undefined) throw new Error(`Missing transferred ${kind} ${id}`)
+ return value
+ }
+ return {
+ nodeIds: new Map(original.nodeIds),
+ rootIds: [...original.rootIds],
+ dependencyPageIds: [...original.dependencyPageIds],
+ nodes: original.nodes.map((entry) => {
+ const node = requireValue(graph.getNode(entry.id), 'node', entry.id)
+ if (!node.parentId) throw new Error(`Missing transferred parent ${entry.id}`)
+ return {
+ id: node.id,
+ type: node.type,
+ parentId: node.parentId,
+ props: cloneNodeProps(node, null)
+ }
+ }),
+ variables: original.variables.map((variable) =>
+ structuredClone(requireValue(graph.variables.get(variable.id), 'variable', variable.id))
+ ),
+ collections: original.collections.map((collection) =>
+ structuredClone(
+ requireValue(graph.variableCollections.get(collection.id), 'collection', collection.id)
+ )
+ ),
+ activeModes: new Map(
+ original.collections.map((collection) => [
+ collection.id,
+ requireValue(graph.activeMode.get(collection.id), 'active mode', collection.id)
+ ])
+ ),
+ images: new Map(
+ [...original.images.keys()].map((hash) => [
+ hash,
+ requireValue(graph.images.get(hash), 'image', hash).slice()
+ ])
+ )
+ }
+}
diff --git a/packages/scene-graph/src/transfer/identity.ts b/packages/scene-graph/src/transfer/identity.ts
new file mode 100644
index 000000000..fc4e5685a
--- /dev/null
+++ b/packages/scene-graph/src/transfer/identity.ts
@@ -0,0 +1,16 @@
+import type { Variable, VariableCollection } from '../types'
+
+export function variableIdentityReferences(
+ variables: readonly Variable[],
+ collections: readonly VariableCollection[]
+) {
+ return {
+ variables: new Map(variables.map((variable) => [variable.id, variable.id])),
+ collections: new Map(collections.map((collection) => [collection.id, collection.id])),
+ modes: new Map(
+ collections.flatMap((collection) =>
+ collection.modes.map((mode) => [mode.modeId, mode.modeId] as const)
+ )
+ )
+ }
+}
diff --git a/packages/scene-graph/src/transfer/index.ts b/packages/scene-graph/src/transfer/index.ts
new file mode 100644
index 000000000..cea09c8d8
--- /dev/null
+++ b/packages/scene-graph/src/transfer/index.ts
@@ -0,0 +1,6 @@
+export { removeGraphTransfer } from './remove'
+export { captureTransferredState } from './history'
+export { applyGraphTransfer, type GraphTransferPlan } from './apply'
+export { prepareGraphTransfer, type GraphTransferInput } from './plan'
+export { prepareNodeTransfer, type NodeTransferReferences } from './nodes'
+export { prepareVariableTransfer, type VariableTransferReferences } from './variables'
diff --git a/packages/scene-graph/src/transfer/nodes.ts b/packages/scene-graph/src/transfer/nodes.ts
new file mode 100644
index 000000000..5c4844d72
--- /dev/null
+++ b/packages/scene-graph/src/transfer/nodes.ts
@@ -0,0 +1,108 @@
+import { cloneNodeProps } from '../copy'
+import { remapInstanceOverrideState } from '../instance-overrides'
+import type { ComponentPropertyType, SceneNode } from '../types'
+import { requireTransferReference as required } from './references'
+import type { VariableTransferReferences } from './variables'
+
+export function semanticTransferReferences(node: SceneNode): string[] {
+ return [
+ ...(node.componentId ? [node.componentId] : []),
+ ...Object.values(node.boundVariables),
+ ...[
+ node.fillStyleId,
+ node.strokeStyleId,
+ node.textStyleId,
+ node.effectStyleId,
+ node.gridStyleId
+ ].filter((id): id is string => !!id),
+ ...node.fillGeometry.flatMap((path) => (path.fillStyleId ? [path.fillStyleId] : [])),
+ ...node.strokeGeometry.flatMap((path) => (path.fillStyleId ? [path.fillStyleId] : [])),
+ ...Object.entries(node.componentPropertyAssignments).flatMap(([id, value]) => [id, value]),
+ ...node.componentPropertyReferences.map((reference) => reference.propertyId),
+ ...node.componentPropertyDefinitions.flatMap((definition) => [
+ definition.id,
+ ...(definition.type === 'INSTANCE_SWAP' && definition.defaultValue
+ ? [definition.defaultValue]
+ : [])
+ ]),
+ ...node.instanceOverrides.descendants.keys(),
+ ...[
+ ...node.instanceOverrides.self,
+ ...[...node.instanceOverrides.descendants.values()].flatMap((fields) => [...fields])
+ ].flatMap(([field, value]) =>
+ typeof value === 'string' &&
+ (field === 'componentId' ||
+ field === 'sourceComponentId' ||
+ field.startsWith('boundVariables/'))
+ ? [value]
+ : []
+ )
+ ]
+}
+
+export interface NodeTransferReferences extends VariableTransferReferences {
+ nodes: ReadonlyMap<string, string>
+ styles: ReadonlyMap<string, string>
+ properties: ReadonlyMap<string, string>
+ propertyTypes: ReadonlyMap<string, ComponentPropertyType>
+}
+
+/** Prepare runtime references without rewriting original format identities or ordinary text. */
+export function prepareNodeTransfer(
+ source: SceneNode,
+ refs: NodeTransferReferences
+): Partial<SceneNode> {
+ const node = (id: string) => required(refs.nodes, id, 'node')
+ const variable = (id: string) => required(refs.variables, id, 'variable')
+ const property = (id: string) => required(refs.properties, id, 'property')
+ const style = (id: string) => required(refs.styles, id, 'style')
+ const propertyValue = (id: string, value: string): string => {
+ const type = refs.propertyTypes.get(id)
+ if (!type) throw new Error(`Missing property transfer type: ${id}`)
+ return type === 'INSTANCE_SWAP' && value ? node(value) : value
+ }
+ const values = (entries: Record<string, string>) =>
+ Object.fromEntries(
+ Object.entries(entries).map(([id, value]) => [property(id), propertyValue(id, value)])
+ )
+ const result = cloneNodeProps(source, null)
+ result.componentId = source.componentId ? node(source.componentId) : null
+ result.instanceOverrides = remapInstanceOverrideState(source.instanceOverrides, {
+ node,
+ variable
+ })
+ result.boundVariables = Object.fromEntries(
+ Object.entries(source.boundVariables).map(([field, id]) => [field, variable(id)])
+ )
+ result.variableModes = Object.fromEntries(
+ Object.entries(source.variableModes).map(([collection, mode]) => [
+ required(refs.collections, collection, 'collection'),
+ required(refs.modes, mode, 'mode')
+ ])
+ )
+ for (const field of [
+ 'fillStyleId',
+ 'strokeStyleId',
+ 'textStyleId',
+ 'effectStyleId',
+ 'gridStyleId'
+ ] as const) {
+ result[field] = source[field] ? style(source[field]) : null
+ }
+ for (const paths of [result.fillGeometry, result.strokeGeometry]) {
+ for (const path of paths ?? []) if (path.fillStyleId) path.fillStyleId = style(path.fillStyleId)
+ }
+ result.componentPropertyDefinitions = source.componentPropertyDefinitions.map((definition) => ({
+ ...structuredClone(definition),
+ id: property(definition.id),
+ defaultValue: propertyValue(definition.id, definition.defaultValue)
+ }))
+ result.componentPropertyReferences = source.componentPropertyReferences.map((reference) => ({
+ ...reference,
+ propertyId: property(reference.propertyId)
+ }))
+ result.componentPropertyAssignments = values(source.componentPropertyAssignments)
+ // Variant values are keyed by display names, unlike definition-ID assignments.
+ result.componentPropertyValues = { ...source.componentPropertyValues }
+ return result
+}
diff --git a/packages/scene-graph/src/transfer/plan.ts b/packages/scene-graph/src/transfer/plan.ts
new file mode 100644
index 000000000..3fba5d0b6
--- /dev/null
+++ b/packages/scene-graph/src/transfer/plan.ts
@@ -0,0 +1,107 @@
+import type { SceneGraph } from '../index'
+import type { ComponentPropertyType, SceneNode } from '../types'
+import { prepareNodeTransfer } from './nodes'
+import { requireTransferReference } from './references'
+import { prepareVariableTransfer } from './variables'
+
+export interface GraphTransferInput {
+ source: SceneGraph
+ rootIds: readonly string[]
+ dependencyPageIds: readonly string[]
+ target: SceneGraph
+ parentId: string
+}
+
+/** Preflight a self-contained fragment; allocation does not insert anything into the target. */
+export function prepareGraphTransfer(input: GraphTransferInput) {
+ const { source, target, parentId } = input
+ if (!target.getNode(parentId)) throw new Error(`Missing transfer parent ${parentId}`)
+ const reserved = new Set([
+ ...target.nodes.keys(),
+ ...target.variables.keys(),
+ ...target.variableCollections.keys()
+ ])
+ for (const collection of target.variableCollections.values())
+ for (const mode of collection.modes) reserved.add(mode.modeId)
+ let sequence = 0
+ const namespace = crypto.randomUUID()
+ const allocate = (): string => {
+ let id = `${namespace}:${sequence++}`
+ while (reserved.has(id)) id = `${namespace}:${sequence++}`
+ reserved.add(id)
+ return id
+ }
+ const ordered: SceneNode[] = []
+ const seen = new Set<string>()
+ const visit = (id: string): void => {
+ if (seen.has(id)) throw new Error(`Repeated transfer node ${id}`)
+ const node = source.getNode(id)
+ if (!node) throw new Error(`Missing transfer source ${id}`)
+ seen.add(id)
+ ordered.push(node)
+ for (const child of node.childIds) visit(child)
+ }
+ for (const id of [...input.dependencyPageIds, ...input.rootIds]) visit(id)
+ const nodes = new Map(ordered.map((node) => [node.id, allocate()]))
+ const variables = new Map([...source.variables.keys()].map((id) => [id, allocate()]))
+ const collections = new Map([...source.variableCollections.keys()].map((id) => [id, allocate()]))
+ const modes = new Map<string, string>()
+ for (const collection of source.variableCollections.values()) {
+ for (const mode of collection.modes)
+ if (!modes.has(mode.modeId)) modes.set(mode.modeId, allocate())
+ }
+ const properties = new Map<string, string>()
+ const propertyTypes = new Map<string, ComponentPropertyType>()
+ for (const node of ordered)
+ for (const definition of node.componentPropertyDefinitions) {
+ if (propertyTypes.has(definition.id) && propertyTypes.get(definition.id) !== definition.type)
+ throw new Error(`Conflicting property type ${definition.id}`)
+ propertyTypes.set(definition.id, definition.type)
+ if (!properties.has(definition.id)) properties.set(definition.id, allocate())
+ }
+ const references = {
+ nodes,
+ variables,
+ collections,
+ modes,
+ properties,
+ propertyTypes,
+ styles: nodes
+ }
+ const resources = prepareVariableTransfer(
+ [...source.variables.values()],
+ [...source.variableCollections.values()],
+ references
+ )
+ const mapped = (id: string): string => {
+ const value = nodes.get(id)
+ if (!value) throw new Error(`Missing transfer node mapping ${id}`)
+ return value
+ }
+ const roots = new Set(input.rootIds)
+ const dependencies = new Set(input.dependencyPageIds)
+ const destinationParent = (node: SceneNode): string => {
+ if (roots.has(node.id)) return parentId
+ if (dependencies.has(node.id)) return target.rootId
+ return mapped(node.parentId ?? '')
+ }
+ return {
+ nodeIds: nodes,
+ rootIds: input.rootIds.map(mapped),
+ dependencyPageIds: input.dependencyPageIds.map(mapped),
+ nodes: ordered.map((node) => ({
+ id: mapped(node.id),
+ type: node.type,
+ parentId: destinationParent(node),
+ props: prepareNodeTransfer(node, references)
+ })),
+ ...resources,
+ activeModes: new Map(
+ [...source.activeMode].map(([collection, mode]) => [
+ requireTransferReference(collections, collection, 'collection'),
+ requireTransferReference(modes, mode, 'mode')
+ ])
+ ),
+ images: new Map([...source.images].map(([hash, bytes]) => [hash, bytes.slice()]))
+ }
+}
diff --git a/packages/scene-graph/src/transfer/references.ts b/packages/scene-graph/src/transfer/references.ts
new file mode 100644
index 000000000..50a30768a
--- /dev/null
+++ b/packages/scene-graph/src/transfer/references.ts
@@ -0,0 +1,9 @@
+export function requireTransferReference(
+ ids: ReadonlyMap<string, string>,
+ id: string,
+ kind: string
+): string {
+ const value = ids.get(id)
+ if (!value) throw new Error(`Missing ${kind} transfer mapping: ${id}`)
+ return value
+}
diff --git a/packages/scene-graph/src/transfer/remove.ts b/packages/scene-graph/src/transfer/remove.ts
new file mode 100644
index 000000000..efc9a19df
--- /dev/null
+++ b/packages/scene-graph/src/transfer/remove.ts
@@ -0,0 +1,39 @@
+import type { SceneGraph } from '../index'
+import type { GraphTransferPlan } from './apply'
+import { semanticTransferReferences } from './nodes'
+
+/** Refuse to remove transferred content that has acquired external dependents. */
+export function removeGraphTransfer(graph: SceneGraph, plan: GraphTransferPlan): void {
+ const nodes = new Set(plan.nodes.map((node) => node.id))
+ const variables = new Set(plan.variables.map((variable) => variable.id))
+ const collections = new Set(plan.collections.map((collection) => collection.id))
+ const referencesOwned = (value: unknown): boolean => {
+ if (typeof value === 'string')
+ return nodes.has(value) || variables.has(value) || collections.has(value)
+ if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) return false
+ if (value instanceof Map)
+ return [...value].some(([key, item]) => referencesOwned(key) || referencesOwned(item))
+ return Object.values(value).some(referencesOwned)
+ }
+ for (const node of graph.getAllNodes()) {
+ if (nodes.has(node.id)) {
+ if (node.childIds.some((id) => !nodes.has(id)))
+ throw new Error('Transferred node has non-owned children')
+ continue
+ }
+ if (semanticTransferReferences(node).some(referencesOwned))
+ throw new Error(`Transferred content is referenced by ${node.id}`)
+ }
+ for (const variable of graph.variables.values()) {
+ if (!variables.has(variable.id) && referencesOwned(variable.valuesByMode))
+ throw new Error('Transferred variable has external aliases')
+ }
+ graph.withBufferedEvents(() => {
+ for (const node of plan.nodes.toReversed()) graph.deleteNode(node.id)
+ for (const id of variables) graph.variables.delete(id)
+ for (const id of collections) {
+ graph.variableCollections.delete(id)
+ graph.activeMode.delete(id)
+ }
+ })
+}
diff --git a/packages/scene-graph/src/transfer/validation.ts b/packages/scene-graph/src/transfer/validation.ts
new file mode 100644
index 000000000..02804008d
--- /dev/null
+++ b/packages/scene-graph/src/transfer/validation.ts
@@ -0,0 +1,54 @@
+import type { SceneGraph } from '../index'
+import { createDefaultNode } from '../node-defaults'
+import type { ComponentPropertyType } from '../types'
+import type { GraphTransferPlan } from './apply'
+import { variableIdentityReferences } from './identity'
+import { prepareNodeTransfer } from './nodes'
+
+/** Revalidate mutable plan references without allocating or registering destination nodes. */
+export function validateTransferReferences(target: SceneGraph, plan: GraphTransferPlan): void {
+ const nodes = new Map(
+ plan.nodes.map((entry) => [
+ entry.id,
+ createDefaultNode(() => entry.id, entry.type, entry.props)
+ ])
+ )
+ const identities = new Map([...nodes.keys()].map((id) => [id, id]))
+ const properties = new Map<string, string>()
+ const propertyTypes = new Map<string, ComponentPropertyType>()
+ for (const node of nodes.values())
+ for (const definition of node.componentPropertyDefinitions) {
+ const previous = propertyTypes.get(definition.id)
+ if (previous && previous !== definition.type)
+ throw new Error(`Conflicting transfer property ${definition.id}`)
+ properties.set(definition.id, definition.id)
+ propertyTypes.set(definition.id, definition.type)
+ }
+ const collections = new Map(plan.collections.map((collection) => [collection.id, collection]))
+ const references = {
+ nodes: identities,
+ styles: identities,
+ properties,
+ propertyTypes,
+ ...variableIdentityReferences(plan.variables, plan.collections)
+ }
+ for (const node of nodes.values()) {
+ prepareNodeTransfer(node, references)
+ for (const [collection, mode] of Object.entries(node.variableModes)) {
+ if (!collections.get(collection)?.modes.some((entry) => entry.modeId === mode))
+ throw new Error(`Invalid node variable mode ${node.id}`)
+ }
+ }
+ const roots = new Set([...plan.rootIds, ...plan.dependencyPageIds])
+ if (roots.size !== plan.rootIds.length + plan.dependencyPageIds.length)
+ throw new Error('Repeated transfer root')
+ for (const entry of plan.nodes) {
+ if (roots.has(entry.id) === nodes.has(entry.parentId))
+ throw new Error(`Invalid transfer root topology ${entry.id}`)
+ if (
+ plan.dependencyPageIds.includes(entry.id) &&
+ (entry.type !== 'CANVAS' || !entry.props.internalOnly || entry.parentId !== target.rootId)
+ )
+ throw new Error(`Invalid transfer dependency page ${entry.id}`)
+ }
+}
diff --git a/packages/scene-graph/src/transfer/variables.ts b/packages/scene-graph/src/transfer/variables.ts
new file mode 100644
index 000000000..ce2e2c15c
--- /dev/null
+++ b/packages/scene-graph/src/transfer/variables.ts
@@ -0,0 +1,82 @@
+import type { Variable, VariableCollection, VariableValue } from '../types'
+import { requireTransferReference as mapped } from './references'
+
+export interface VariableTransferReferences {
+ variables: ReadonlyMap<string, string>
+ collections: ReadonlyMap<string, string>
+ modes: ReadonlyMap<string, string>
+}
+
+function assertUniqueMappings(ids: ReadonlyMap<string, string>, kind: string): void {
+ if (new Set(ids.values()).size !== ids.size)
+ throw new Error(`Colliding ${kind} transfer mappings`)
+}
+
+function assertResourceOwnership(
+ variables: readonly Variable[],
+ collections: readonly VariableCollection[]
+): void {
+ const sets = new Map(collections.map((collection) => [collection.id, collection]))
+ const tokens = new Map(variables.map((variable) => [variable.id, variable]))
+ if (sets.size !== collections.length || tokens.size !== variables.length)
+ throw new Error('Duplicate source variable resource')
+ for (const collection of collections) {
+ const modes = new Set(collection.modes.map((mode) => mode.modeId))
+ if (!modes.has(collection.defaultModeId) || modes.size !== collection.modes.length)
+ throw new Error(`Invalid modes for collection ${collection.id}`)
+ for (const id of collection.variableIds) {
+ if (tokens.get(id)?.collectionId !== collection.id)
+ throw new Error(`Invalid variable membership ${id} in ${collection.id}`)
+ }
+ }
+ for (const variable of variables) {
+ const collection = sets.get(variable.collectionId)
+ if (!collection?.variableIds.includes(variable.id))
+ throw new Error(`Missing collection membership for ${variable.id}`)
+ const modes = new Set(collection.modes.map((mode) => mode.modeId))
+ for (const mode of Object.keys(variable.valuesByMode)) {
+ if (!modes.has(mode)) throw new Error(`Unknown mode ${mode} for ${variable.id}`)
+ }
+ }
+}
+
+/** Prepare isolated resource copies; never mutate the source or destination graph. */
+export function prepareVariableTransfer(
+ variables: readonly Variable[],
+ collections: readonly VariableCollection[],
+ references: VariableTransferReferences
+): { variables: Variable[]; collections: VariableCollection[] } {
+ assertResourceOwnership(variables, collections)
+ assertUniqueMappings(references.variables, 'variable')
+ assertUniqueMappings(references.collections, 'collection')
+ assertUniqueMappings(references.modes, 'mode')
+ const value = (input: VariableValue): VariableValue => {
+ if (typeof input === 'object' && 'aliasId' in input) {
+ return { aliasId: mapped(references.variables, input.aliasId, 'variable alias') }
+ }
+ return structuredClone(input)
+ }
+ return {
+ collections: collections.map((collection) => ({
+ ...collection,
+ id: mapped(references.collections, collection.id, 'collection'),
+ defaultModeId: mapped(references.modes, collection.defaultModeId, 'mode'),
+ modes: collection.modes.map((mode) => ({
+ ...mode,
+ modeId: mapped(references.modes, mode.modeId, 'mode')
+ })),
+ variableIds: collection.variableIds.map((id) => mapped(references.variables, id, 'variable'))
+ })),
+ variables: variables.map((variable) => ({
+ ...variable,
+ id: mapped(references.variables, variable.id, 'variable'),
+ collectionId: mapped(references.collections, variable.collectionId, 'collection'),
+ valuesByMode: Object.fromEntries(
+ Object.entries(variable.valuesByMode).map(([mode, input]) => [
+ mapped(references.modes, mode, 'mode'),
+ value(input)
+ ])
+ )
+ }))
+ }
+}
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index f355bdc65..4d1e75e20 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -331,6 +331,8 @@ export interface TextPathData {
}
export interface DerivedTextGlyph {
+ /** UTF-16 source-text cluster start, when supplied by the shaping source. */
+ firstCharacter?: number
commandsBlob: Uint8Array
x: number
y: number
@@ -560,6 +562,12 @@ export interface SceneNode {
variantPropSpecs: VariantPropSpec[]
boundVariables: Record<string, string>
+ /** Multipliers from bound numeric values to this occurrence's scene units. */
+ variableBindingScales: Partial<Record<string, number>>
+ /** Numeric units for new declarations owned by this node's occurrence scope. */
+ variableAssignmentScales: Partial<Record<string, number>>
+ /** Explicit coordinate scale relative to the containing component definition. */
+ componentScale: number
variableModes: VariableModeMap
exportSettings: ExportSetting[]
diff --git a/packages/scene-graph/src/variables.ts b/packages/scene-graph/src/variables.ts
index cbbbdcabc..3ed11d461 100644
--- a/packages/scene-graph/src/variables.ts
+++ b/packages/scene-graph/src/variables.ts
@@ -3,8 +3,15 @@ import { omit, omitBy } from 'es-toolkit/object'
import { BLACK } from './constants'
import type { SceneGraph } from './index'
import { setInstanceOverride } from './instance-overrides'
+import { findInstanceAncestor } from './instances'
import type { Color } from './primitives'
import type { Variable, VariableCollection, VariableType, VariableValue } from './types'
+import {
+ isNumericVariableBindingField,
+ variableBindingOwner,
+ assignVariableBindingUnits
+} from './variables/bindings'
+import { BOOLEAN_BINDING_FIELDS, STRING_BINDING_FIELDS } from './variables/fields'
export function addVariable(graph: SceneGraph, variable: Variable): void {
graph.variables.set(variable.id, variable)
@@ -29,7 +36,14 @@ export function removeVariable(graph: SceneGraph, id: string): void {
string,
string
>
- graph.emitter.emit('node:updated', node.id, { boundVariables: { ...node.boundVariables } })
+ node.variableBindingScales = omitBy(
+ node.variableBindingScales,
+ (_, field) => !(field in node.boundVariables)
+ )
+ graph.emitter.emit('node:updated', node.id, {
+ boundVariables: { ...node.boundVariables },
+ variableBindingScales: { ...node.variableBindingScales }
+ })
markBoundVariablesOverrideOnInstance(graph, node.id)
}
}
@@ -254,6 +268,18 @@ export function resolveNumberVariableForNode(
return typeof value === 'number' ? value : undefined
}
+export function resolveStringVariableForNode(
+ graph: SceneGraph,
+ nodeId: string,
+ variableId: string
+): string | undefined {
+ const variable = graph.variables.get(variableId)
+ if (!variable) return undefined
+ const modeId = getNodeVariableModeId(graph, nodeId, variable.collectionId)
+ const value = resolveVariable(graph, variableId, modeId)
+ return typeof value === 'string' ? value : undefined
+}
+
export function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {
const collection = graph.variableCollections.get(collectionId)
if (!collection) return []
@@ -266,44 +292,6 @@ export function getVariablesByType(graph: SceneGraph, type: VariableType): Varia
return [...graph.variables.values()].filter((v) => v.type === type)
}
-const SCALAR_BINDING_FIELDS: ReadonlySet<string> = new Set([
- 'opacity',
- 'width',
- 'height',
- 'cornerRadius',
- 'fontSize',
- 'letterSpacing',
- 'lineHeight',
- 'itemSpacing',
- 'strokeWeight',
- 'paddingLeft',
- 'paddingRight',
- 'paddingTop',
- 'paddingBottom',
- 'counterAxisSpacing',
- 'topLeftRadius',
- 'topRightRadius',
- 'bottomLeftRadius',
- 'bottomRightRadius',
- 'rotation',
- 'x',
- 'y',
- 'minWidth',
- 'maxWidth',
- 'minHeight',
- 'maxHeight',
- 'borderTopWeight',
- 'borderBottomWeight',
- 'borderLeftWeight',
- 'borderRightWeight',
- 'gridRowGap',
- 'gridColumnGap'
-])
-
-const STRING_BINDING_FIELDS: ReadonlySet<string> = new Set(['fontFamily'])
-
-const BOOLEAN_BINDING_FIELDS: ReadonlySet<string> = new Set(['visible'])
-
export function bindVariable(
graph: SceneGraph,
nodeId: string,
@@ -339,7 +327,7 @@ export function bindVariable(
}
}
- if (SCALAR_BINDING_FIELDS.has(field) && variable.type !== 'FLOAT') {
+ if (isNumericVariableBindingField(field) && variable.type !== 'FLOAT') {
throw new Error(`Cannot bind ${variable.type} variable to scalar field "${field}"`)
}
@@ -352,7 +340,7 @@ export function bindVariable(
}
const isKnownField =
- SCALAR_BINDING_FIELDS.has(field) ||
+ isNumericVariableBindingField(field) ||
STRING_BINDING_FIELDS.has(field) ||
BOOLEAN_BINDING_FIELDS.has(field) ||
colorFieldMatch
@@ -362,8 +350,12 @@ export function bindVariable(
}
node.boundVariables = { ...node.boundVariables, [field]: variableId }
- graph.emitter.emit('node:updated', nodeId, { boundVariables: { ...node.boundVariables } })
- markBoundVariablesOverrideOnInstance(graph, nodeId)
+ assignVariableBindingUnits(graph, node, field)
+ markBoundVariablesOverrideOnInstance(graph, nodeId, field)
+ graph.emitter.emit('node:updated', nodeId, {
+ boundVariables: { ...node.boundVariables },
+ variableBindingScales: { ...node.variableBindingScales }
+ })
}
export function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {
@@ -371,29 +363,33 @@ export function unbindVariable(graph: SceneGraph, nodeId: string, field: string)
if (!node) return
if (!(field in node.boundVariables)) return
node.boundVariables = omit(node.boundVariables, [field])
- graph.emitter.emit('node:updated', nodeId, { boundVariables: { ...node.boundVariables } })
- markBoundVariablesOverrideOnInstance(graph, nodeId)
+ node.variableBindingScales = omit(node.variableBindingScales, [field])
+ markBoundVariablesOverrideOnInstance(graph, nodeId, field)
+ graph.emitter.emit('node:updated', nodeId, {
+ boundVariables: { ...node.boundVariables },
+ variableBindingScales: { ...node.variableBindingScales }
+ })
}
-function markBoundVariablesOverrideOnInstance(graph: SceneGraph, nodeId: string): void {
+function markBoundVariablesOverrideOnInstance(
+ graph: SceneGraph,
+ nodeId: string,
+ field?: string
+): void {
const node = graph.nodes.get(nodeId)
if (!node) return
- // Mark the field on the canonical structured state.
- if (node.type === 'INSTANCE') {
- setInstanceOverride(node.instanceOverrides, node.id, node.id, 'boundVariables')
- return
- }
-
- // Walk up to the owning instance for descendant fields.
- let current = node
- while (current.parentId) {
- const parent = graph.nodes.get(current.parentId)
- if (!parent) break
- if (parent.type === 'INSTANCE') {
- setInstanceOverride(parent.instanceOverrides, parent.id, nodeId, 'boundVariables')
- break
- }
- current = parent
- }
+ const owner = variableBindingOwner(graph, node)
+ if (owner.type !== 'INSTANCE') return
+ const nearest = findInstanceAncestor(graph, nodeId)
+ if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')
+ setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')
+ if (field)
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ nodeId,
+ `boundVariables/${field}`,
+ node.boundVariables[field] ?? null
+ )
}
diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.ts
new file mode 100644
index 000000000..41af3c01b
--- /dev/null
+++ b/packages/scene-graph/src/variables/bindings.ts
@@ -0,0 +1,54 @@
+import type { SceneGraph } from '../index'
+import { hasInstanceOverride } from '../instances'
+import type { SceneNode } from '../types'
+import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
+export { isNumericVariableBindingField } from './fields'
+
+/** New declarations belong to the outermost occurrence, bounded by a component definition. */
+export function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {
+ let owner = node
+ let current: SceneNode | undefined = node
+ while (current) {
+ if (current.type === 'COMPONENT' || current.type === 'COMPONENT_SET') break
+ if (current.type === 'INSTANCE') owner = current
+ current = current.parentId ? graph.getNode(current.parentId) : undefined
+ }
+ return owner
+}
+
+export function assignVariableBindingUnits(
+ graph: SceneGraph,
+ node: SceneNode,
+ field: string
+): void {
+ if (!isNumericVariableBindingField(field)) return
+ const owner = variableBindingOwner(graph, node)
+ node.variableBindingScales = {
+ ...node.variableBindingScales,
+ [field]: owner.variableAssignmentScales[field] ?? 1
+ }
+}
+
+/** Resolve live numeric bindings in scene units, without authoring instance overrides. */
+export function reconcileNumericVariableBindings(graph: SceneGraph): string[] {
+ const changed: string[] = []
+ for (const node of graph.getAllNodes()) {
+ const updates: Partial<SceneNode> = {}
+ for (const [field, variableId] of Object.entries(node.boundVariables)) {
+ if (!NUMERIC_FIELDS.has(field)) continue
+ if ((field === 'width' || field === 'height') && hasInstanceOverride(graph, node.id, field))
+ continue
+ const value = graph.resolveNumberVariableForNode(node.id, variableId)
+ if (value === undefined || !Number.isFinite(value)) continue
+ const scale = node.variableBindingScales[field] ?? 1
+ const effective = value * scale
+ if (!Number.isFinite(effective)) continue
+ const next = field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective
+ if (node[field as keyof SceneNode] !== next) Object.assign(updates, { [field]: next })
+ }
+ if (Object.keys(updates).length === 0) continue
+ graph.updateNode(node.id, updates)
+ changed.push(node.id)
+ }
+ return changed
+}
diff --git a/packages/scene-graph/src/variables/fields.ts b/packages/scene-graph/src/variables/fields.ts
new file mode 100644
index 000000000..57ade651b
--- /dev/null
+++ b/packages/scene-graph/src/variables/fields.ts
@@ -0,0 +1,43 @@
+export const NUMERIC_FIELDS = new Set([
+ 'opacity',
+ 'width',
+ 'height',
+ 'minWidth',
+ 'maxWidth',
+ 'minHeight',
+ 'maxHeight',
+ 'x',
+ 'y',
+ 'rotation',
+ 'cornerRadius',
+ 'topLeftRadius',
+ 'topRightRadius',
+ 'bottomLeftRadius',
+ 'bottomRightRadius',
+ 'strokeWeight',
+ 'borderTopWeight',
+ 'borderBottomWeight',
+ 'borderLeftWeight',
+ 'borderRightWeight',
+ 'fontSize',
+ 'letterSpacing',
+ 'lineHeight',
+ 'paddingLeft',
+ 'paddingRight',
+ 'paddingTop',
+ 'paddingBottom',
+ 'itemSpacing',
+ 'counterAxisSpacing',
+ 'gridRowGap',
+ 'gridColumnGap'
+])
+
+export function isNumericVariableBindingField(field: string): boolean {
+ return NUMERIC_FIELDS.has(field)
+}
+
+/** Text content and font family are the string-valued bindings a node accepts. */
+export const STRING_BINDING_FIELDS: ReadonlySet<string> = new Set(['text', 'fontFamily'])
+
+/** Visibility is the only boolean-valued binding a node accepts. */
+export const BOOLEAN_BINDING_FIELDS: ReadonlySet<string> = new Set(['visible'])
diff --git a/packages/scene-graph/src/variables/units.ts b/packages/scene-graph/src/variables/units.ts
new file mode 100644
index 000000000..965a66ab6
--- /dev/null
+++ b/packages/scene-graph/src/variables/units.ts
@@ -0,0 +1,15 @@
+import type { SceneNode } from '../types'
+import { NUMERIC_FIELDS } from './fields'
+
+export function scaleVariableBindingUnits(node: SceneNode, factor: number): Partial<SceneNode> {
+ const variableBindingScales = { ...node.variableBindingScales }
+ const variableAssignmentScales = { ...node.variableAssignmentScales }
+ for (const field of NUMERIC_FIELDS) {
+ if (field === 'opacity' || field === 'rotation') continue
+ if (field in node.boundVariables)
+ variableBindingScales[field] = (variableBindingScales[field] ?? 1) * factor
+ if (node.type === 'INSTANCE')
+ variableAssignmentScales[field] = (variableAssignmentScales[field] ?? 1) * factor
+ }
+ return { variableBindingScales, variableAssignmentScales }
+}
diff --git a/packages/scene-graph/tests/basic/text-picture-keys.test.ts b/packages/scene-graph/tests/basic/text-picture-keys.test.ts
index 02698690b..e1cd06824 100644
--- a/packages/scene-graph/tests/basic/text-picture-keys.test.ts
+++ b/packages/scene-graph/tests/basic/text-picture-keys.test.ts
@@ -39,20 +39,15 @@ describe('text rendering invalidation keys', () => {
'lineHeight',
'letterSpacing',
'textCase',
+ 'fontVariations',
+ 'fontFeatures',
+ 'textAlignHorizontal',
+ 'textAlignVertical',
'styleRuns'
]) {
expect(keys.has(k)).toBe(true)
}
- for (const k of [
- 'x',
- 'y',
- 'width',
- 'height',
- 'fills',
- 'textAlignHorizontal',
- 'textAlignVertical',
- 'textDecoration'
- ]) {
+ for (const k of ['x', 'y', 'width', 'height', 'fills', 'textDecoration']) {
expect(keys.has(k)).toBe(false)
}
})
diff --git a/packages/scene-graph/tests/basic/update-node.test.ts b/packages/scene-graph/tests/basic/update-node.test.ts
index 0b2e1b8b0..6706f65e9 100644
--- a/packages/scene-graph/tests/basic/update-node.test.ts
+++ b/packages/scene-graph/tests/basic/update-node.test.ts
@@ -204,15 +204,8 @@ describe('updateNode', () => {
expect(expectDefined(graph.getNode(textId), 'updated node').derivedTextGlyphs).toBeNull()
})
- test('derivedTextGlyphs survive picture-only text property changes', () => {
- const pictureOnlyChanges = [
- { width: 120 },
- { height: 24 },
- { fills: [] },
- { textAlignHorizontal: 'CENTER' as const },
- { textAlignVertical: 'CENTER' as const },
- { textDecoration: 'UNDERLINE' as const }
- ]
+ test('derivedTextGlyphs survive paint and decoration changes', () => {
+ const pictureOnlyChanges = [{ fills: [] }, { textDecoration: 'UNDERLINE' as const }]
for (const changes of pictureOnlyChanges) {
const graph = new SceneGraph()
diff --git a/packages/scene-graph/tests/buffered-events.test.ts b/packages/scene-graph/tests/buffered-events.test.ts
new file mode 100644
index 000000000..1bdd2d889
--- /dev/null
+++ b/packages/scene-graph/tests/buffered-events.test.ts
@@ -0,0 +1,48 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('nested event buffers publish in order only after the outer action commits', () => {
+ const graph = new SceneGraph()
+ const events: string[] = []
+ graph.onNodeEvents({ created: (node) => events.push(node.name) })
+ const page = graph.getPages()[0]
+ graph.withBufferedEvents(() => {
+ graph.createNode('RECTANGLE', page.id, { name: 'First' })
+ graph.withBufferedEvents(() => graph.createNode('RECTANGLE', page.id, { name: 'Second' }))
+ expect(events).toEqual([])
+ })
+ expect(events).toEqual(['First', 'Second'])
+ expect(() =>
+ graph.withBufferedEvents(() => {
+ graph.withBufferedEvents(() =>
+ graph.createNode('RECTANGLE', page.id, { name: 'Discarded event' })
+ )
+ throw new Error('Fail')
+ })
+ ).toThrow('Fail')
+ expect(events).toEqual(['First', 'Second'])
+})
+
+test('observer failure does not prevent later queued events or poison the emitter', () => {
+ const graph = new SceneGraph()
+ const names: string[] = []
+ const off = graph.onNodeEvents({
+ created: (node) => {
+ names.push(node.name)
+ if (node.name === 'First') throw new Error('Observer failed')
+ }
+ })
+ const page = graph.getPages()[0]
+ expect(() =>
+ graph.withBufferedEvents(() => {
+ graph.createNode('RECTANGLE', page.id, { name: 'First' })
+ graph.createNode('RECTANGLE', page.id, { name: 'Second' })
+ })
+ ).toThrow('Committed graph event delivery failed')
+ expect(names).toEqual(['First', 'Second'])
+ expect(graph.getChildren(page.id)).toHaveLength(2)
+ off()
+ graph.withBufferedEvents(() => graph.createNode('RECTANGLE', page.id))
+ expect(graph.getChildren(page.id)).toHaveLength(3)
+})
diff --git a/packages/scene-graph/tests/components/binding-protection.test.ts b/packages/scene-graph/tests/components/binding-protection.test.ts
new file mode 100644
index 000000000..695bf1b81
--- /dev/null
+++ b/packages/scene-graph/tests/components/binding-protection.test.ts
@@ -0,0 +1,50 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph, setInstanceOverride } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../helpers/assert'
+
+for (const legacyOwner of ['outer', 'self'] as const) {
+ test(`per-field claims do not weaken another owner's ${legacyOwner} whole-map protection`, () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const component = graph.createNode('COMPONENT', page, {
+ boundVariables: { paddingLeft: 'source-left', paddingRight: 'source-right' },
+ variableBindingScales: { paddingLeft: 1, paddingRight: 1 },
+ paddingLeft: 20,
+ paddingRight: 30
+ })
+ const outer = graph.createNode('INSTANCE', page)
+ const instance = expectDefined(graph.createInstance(component.id, outer.id))
+ graph.updateNode(instance.id, {
+ boundVariables: { paddingLeft: 'local-left', paddingRight: 'local-right' },
+ variableBindingScales: { paddingLeft: 0.5, paddingRight: 0.25 },
+ paddingLeft: 10,
+ paddingRight: 7.5
+ })
+ const whole = legacyOwner === 'outer' ? outer : instance
+ const granular = legacyOwner === 'outer' ? instance : outer
+ setInstanceOverride(whole.instanceOverrides, whole.id, instance.id, 'boundVariables', true)
+ setInstanceOverride(
+ granular.instanceOverrides,
+ granular.id,
+ instance.id,
+ 'boundVariables',
+ true
+ )
+ setInstanceOverride(
+ granular.instanceOverrides,
+ granular.id,
+ instance.id,
+ 'boundVariables/paddingLeft',
+ true
+ )
+ graph.syncInstances(component.id)
+ expect(instance.boundVariables).toEqual({
+ paddingLeft: 'local-left',
+ paddingRight: 'local-right'
+ })
+ expect(instance.variableBindingScales).toEqual({ paddingLeft: 0.5, paddingRight: 0.25 })
+ expect([instance.paddingLeft, instance.paddingRight]).toEqual([10, 7.5])
+ })
+}
diff --git a/packages/scene-graph/tests/components/nested-sync.test.ts b/packages/scene-graph/tests/components/nested-sync.test.ts
new file mode 100644
index 000000000..d2e15341e
--- /dev/null
+++ b/packages/scene-graph/tests/components/nested-sync.test.ts
@@ -0,0 +1,35 @@
+import { expect, test } from 'bun:test'
+
+import {
+ SceneGraph,
+ recordInstanceOverride,
+ deleteInstanceOverride
+} from '@open-pencil/scene-graph'
+
+test('outer sync preserves a nested edit without blocking sibling or other-field inheritance', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const inner = graph.createNode('COMPONENT', page.id)
+ graph.createNode('TEXT', inner.id, { text: 'Default', opacity: 1 })
+ const outer = graph.createNode('COMPONENT', page.id)
+ const nestedSource = graph.createInstance(inner.id, outer.id)
+ const first = graph.createInstance(outer.id, page.id)
+ const second = graph.createInstance(outer.id, page.id)
+ if (!nestedSource || !first || !second) throw new Error('Missing instances')
+ const firstNested = graph.getChildren(first.id)[0]
+ const firstText = graph.getChildren(firstNested.id)[0]
+ const secondText = graph.getChildren(graph.getChildren(second.id)[0].id)[0]
+ const sourceText = graph.getChildren(nestedSource.id)[0]
+ graph.updateNode(firstText.id, { text: 'Local edit' })
+ recordInstanceOverride(graph, firstText.id, ['text'])
+ graph.updateNode(sourceText.id, { text: 'Component edit', opacity: 0.5 })
+ graph.syncInstances(outer.id)
+ expect(firstText.text).toBe('Local edit')
+ expect(firstText.opacity).toBe(0.5)
+ expect(secondText.text).toBe('Component edit')
+ expect(graph.getChildren(firstNested.id)).toHaveLength(1)
+
+ deleteInstanceOverride(firstNested.instanceOverrides, firstNested.id, firstText.id, 'text')
+ graph.syncInstances(outer.id)
+ expect(firstText.text).toBe('Component edit')
+})
diff --git a/packages/scene-graph/tests/components/override-transfer.test.ts b/packages/scene-graph/tests/components/override-transfer.test.ts
new file mode 100644
index 000000000..228a198b4
--- /dev/null
+++ b/packages/scene-graph/tests/components/override-transfer.test.ts
@@ -0,0 +1,45 @@
+import { expect, test } from 'bun:test'
+
+import { createInstanceOverrideState, remapInstanceOverrideState } from '@open-pencil/scene-graph'
+
+test('override transfer remaps typed identities without rewriting equal text', () => {
+ const state = createInstanceOverrideState()
+ state.self.set('componentId', 'source')
+ state.self.set('text', 'source')
+ state.descendants.set(
+ 'child',
+ new Map<string, unknown>([
+ ['sourceComponentId', 'source'],
+ ['boundVariables/paddingLeft', 'token'],
+ ['boundVariables/paddingRight', undefined],
+ ['visible', false],
+ ['fills', [{ marker: 'source' }]]
+ ])
+ )
+ const before = structuredClone(state)
+ const result = remapInstanceOverrideState(state, {
+ node: (id) => `node/${id}`,
+ variable: (id) => `variable/${id}`
+ })
+ expect(result.self.get('componentId')).toBe('node/source')
+ expect(result.self.get('text')).toBe('source')
+ expect(result.descendants.get('node/child')).toEqual(
+ new Map<string, unknown>([
+ ['sourceComponentId', 'node/source'],
+ ['boundVariables/paddingLeft', 'variable/token'],
+ ['boundVariables/paddingRight', undefined],
+ ['visible', false],
+ ['fills', [{ marker: 'source' }]]
+ ])
+ )
+ expect(state).toEqual(before)
+})
+
+test('override transfer rejects colliding target mappings', () => {
+ const state = createInstanceOverrideState()
+ state.descendants.set('a', new Map())
+ state.descendants.set('b', new Map())
+ expect(() =>
+ remapInstanceOverrideState(state, { node: () => 'same', variable: (id) => id })
+ ).toThrow('Duplicate remapped override target')
+})
diff --git a/packages/scene-graph/tests/components/property-targets.test.ts b/packages/scene-graph/tests/components/property-targets.test.ts
new file mode 100644
index 000000000..419bab729
--- /dev/null
+++ b/packages/scene-graph/tests/components/property-targets.test.ts
@@ -0,0 +1,20 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph, findComponentPropertyTarget } from '@open-pencil/scene-graph'
+
+test('component properties follow source identity when instance siblings are reordered', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id)
+ const source = graph.createNode('RECTANGLE', component.id, {
+ name: 'Target',
+ componentPropertyReferences: [{ propertyId: 'show', field: 'VISIBLE' }]
+ })
+ graph.createNode('RECTANGLE', component.id, { name: 'Other' })
+ const instance = graph.createInstance(component.id, page.id)
+ if (!instance) throw new Error('Missing instance')
+ const target = graph.getChildren(instance.id).find((node) => node.componentId === source.id)
+ if (!target) throw new Error('Missing target')
+ instance.childIds.reverse()
+ expect(findComponentPropertyTarget(graph, instance, 'show')?.node.id).toBe(target.id)
+})
diff --git a/packages/scene-graph/tests/components/scale.test.ts b/packages/scene-graph/tests/components/scale.test.ts
new file mode 100644
index 000000000..d0a3a4a4a
--- /dev/null
+++ b/packages/scene-graph/tests/components/scale.test.ts
@@ -0,0 +1,72 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph, rescaleNodeTree } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../helpers/assert'
+
+test('nested synchronization converts between explicit source and occurrence coordinates', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const inner = graph.createNode('COMPONENT', page, { paddingTop: 4 })
+ graph.createNode('RECTANGLE', inner.id, { width: 20, height: 20 })
+ const outer = graph.createNode('COMPONENT', page)
+ const template = expectDefined(graph.createInstance(inner.id, outer.id), 'template')
+ rescaleNodeTree(graph, template.id, 0.5)
+ const placed = expectDefined(graph.createInstance(outer.id, page), 'placed')
+ rescaleNodeTree(graph, placed.id, 0.5)
+ const nested = expectDefined(graph.getChildren(placed.id)[0], 'nested')
+ expect(nested.componentScale).toBe(0.25)
+ graph.updateNode(inner.id, { paddingTop: 8 })
+ graph.syncInstances(inner.id)
+ expect(template.paddingTop).toBe(4)
+ graph.syncInstances(outer.id)
+ expect(nested.paddingTop).toBe(2)
+ expect(graph.getChildren(nested.id)[0].width).toBe(5)
+ graph.createNode('RECTANGLE', inner.id, { width: 12, height: 16 })
+ graph.syncInstances(inner.id)
+ graph.syncInstances(outer.id)
+ expect(graph.getChildren(nested.id)[1].width).toBe(3)
+ expect(graph.getChildren(nested.id)[1].componentScale).toBe(0.25)
+})
+
+test('definition rescaling updates existing descendant coordinate scales', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const inner = graph.createNode('COMPONENT', page, {
+ width: 50,
+ height: 28,
+ paddingLeft: 20,
+ paddingRight: 10
+ })
+ graph.createNode('RECTANGLE', inner.id, { width: 20, height: 20 })
+ const outer = graph.createNode('COMPONENT', page)
+ const template = expectDefined(graph.createInstance(inner.id, outer.id))
+ rescaleNodeTree(graph, template.id, 0.5)
+ const placed = expectDefined(graph.createInstance(outer.id, page))
+ rescaleNodeTree(graph, placed.id, 0.25)
+ const nested = graph.getChildren(placed.id)[0]
+ expect(nested.width).toBe(6.25)
+ rescaleNodeTree(graph, template.id, 2)
+ graph.syncInstances(outer.id)
+ expect(nested.width).toBe(12.5)
+ expect(nested.height).toBe(7)
+ expect(nested.paddingLeft).toBe(5)
+ expect(nested.paddingRight).toBe(2.5)
+ expect(nested.componentScale).toBe(0.25)
+ expect(graph.getChildren(nested.id)[0].componentScale).toBe(0.25)
+})
+
+test('rescaling updates live binding and declaration conversions without scaling opacity units', () => {
+ const graph = new SceneGraph()
+ const root = graph.createNode('INSTANCE', graph.getPages()[0].id, {
+ variableBindingScales: { paddingLeft: 0.25, opacity: 0.01 },
+ variableAssignmentScales: { paddingLeft: 0.5, opacity: 0.01 },
+ boundVariables: { paddingLeft: 'padding', opacity: 'opacity' },
+ componentScale: 0.5
+ })
+ rescaleNodeTree(graph, root.id, 0.5)
+ expect(root.componentScale).toBe(0.25)
+ expect(root.variableBindingScales).toEqual({ paddingLeft: 0.125, opacity: 0.01 })
+ expect(root.variableAssignmentScales.paddingLeft).toBe(0.25)
+ expect(root.variableAssignmentScales.opacity).toBe(0.01)
+})
diff --git a/packages/scene-graph/tests/components/sync-field-contract.test.ts b/packages/scene-graph/tests/components/sync-field-contract.test.ts
new file mode 100644
index 000000000..995bdf3e1
--- /dev/null
+++ b/packages/scene-graph/tests/components/sync-field-contract.test.ts
@@ -0,0 +1,50 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph, setInstanceOverride } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../helpers/assert'
+
+for (const protectedField of ['width', 'text'] as const) {
+ test(`component synchronization preserves ${protectedField} without freezing other fields`, () => {
+ const graph = new SceneGraph()
+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id)
+ const source = graph.createNode('TEXT', component.id, {
+ text: 'Source',
+ visible: false,
+ width: 80
+ })
+ const instance = expectDefined(graph.createInstance(component.id, graph.getPages()[0].id))
+ const clone = graph.getChildren(instance.id)[0]
+ graph.updateNode(clone.id, { text: 'Override', visible: true, width: 160 })
+ setInstanceOverride(instance.instanceOverrides, instance.id, clone.id, protectedField, true)
+ graph.syncInstances(component.id)
+ expect(clone.text).toBe(protectedField === 'text' ? 'Override' : source.text)
+ expect(clone.width).toBe(protectedField === 'width' ? 160 : 80)
+ expect(clone.visible).toBe(false)
+ })
+}
+
+test('component synchronization updates and removes opacity bindings while preserving a claimed width binding', () => {
+ const graph = new SceneGraph()
+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id, {
+ opacity: 0.5,
+ boundVariables: { opacity: 'opacity-var' }
+ })
+ const instance = expectDefined(graph.createInstance(component.id, graph.getPages()[0].id))
+ expect(instance.opacity).toBe(0.5)
+ expect(instance.boundVariables.opacity).toBe('opacity-var')
+ graph.updateNode(instance.id, {
+ boundVariables: { ...instance.boundVariables, width: 'width-var' }
+ })
+ setInstanceOverride(
+ instance.instanceOverrides,
+ instance.id,
+ instance.id,
+ 'boundVariables/width',
+ true
+ )
+ graph.updateNode(component.id, { opacity: 1, boundVariables: {} })
+ graph.syncInstances(component.id)
+ expect(instance.boundVariables).toEqual({ width: 'width-var' })
+ expect(instance.opacity).toBe(1)
+})
diff --git a/packages/scene-graph/tests/text/layout-invalidation.test.ts b/packages/scene-graph/tests/text/layout-invalidation.test.ts
new file mode 100644
index 000000000..0c8432ca8
--- /dev/null
+++ b/packages/scene-graph/tests/text/layout-invalidation.test.ts
@@ -0,0 +1,71 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph, copyStyleRuns } from '@open-pencil/scene-graph'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+const shapingEdits: Partial<SceneNode>[] = [
+ { fontVariations: [{ axis: 'wght', value: 600 }] },
+ { fontFeatures: [{ tag: 'liga', enabled: false }] },
+ { textAlignHorizontal: 'RIGHT' },
+ { textAlignVertical: 'BOTTOM' },
+ { height: 80 }
+]
+for (const change of shapingEdits) {
+ test(`invalidates saved glyph placement for ${Object.keys(change)[0]}`, () => {
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Text',
+ derivedTextGlyphs: [{ commandsBlob: new Uint8Array([0]), x: 0, y: 10, fontSize: 12 }]
+ })
+ graph.updateNode(node.id, change)
+ expect(node.derivedTextGlyphs).toBeNull()
+ })
+}
+
+for (const field of ['width', 'textAutoResize', 'maxLines'] as const) {
+ test(`changing ${field} invalidates saved glyphs but supplying new glyphs preserves them`, () => {
+ const graph = new SceneGraph()
+ const glyphs = [{ commandsBlob: new Uint8Array([0]), x: 0, y: 10, fontSize: 12 }]
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Text',
+ derivedTextGlyphs: glyphs
+ })
+ const changes = { width: 120, textAutoResize: 'HEIGHT' as const, maxLines: 2 }
+ graph.updateNode(node.id, { [field]: changes[field] })
+ expect(node.derivedTextGlyphs).toBeNull()
+ graph.updateNode(node.id, { [field]: changes[field], derivedTextGlyphs: glyphs })
+ expect(node.derivedTextGlyphs).toEqual(glyphs)
+ })
+}
+
+for (const preview of [false, true]) {
+ test(`equal layout updates preserve saved glyphs (preview=${preview})`, () => {
+ const graph = new SceneGraph()
+ const glyphs = [{ commandsBlob: new Uint8Array([0]), x: 0, y: 10, fontSize: 12 }]
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Text',
+ derivedTextGlyphs: glyphs
+ })
+ const update = preview ? graph.updateNodePreview.bind(graph) : graph.updateNode.bind(graph)
+ update(node.id, {
+ width: node.width,
+ height: node.height,
+ styleRuns: copyStyleRuns(node.styleRuns)
+ })
+ expect(node.derivedTextGlyphs).toEqual(glyphs)
+ })
+ test(`text layout cache invalidation preserves supplied replacements (preview=${preview})`, () => {
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Initial',
+ derivedLayout: { width: 67, height: 24 }
+ })
+ const update = preview ? graph.updateNodePreview.bind(graph) : graph.updateNode.bind(graph)
+ update(node.id, { opacity: 0.5 })
+ expect(node.derivedLayout).toEqual({ width: 67, height: 24 })
+ update(node.id, { text: 'Replacement', derivedLayout: { width: 120, height: 24 } })
+ expect(node.derivedLayout).toEqual({ width: 120, height: 24 })
+ update(node.id, { fontSize: 20 })
+ expect(node.derivedLayout).toBeNull()
+ })
+}
diff --git a/packages/scene-graph/tests/transfer/apply.test.ts b/packages/scene-graph/tests/transfer/apply.test.ts
new file mode 100644
index 000000000..8fa32cb4b
--- /dev/null
+++ b/packages/scene-graph/tests/transfer/apply.test.ts
@@ -0,0 +1,93 @@
+import { expect, test } from 'bun:test'
+
+import {
+ applyGraphTransfer,
+ prepareGraphTransfer,
+ SceneGraph,
+ CommittedGraphEventError
+} from '@open-pencil/scene-graph'
+
+function setup() {
+ const source = new SceneGraph(),
+ target = new SceneGraph()
+ const root = source.createNode('FRAME', source.getPages()[0].id)
+ source.createNode('RECTANGLE', root.id)
+ const collection = source.createCollection('Spacing')
+ source.createVariable('Spacing', 'FLOAT', collection.id, 12)
+ source.images.set('existing', new Uint8Array([1]))
+ source.images.set('new', new Uint8Array([2]))
+ target.images.set('existing', new Uint8Array([1]))
+ const plan = prepareGraphTransfer({
+ source,
+ target,
+ rootIds: [root.id],
+ dependencyPageIds: [],
+ parentId: target.getPages()[0].id
+ })
+ return { target, plan }
+}
+
+test('transfer events see the complete graph and repeated insertion cannot overwrite it', () => {
+ const { target, plan } = setup()
+ target.onNodeEvents({
+ created: () => expect(target.getChildren(plan.rootIds[0])).toHaveLength(1)
+ })
+ applyGraphTransfer(target, plan)
+ expect(() => applyGraphTransfer(target, plan)).toThrow('Transfer identity collision')
+})
+
+test('transfer rolls back inserted nodes and buffered events on mutation failure', () => {
+ const { target, plan } = setup()
+ const before = [...target.nodes.keys()]
+ let events = 0
+ target.onNodeEvents({ created: () => events++ })
+ const create = target.createNodeWithId.bind(target)
+ let calls = 0
+ target.createNodeWithId = (...args) => {
+ if (++calls === 2) throw new Error('Injected mutation failure')
+ return create(...args)
+ }
+ expect(() => applyGraphTransfer(target, plan)).toThrow('Injected mutation failure')
+ expect([...target.nodes.keys()]).toEqual(before)
+ expect(target.getChildren(target.getPages()[0].id)).toHaveLength(0)
+ expect(events).toBe(0)
+ expect(target.variables.size).toBe(0)
+ expect(target.variableCollections.size).toBe(0)
+ expect(target.activeMode.size).toBe(0)
+ expect([...target.images]).toEqual([['existing', new Uint8Array([1])]])
+})
+
+test('tampered resource ownership cannot change an existing destination collection', () => {
+ const { target, plan } = setup()
+ const existing = target.createCollection('Existing')
+ plan.variables[0].collectionId = existing.id
+ expect(() => applyGraphTransfer(target, plan)).toThrow('Invalid variable membership')
+ expect(existing.variableIds).toEqual([])
+ expect(target.variableCollections.size).toBe(1)
+})
+
+for (const corruption of ['binding', 'override', 'topology'] as const) {
+ test(`commit rejects tampered ${corruption} references before inserting resources`, () => {
+ const { target, plan } = setup()
+ if (corruption === 'binding') plan.nodes[0].props.boundVariables = { paddingLeft: 'missing' }
+ if (corruption === 'override')
+ plan.nodes[0].props.instanceOverrides?.descendants.set('missing', new Map())
+ if (corruption === 'topology') plan.rootIds.push(plan.nodes[1].id)
+ const before = [...target.nodes.keys()]
+ expect(() => applyGraphTransfer(target, plan)).toThrow()
+ expect([...target.nodes.keys()]).toEqual(before)
+ expect(target.variables.size).toBe(0)
+ expect(target.variableCollections.size).toBe(0)
+ })
+}
+
+test('observer failure reports committed transfer instead of rolling it back', () => {
+ const { target, plan } = setup()
+ target.onNodeEvents({
+ created: () => {
+ throw new Error('Observer')
+ }
+ })
+ expect(() => applyGraphTransfer(target, plan)).toThrow(CommittedGraphEventError)
+ expect(target.getChildren(plan.rootIds[0])).toHaveLength(1)
+})
diff --git a/packages/scene-graph/tests/transfer/history.test.ts b/packages/scene-graph/tests/transfer/history.test.ts
new file mode 100644
index 000000000..1c4490bc6
--- /dev/null
+++ b/packages/scene-graph/tests/transfer/history.test.ts
@@ -0,0 +1,33 @@
+import { expect, test } from 'bun:test'
+
+import {
+ applyGraphTransfer,
+ captureTransferredState,
+ prepareGraphTransfer,
+ SceneGraph
+} from '@open-pencil/scene-graph'
+
+test('history captures post-placement geometry and separates reused image ownership', () => {
+ const source = new SceneGraph(),
+ target = new SceneGraph()
+ const root = source.createNode('FRAME', source.getPages()[0].id)
+ source.images.set('shared', new Uint8Array([1]))
+ source.images.set('new', new Uint8Array([2]))
+ target.images.set('shared', new Uint8Array([1]))
+ const plan = prepareGraphTransfer({
+ source,
+ target,
+ rootIds: [root.id],
+ dependencyPageIds: [],
+ parentId: target.getPages()[0].id
+ })
+ applyGraphTransfer(target, plan)
+ target.updateNode(plan.rootIds[0], { x: 120, y: 60 })
+ const snapshot = captureTransferredState(target, plan)
+ expect(snapshot.nodes[0].props).toMatchObject({ x: 120, y: 60 })
+ expect(plan.nodes[0].props.x).toBe(0)
+ target.updateNode(plan.rootIds[0], { x: 200 })
+ expect(snapshot.nodes[0].props.x).toBe(120)
+ target.deleteNode(plan.rootIds[0])
+ expect(() => captureTransferredState(target, plan)).toThrow('Missing transferred node')
+})
diff --git a/packages/scene-graph/tests/transfer/nodes.test.ts b/packages/scene-graph/tests/transfer/nodes.test.ts
new file mode 100644
index 000000000..589cd479d
--- /dev/null
+++ b/packages/scene-graph/tests/transfer/nodes.test.ts
@@ -0,0 +1,60 @@
+import { expect, test } from 'bun:test'
+
+import {
+ prepareNodeTransfer,
+ SceneGraph,
+ type NodeTransferReferences
+} from '@open-pencil/scene-graph'
+
+const references = (): NodeTransferReferences => ({
+ nodes: new Map([['component', 'new-component']]),
+ variables: new Map([['token', 'new-token']]),
+ collections: new Map([['set', 'new-set']]),
+ modes: new Map([['mode', 'new-mode']]),
+ styles: new Map([['style', 'new-style']]),
+ properties: new Map([
+ ['swap', 'new-swap'],
+ ['text', 'new-text']
+ ]),
+ propertyTypes: new Map([
+ ['swap', 'INSTANCE_SWAP'],
+ ['text', 'TEXT']
+ ])
+})
+
+test('node preparation remaps typed runtime references but preserves source identities and text', () => {
+ const graph = new SceneGraph()
+ const node = graph.createNode('INSTANCE', graph.getPages()[0].id, {
+ componentId: 'component',
+ text: 'component',
+ fillStyleId: 'style',
+ boundVariables: { paddingLeft: 'token' },
+ variableModes: { set: 'mode' },
+ componentPropertyAssignments: { swap: 'component', text: 'component' },
+ componentPropertyDefinitions: [
+ { id: 'swap', name: 'Swap', type: 'INSTANCE_SWAP', defaultValue: 'component' }
+ ]
+ })
+ node.source.id = 'component'
+ const before = structuredClone(node)
+ const result = prepareNodeTransfer(node, references())
+ expect(result.componentId).toBe('new-component')
+ expect(result.text).toBe('component')
+ expect(result.source?.id).toBe('component')
+ expect(result.fillStyleId).toBe('new-style')
+ expect(result.boundVariables).toEqual({ paddingLeft: 'new-token' })
+ expect(result.variableModes).toEqual({ 'new-set': 'new-mode' })
+ expect(result.componentPropertyAssignments).toEqual({
+ 'new-swap': 'new-component',
+ 'new-text': 'component'
+ })
+ expect(result.componentPropertyDefinitions?.[0].defaultValue).toBe('new-component')
+ expect(node).toEqual(before)
+ expect(result.source).not.toBe(node.source)
+})
+
+test('node preparation fails on missing runtime references before destination mutation', () => {
+ const graph = new SceneGraph()
+ const node = graph.createNode('INSTANCE', graph.getPages()[0].id, { componentId: 'missing' })
+ expect(() => prepareNodeTransfer(node, references())).toThrow('Missing node transfer mapping')
+})
diff --git a/packages/scene-graph/tests/transfer/variables.test.ts b/packages/scene-graph/tests/transfer/variables.test.ts
new file mode 100644
index 000000000..0abcd7cc5
--- /dev/null
+++ b/packages/scene-graph/tests/transfer/variables.test.ts
@@ -0,0 +1,84 @@
+import { expect, test } from 'bun:test'
+
+import {
+ prepareVariableTransfer,
+ type Variable,
+ type VariableCollection
+} from '@open-pencil/scene-graph'
+
+const collections: VariableCollection[] = [
+ {
+ id: 'set',
+ name: 'Tokens',
+ modes: [{ modeId: 'mode', name: 'Default' }],
+ defaultModeId: 'mode',
+ variableIds: ['color', 'alias']
+ }
+]
+const variables: Variable[] = [
+ {
+ id: 'color',
+ collectionId: 'set',
+ name: 'color',
+ type: 'COLOR',
+ description: '',
+ hiddenFromPublishing: false,
+ valuesByMode: { mode: { r: 1, g: 0, b: 0, a: 1 } }
+ },
+ {
+ id: 'alias',
+ collectionId: 'set',
+ name: 'alias',
+ type: 'COLOR',
+ description: '',
+ hiddenFromPublishing: false,
+ valuesByMode: { mode: { aliasId: 'color' } }
+ }
+]
+const references = () => ({
+ variables: new Map([
+ ['color', 'new-color'],
+ ['alias', 'new-alias']
+ ]),
+ collections: new Map([['set', 'new-set']]),
+ modes: new Map([['mode', 'new-mode']])
+})
+
+test('variable transfer remaps resource membership, modes, and aliases with isolated values', () => {
+ const before = structuredClone({ variables, collections })
+ const prepared = prepareVariableTransfer(variables, collections, references())
+ expect(prepared.collections[0]).toMatchObject({
+ id: 'new-set',
+ defaultModeId: 'new-mode',
+ variableIds: ['new-color', 'new-alias']
+ })
+ expect(prepared.variables[1]).toMatchObject({
+ id: 'new-alias',
+ collectionId: 'new-set',
+ valuesByMode: { 'new-mode': { aliasId: 'new-color' } }
+ })
+ expect(prepared.variables[0].valuesByMode['new-mode']).not.toBe(variables[0].valuesByMode.mode)
+ prepared.collections[0].modes[0].name = 'Changed'
+ expect({ variables, collections }).toEqual(before)
+})
+
+test('variable transfer rejects missing references and target collisions before mutation', () => {
+ const invalidMode = structuredClone(variables)
+ invalidMode[0].valuesByMode = { other: 12 }
+ expect(() => prepareVariableTransfer(invalidMode, collections, references())).toThrow(
+ 'Unknown mode'
+ )
+ expect(() =>
+ prepareVariableTransfer([...variables, variables[0]], collections, references())
+ ).toThrow('Duplicate source')
+ const missing = references()
+ missing.variables.delete('color')
+ expect(() => prepareVariableTransfer(variables, collections, missing)).toThrow(
+ 'Missing variable transfer mapping'
+ )
+ const collision = references()
+ collision.variables.set('alias', 'new-color')
+ expect(() => prepareVariableTransfer(variables, collections, collision)).toThrow(
+ 'Colliding variable'
+ )
+})
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index c11c4b7a6..cd2e0280c 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -2,9 +2,8 @@ import { promiseTimeout } from '@vueuse/core'
import { shallowRef, computed, triggerRef } from 'vue'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
-import { findFigThumbnailPageId } from '@open-pencil/core/io/formats/fig'
+import { findFigThumbnailPageId, populateFigPage } from '@open-pencil/core/io/formats/fig'
import { renderThumbnail } from '@open-pencil/core/io/formats/raster'
-import { populateLazyFigImportRoots } from '@open-pencil/core/kiwi'
import { computeAllLayouts } from '@open-pencil/core/layout'
import type { SceneGraph } from '@open-pencil/scene-graph'
@@ -215,7 +214,7 @@ async function readFigForTab(file: File, signal?: AbortSignal): Promise<SceneGra
if (firstPageId) computeAllLayouts(imported, firstPageId)
const coverPageId = findFigThumbnailPageId(imported.getPages())
if (coverPageId && coverPageId !== firstPageId) {
- populateLazyFigImportRoots(imported, [coverPageId])
+ populateFigPage(imported, coverPageId)
computeAllLayouts(imported, coverPageId)
}
return imported
diff --git a/tests/AGENTS.md b/tests/AGENTS.md
index 1492408ce..42cfa45d7 100644
--- a/tests/AGENTS.md
+++ b/tests/AGENTS.md
@@ -5,7 +5,7 @@
## Placement
- Package-local tests mirror source domains under `packages/<owner>/tests/`; central app tests mirror `src/app/**` under `tests/app/`; `tests/integration/` requires a genuinely cross-owner contract; E2E under `tests/e2e/` follows user workflows; native and Figma acceptance are explicit exceptions.
-- Existing `tests/engine/**` domains migrate together with runner discovery: `tools/dev/unit-tests/src/shards.ts` lists each owner's canonical home and its current `tests/engine` directories, so a move is a `git mv` plus imports. `bun run check:test-homes` rejects any test added under `tests/engine` and any stale entry in `tools/dev/unit-tests/engine-baseline.txt`; new tests go to the canonical home, and a moved file is removed from the baseline (`--write` regenerates it). Scene Graph has migrated to `packages/scene-graph/tests` and the editor domain to `packages/core/tests/editor`; put new Core tests there, mirroring `packages/core/src`.
+- Existing `tests/engine/**` domains migrate together with runner discovery: `tools/dev/unit-tests/src/shards.ts` lists each owner's canonical home and its current `tests/engine` directories, so a move is a `git mv` plus imports. `bun run check:test-homes` rejects any test added under `tests/engine` and any stale entry in `tools/checks/test-homes/engine-baseline.txt`; new tests go to the canonical home, and a moved file is removed from the baseline (`--write` regenerates it). Scene Graph has migrated to `packages/scene-graph/tests` and the editor domain to `packages/core/tests/editor`; put new Core tests there, mirroring `packages/core/src`.
- Owner-local helpers and fixtures stay local; only genuinely shared support goes under central `tests/helpers/<domain>/` and `tests/fixtures/`. MCP transport tests: `tests/engine/mcp/{server,stdio,transport}` with `tests/helpers/mcp`.
- Never commit temporary, diagnostic, or profile specs; keep them in ignored `scratch/`.
diff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts b/tests/e2e/canvas/instance-scale-visual.spec.ts
new file mode 100644
index 000000000..e079d2c81
--- /dev/null
+++ b/tests/e2e/canvas/instance-scale-visual.spec.ts
@@ -0,0 +1,178 @@
+import { pick } from 'es-toolkit/object'
+import { toUint8Array } from 'js-base64'
+
+import { computeAllLayouts, computeLayout } from '@open-pencil/core/layout'
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import {
+ reconcileNumericVariableBindings,
+ rescaleNodeTree,
+ type SceneNode,
+ type SceneGraph
+} from '@open-pencil/scene-graph'
+
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import bindingFixture from '#tests/fixtures/nested-binding-ownership-records.json' with { type: 'json' }
+import fixture from '#tests/fixtures/nested-layout-scale.json' with { type: 'json' }
+import { absoluteConstraintRecords } from '#tests/helpers/fig/absolute-constraints'
+import { inheritedNestedBindingRecords } from '#tests/helpers/fig/nested-binding'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+const fields = [
+ 'type',
+ 'x',
+ 'y',
+ 'width',
+ 'height',
+ 'fills',
+ 'strokes',
+ 'strokeWeight',
+ 'cornerRadius',
+ 'opacity',
+ 'visible'
+] as const
+interface RenderNode {
+ props: Pick<SceneNode, (typeof fields)[number]>
+ children: RenderNode[]
+}
+
+function interpretedTree(phase: 'before' | 'edited'): RenderNode {
+ const { graph, sources } = materializeDocument(
+ [{ guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT' }, ...fixture[phase]] as NodeChange[],
+ fixture.blobs.map((value) => toUint8Array(value)),
+ { derivedBounds: true }
+ )
+ computeAllLayouts(graph)
+ const rootId = sources.get(fixture.ids.instance)
+ if (!rootId) throw new Error('Missing scaled instance')
+ return renderTree(graph, rootId)
+}
+
+function renderTree(graph: SceneGraph, rootId: string): RenderNode {
+ const visit = (id: string): RenderNode => {
+ const node = graph.getNode(id)
+ if (!node) throw new Error(`Missing node ${id}`)
+ return {
+ props: pick(node, fields),
+ children: graph.getChildren(id).map((child) => visit(child.id))
+ }
+ }
+ return visit(rootId)
+}
+
+async function renderTrees(trees: RenderNode[]) {
+ await editor.page.evaluate((trees) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Missing editor')
+ const visit = (tree: RenderNode, parentId: string) => {
+ const { type, ...props } = tree.props
+ const node = store.graph.createNode(type, parentId, props)
+ for (const child of tree.children) visit(child, node.id)
+ }
+ for (const [index, tree] of trees.entries()) {
+ tree.props.x = 20 + index * 60
+ tree.props.y = 20
+ visit(tree, store.state.currentPageId)
+ }
+ store.setZoomAroundPoint(6, 0, 0)
+ store.requestRender()
+ }, trees)
+}
+
+test('absolute constraints survive occurrence resizing', async () => {
+ const { graph, sources } = materializeDocument(absoluteConstraintRecords())
+ const id = sources.get('1:4')
+ if (!id) throw new Error('Missing constrained instance')
+ const child = graph.getChildren(id)[0]
+ expect([child.x, child.y, child.width, child.height]).toEqual([180, 10, 10, 100])
+ await renderTrees([renderTree(graph, id)])
+ await editor.page.evaluate(() => window.openPencil?.getStore?.().setZoomAroundPoint(2, 0, 0))
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot(
+ 'absolute-constraint-resize.png'
+ )
+})
+
+test('nested scale preserves before and edited padding after layout', async () => {
+ await renderTrees([interpretedTree('before'), interpretedTree('edited')])
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('nested-layout-scale.png')
+})
+
+test('saved inherited expressions follow token edits without double scaling', async () => {
+ const { graph, sources } = materializeDocument(
+ inheritedNestedBindingRecords(),
+ bindingFixture.blobs.map((value) => toUint8Array(value)),
+ { derivedBounds: true }
+ )
+ const rootId = sources.get('293733:8')
+ if (!rootId) throw new Error('Missing captured instance')
+ const nested = graph.getChildren(rootId)[0]
+ const variable = graph.variables.get(nested.boundVariables.paddingLeft)
+ if (!variable) throw new Error('Missing inherited expression binding')
+ computeLayout(graph, nested.id)
+ computeLayout(graph, rootId)
+ expect(nested.paddingLeft).toBe(5)
+ const before = renderTree(graph, rootId)
+ variable.valuesByMode[graph.getNodeVariableModeId(nested.id, variable.collectionId)] = 40
+ reconcileNumericVariableBindings(graph)
+ computeLayout(graph, nested.id)
+ computeLayout(graph, rootId)
+ expect(nested.paddingLeft).toBe(10)
+ await renderTrees([before, renderTree(graph, rootId)])
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot(
+ 'expression-layout-scale.png'
+ )
+})
+
+test('definition rescale updates existing occurrence geometry', async () => {
+ const { graph, sources } = materializeDocument(
+ inheritedNestedBindingRecords(),
+ bindingFixture.blobs.map((value) => toUint8Array(value)),
+ { derivedBounds: true }
+ )
+ const root = sources.get('293733:8'),
+ outer = sources.get('1:4')
+ if (!root || !outer) throw new Error('Missing captured sources')
+ rescaleNodeTree(graph, root, 0.5)
+ computeAllLayouts(graph)
+ const before = renderTree(graph, root)
+ rescaleNodeTree(graph, graph.getChildren(outer)[0].id, 2)
+ graph.syncInstances(outer)
+ computeAllLayouts(graph)
+ const nested = graph.getChildren(root)[0]
+ expect([graph.getNode(root)?.width, nested.width, nested.paddingLeft]).toEqual([22.5, 12.5, 5])
+ await renderTrees([before, renderTree(graph, root)])
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot(
+ 'definition-layout-scale.png'
+ )
+})
+
+for (const operation of ['component', 'rescale'] as const) {
+ test(`${operation} edits preserve scaled geometry and authored bindings`, async () => {
+ const { graph, sources } = materializeDocument(
+ bindingFixture.nodeChanges as NodeChange[],
+ bindingFixture.blobs.map((value) => toUint8Array(value)),
+ { derivedBounds: true }
+ )
+ const rootId = sources.get('293733:8'),
+ component = sources.get('1:2')
+ if (!rootId || !component) throw new Error('Missing captured sources')
+ const nested = graph.getChildren(rootId)[0]
+ graph.bindVariable(rootId, 'paddingRight', '293742:7')
+ graph.bindVariable(nested.id, 'paddingRight', '293742:7')
+ reconcileNumericVariableBindings(graph)
+ computeLayout(graph, nested.id)
+ computeLayout(graph, rootId)
+ const before = renderTree(graph, rootId)
+ if (operation === 'component') {
+ graph.updateNode(component, { paddingTop: 8 })
+ graph.syncInstances(component)
+ } else rescaleNodeTree(graph, rootId, 0.5)
+ computeAllLayouts(graph)
+ expect(nested.paddingTop).toBe(operation === 'component' ? 2 : 0.5)
+ expect(nested.paddingRight).toBe(operation === 'component' ? 6 : 3)
+ await renderTrees([before, renderTree(graph, rootId)])
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot(
+ `${operation}-layout-scale.png`
+ )
+ })
+}
diff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/absolute-constraint-resize-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/absolute-constraint-resize-openpencil-darwin.png
new file mode 100644
index 000000000..f63afd703
Binary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/absolute-constraint-resize-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/component-layout-scale-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/component-layout-scale-openpencil-darwin.png
new file mode 100644
index 000000000..c53f5cd09
Binary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/component-layout-scale-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/definition-layout-scale-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/definition-layout-scale-openpencil-darwin.png
new file mode 100644
index 000000000..80ba96f13
Binary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/definition-layout-scale-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/expression-layout-scale-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/expression-layout-scale-openpencil-darwin.png
new file mode 100644
index 000000000..3b889dec4
Binary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/expression-layout-scale-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/nested-layout-scale-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/nested-layout-scale-openpencil-darwin.png
new file mode 100644
index 000000000..2fa98e2bd
Binary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/nested-layout-scale-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/rescale-layout-scale-openpencil-darwin.png b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/rescale-layout-scale-openpencil-darwin.png
new file mode 100644
index 000000000..3112a2b7a
Binary files /dev/null and b/tests/e2e/canvas/instance-scale-visual.spec.ts-snapshots/rescale-layout-scale-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/occurrence-text-visual.spec.ts b/tests/e2e/canvas/occurrence-text-visual.spec.ts
new file mode 100644
index 000000000..25a752059
--- /dev/null
+++ b/tests/e2e/canvas/occurrence-text-visual.spec.ts
@@ -0,0 +1,63 @@
+import { interpretInstance } from '@open-pencil/fig/instance-overrides'
+import { nodeChangeToProps } from '@open-pencil/fig/node-change'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import fixture from '#tests/fixtures/styled-saved-glyphs.json' with { type: 'json' }
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+test('occurrence override renders new text rather than inherited source glyphs', async () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const source: NodeChange[] = [
+ { guid: guid(1), type: 'SYMBOL' },
+ {
+ guid: guid(2),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1), position: '!' },
+ textData: { characters: fixture.text },
+ fontName: { family: 'Inter', style: 'Regular' },
+ fontSize: 40,
+ size: { x: 450, y: 60 },
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ derivedTextData: {
+ glyphs: fixture.derivedTextGlyphs.map((glyph, index) => ({
+ commandsBlob: index,
+ position: { x: glyph.x, y: glyph.y },
+ fontSize: glyph.fontSize,
+ firstCharacter: glyph.firstCharacter
+ }))
+ }
+ },
+ {
+ guid: guid(3),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1),
+ symbolOverrides: [{ guidPath: { guids: [guid(2)] }, textData: { characters: 'Toolbars' } }]
+ }
+ } as NodeChange
+ ]
+ const occurrence = interpretInstance(source, '1:3')
+ const props = nodeChangeToProps(
+ occurrence.children[0].properties,
+ fixture.derivedTextGlyphs.map((glyph) => new Uint8Array(glyph.commandsBlob))
+ )
+ expect(props.derivedTextGlyphs).toHaveLength(0)
+ await editor.page.evaluate((props) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Missing editor')
+ const { nodeType, ...values } = props
+ if (nodeType !== 'TEXT') throw new Error('Expected text')
+ store.graph.createNode(nodeType, store.state.currentPageId, {
+ ...values,
+ x: 80,
+ y: 100,
+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]
+ })
+ store.requestRender()
+ }, props)
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot(
+ 'occurrence-text-override.png'
+ )
+})
diff --git a/tests/e2e/canvas/occurrence-text-visual.spec.ts-snapshots/occurrence-text-override-openpencil-darwin.png b/tests/e2e/canvas/occurrence-text-visual.spec.ts-snapshots/occurrence-text-override-openpencil-darwin.png
new file mode 100644
index 000000000..dc11e6829
Binary files /dev/null and b/tests/e2e/canvas/occurrence-text-visual.spec.ts-snapshots/occurrence-text-override-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/saved-glyph-visual.spec.ts b/tests/e2e/canvas/saved-glyph-visual.spec.ts
new file mode 100644
index 000000000..64d07f4df
--- /dev/null
+++ b/tests/e2e/canvas/saved-glyph-visual.spec.ts
@@ -0,0 +1,103 @@
+import type { Fill, StyleRun } from '@open-pencil/scene-graph'
+
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import styledGlyphs from '#tests/fixtures/styled-saved-glyphs.json' with { type: 'json' }
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+test('saved glyphs remain authoritative with an available font and invalidate on edit', async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Missing editor')
+ const bytes = new Uint8Array(37)
+ const view = new DataView(bytes.buffer)
+ for (const [index, [command, x, y]] of [
+ [1, 0, 0],
+ [2, 1, 0],
+ [2, 1, 1],
+ [2, 0, 1]
+ ].entries()) {
+ bytes[index * 9] = command
+ view.setFloat32(index * 9 + 1, x, true)
+ view.setFloat32(index * 9 + 5, y, true)
+ }
+ for (const [index, action] of ['unchanged', 'paint', 'text', 'width', 'runs'].entries()) {
+ const node = store.graph.createNode('TEXT', store.state.currentPageId, {
+ x: 40 + index * 150,
+ y: 100,
+ width: 140,
+ height: 60,
+ text: 'Inter',
+ fontFamily: 'Inter',
+ fontSize: 32,
+ fills: [
+ { type: 'SOLID', color: { r: 0.1, g: 0.2, b: 0.8, a: 1 }, opacity: 1, visible: true }
+ ],
+ derivedTextGlyphs: [{ commandsBlob: bytes.slice(), x: 4, y: 40, fontSize: 32 }]
+ })
+ if (action === 'paint')
+ store.graph.updateNode(node.id, {
+ fills: [
+ { type: 'SOLID', color: { r: 0.8, g: 0.2, b: 0.1, a: 1 }, opacity: 1, visible: true }
+ ]
+ })
+ if (action === 'runs') {
+ store.graph.updateNode(node.id, {
+ styleRuns: [
+ {
+ start: 0,
+ length: 2,
+ style: {
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 0.1, g: 0.7, b: 0.2, a: 1 },
+ opacity: 1,
+ visible: true
+ }
+ ]
+ }
+ }
+ ],
+ derivedTextGlyphs: [
+ { commandsBlob: bytes.slice(), x: 4, y: 40, fontSize: 24, firstCharacter: 0 },
+ { commandsBlob: bytes.slice(), x: 40, y: 40, fontSize: 24, firstCharacter: 2 }
+ ]
+ })
+ }
+ if (action === 'text') store.graph.updateNode(node.id, { text: 'Edited' })
+ if (action === 'width') store.graph.updateNode(node.id, { width: 100 })
+ }
+ store.requestRender()
+ })
+ await editor.page.evaluate((fixture) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Missing editor')
+ store.graph.createNode('TEXT', store.state.currentPageId, {
+ ...fixture,
+ x: 40,
+ y: 220,
+ fills: fixture.fills as Fill[],
+ styleRuns: fixture.styleRuns as StyleRun[],
+ derivedTextGlyphs: fixture.derivedTextGlyphs.map((glyph) => ({
+ ...glyph,
+ commandsBlob: new Uint8Array(glyph.commandsBlob)
+ }))
+ })
+ store.requestRender()
+ }, styledGlyphs)
+ await editor.page.waitForFunction(() => {
+ const store = window.openPencil?.getStore?.()
+ return (
+ store?.graph.getChildren(store.state.currentPageId).filter((node) => node.type === 'TEXT')
+ .length === 6
+ )
+ })
+ await editor.page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ })
+ )
+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('saved-glyph-authority.png')
+})
diff --git a/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/saved-glyph-authority-openpencil-darwin.png b/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/saved-glyph-authority-openpencil-darwin.png
new file mode 100644
index 000000000..c636837c0
Binary files /dev/null and b/tests/e2e/canvas/saved-glyph-visual.spec.ts-snapshots/saved-glyph-authority-openpencil-darwin.png differ
diff --git a/tests/engine/cli/eval.test.ts b/tests/engine/cli/eval.test.ts
index fe336d808..113597708 100644
--- a/tests/engine/cli/eval.test.ts
+++ b/tests/engine/cli/eval.test.ts
@@ -42,6 +42,31 @@ heavy('eval CLI', () => {
expect(stdout.length).toBeGreaterThan(0)
})
+ test('variable API edits reflow layout before returning eval results', async () => {
+ const { stdout, exitCode } = await run([
+ 'eval',
+ FIXTURE,
+ '--json',
+ '--code',
+ `
+ const collection = figma.createVariableCollection('Eval spacing');
+ const variable = figma.createVariable('Padding', 'FLOAT', collection.id, 10);
+ const frame = figma.createFrame();
+ frame.layoutMode = 'HORIZONTAL';
+ frame.primaryAxisSizingMode = 'AUTO';
+ frame.counterAxisSizingMode = 'AUTO';
+ const child = figma.createRectangle();
+ child.resize(5, 5);
+ frame.appendChild(child);
+ figma.bindVariable(frame.id, 'paddingLeft', variable.id);
+ figma.setVariableValue(variable.id, collection.defaultModeId, 20);
+ return { padding: frame.paddingLeft, width: frame.width, childX: child.x };
+ `
+ ])
+ expect(exitCode).toBe(0)
+ expect(JSON.parse(stdout)).toEqual({ padding: 20, width: 25, childX: 20 })
+ })
+
test('returns primitive number', async () => {
const { stdout, exitCode } = await run(['eval', FIXTURE, '--code', 'return 42'])
expect(exitCode).toBe(0)
diff --git a/tests/engine/cli/headless.test.ts b/tests/engine/cli/headless.test.ts
index e9da469ce..ce5da90b5 100644
--- a/tests/engine/cli/headless.test.ts
+++ b/tests/engine/cli/headless.test.ts
@@ -56,31 +56,27 @@ describe('headless CLI lazy .fig preparation', () => {
test('populates only the requested tree page', async () => {
const graph = await createLazyFixture()
const page1Instance = pageInstance(graph, 'Page 1')
- const page2Instance = pageInstance(graph, 'Page 2')
expect(page1Instance ? graph.getChildren(page1Instance.id) : []).toHaveLength(1)
- expect(page2Instance ? graph.getChildren(page2Instance.id) : []).toHaveLength(0)
+ expect(pageInstance(graph, 'Page 2')).toBeUndefined()
prepareDocumentForRPC(graph, 'tree', { page: 'Page 2' })
+ const page2Instance = pageInstance(graph, 'Page 2')
expect(page2Instance ? graph.getChildren(page2Instance.id) : []).toHaveLength(1)
})
test('populates all pages for document-wide searches', async () => {
const graph = await createLazyFixture()
- const page2Instance = pageInstance(graph, 'Page 2')
-
+ expect(pageInstance(graph, 'Page 2')).toBeUndefined()
prepareDocumentForRPC(graph, 'find', {})
-
+ const page2Instance = pageInstance(graph, 'Page 2')
expect(page2Instance ? graph.getChildren(page2Instance.id) : []).toHaveLength(1)
})
test('keeps page listings lazy', async () => {
const graph = await createLazyFixture()
- const page2Instance = pageInstance(graph, 'Page 2')
-
prepareDocumentForRPC(graph, 'pages')
-
- expect(page2Instance ? graph.getChildren(page2Instance.id) : []).toHaveLength(0)
+ expect(pageInstance(graph, 'Page 2')).toBeUndefined()
})
})
diff --git a/tests/engine/core/text/path-layout.test.ts b/tests/engine/core/text/path-layout.test.ts
index ad4f830ab..0801e795d 100644
--- a/tests/engine/core/text/path-layout.test.ts
+++ b/tests/engine/core/text/path-layout.test.ts
@@ -15,7 +15,7 @@ import {
} from '#core/text/path'
import { expectDefined } from '#tests/helpers/assert'
-import { loadFigFixture } from '#tests/helpers/fig-fixtures'
+import { loadFigFixture } from '#tests/helpers/fig/fixtures'
/** Signed shortest angular difference a - b. */
function angleDiff(a: number, b: number): number {
diff --git a/tests/engine/figma/api/components.test.ts b/tests/engine/figma/api/components.test.ts
index cb879fbd5..f31cf35c7 100644
--- a/tests/engine/figma/api/components.test.ts
+++ b/tests/engine/figma/api/components.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, test } from 'bun:test'
+import { hasInstanceOverride } from '@open-pencil/scene-graph'
+
import { expectDefined } from '#tests/helpers/assert'
import { createAPI } from './helpers'
@@ -129,3 +131,55 @@ describe('components', () => {
)
})
})
+
+describe('instance child edits record overrides', () => {
+ test('renaming and resizing an instance child survives component sync and export', () => {
+ const api = createAPI()
+ const component = api.createComponent()
+ const child = api.createRectangle()
+ child.resize(24, 24)
+ component.appendChild(child)
+ const instance = component.createInstance()
+ const instanceChild = expectDefined(instance.children[0], 'instance child')
+ instanceChild.name = 'renamed'
+ instanceChild.resize(32, 32)
+
+ expect(hasInstanceOverride(api.graph, instanceChild.id, 'name')).toBe(true)
+ expect(hasInstanceOverride(api.graph, instanceChild.id, 'width')).toBe(true)
+ child.resize(40, 40)
+ child.name = 'component child'
+ api.graph.syncInstances(component.id)
+ expect(instanceChild.name).toBe('renamed')
+ expect(instanceChild.width).toBe(32)
+ })
+})
+
+describe('applied shared styles on instance children', () => {
+ test('a text style applied inside an instance is an override and follows the component otherwise', () => {
+ const api = createAPI()
+ const graph = api.graph
+ const page = graph.getPages()[0]
+ const heading = graph.createNode('TEXT', page.id, {
+ name: 'Heading',
+ sharedStyleType: 'TEXT',
+ text: 'Ag'
+ })
+ const body = graph.createNode('TEXT', page.id, {
+ name: 'Body',
+ sharedStyleType: 'TEXT',
+ text: 'Ag'
+ })
+ const component = graph.createNode('COMPONENT', page.id, { name: 'Card' })
+ const title = graph.createNode('TEXT', component.id, { name: 'title', text: 'Title' })
+ const first = graph.createInstance(component.id, page.id)
+ const second = graph.createInstance(component.id, page.id)
+ const firstTitle = expectDefined(graph.getChildren(first.id)[0], 'first title')
+ api.wrapNode(firstTitle.id).textStyleId = heading.id
+ expect(hasInstanceOverride(graph, firstTitle.id, 'textStyleId')).toBe(true)
+
+ graph.updateNode(title.id, { textStyleId: body.id })
+ graph.syncInstances(component.id)
+ expect(graph.getNode(firstTitle.id)?.textStyleId).toBe(heading.id)
+ expect(graph.getChildren(second.id)[0]?.textStyleId).toBe(body.id)
+ })
+})
diff --git a/tests/engine/figma/api/layout/plugin-compat.test.ts b/tests/engine/figma/api/layout/plugin-compat.test.ts
index 9b76b8562..a6da4aa54 100644
--- a/tests/engine/figma/api/layout/plugin-compat.test.ts
+++ b/tests/engine/figma/api/layout/plugin-compat.test.ts
@@ -75,6 +75,29 @@ describe('Figma Plugin API layout compatibility', () => {
expect(graph.getNode(text.id)?.width).toBe(200)
})
+ test('rescale rejects occurrence descendants without mutation but permits definition children', () => {
+ const { api, graph } = setup()
+ const page = graph.getPages()[0]
+ const inner = graph.createNode('COMPONENT', page.id)
+ graph.createNode('RECTANGLE', inner.id, { width: 20, height: 10 })
+ const outer = graph.createNode('COMPONENT', page.id)
+ const definition = graph.createInstance(inner.id, outer.id)
+ if (!definition) throw new Error('Missing definition instance')
+ api.getNodeById(definition.id).rescale(2)
+ expect(graph.getChildren(definition.id)[0].width).toBe(40)
+ const owner = graph.createInstance(outer.id, page.id)
+ if (!owner) throw new Error('Missing placed owner')
+ const nested = graph.getChildren(owner.id)[0]
+ const rectangle = graph.getChildren(nested.id)[0]
+ for (const target of [nested, rectangle]) {
+ const before = structuredClone(target)
+ expect(() => api.getNodeById(target.id).rescale(1)).toThrow(
+ 'cannot be overridden in an instance: size'
+ )
+ expect(target).toEqual(before)
+ }
+ })
+
test('rescale rejects non-Figma scale factors and pages', () => {
const { api } = setup()
const rect = api.createRectangle()
diff --git a/tests/engine/io/fig/export/component-properties.test.ts b/tests/engine/io/fig/export/component-properties.test.ts
index a830732d2..61b7159ee 100644
--- a/tests/engine/io/fig/export/component-properties.test.ts
+++ b/tests/engine/io/fig/export/component-properties.test.ts
@@ -1,11 +1,9 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import { exportFigFile, initCodec } from '@open-pencil/core'
-import { parseFigBuffer } from '@open-pencil/fig'
+import { parseFigBuffer, materializeDocument } from '@open-pencil/fig'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { importNodeChanges } from '#core/kiwi/fig/import'
-
describe('Figma component property roundtrip', () => {
beforeAll(async () => {
await initCodec()
@@ -38,9 +36,7 @@ describe('Figma component property roundtrip', () => {
const parsed = parseFigBuffer(
bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
)
- const imported = importNodeChanges(parsed.nodeChanges, parsed.blobs, undefined, {
- populate: 'all'
- })
+ const imported = materializeDocument(parsed.nodeChanges, parsed.blobs).graph
expect(imported.enabledLibraries.get('design-system')).toEqual({
libraryId: 'design-system',
revisionId: 'revision-1',
@@ -100,9 +96,7 @@ describe('Figma component property roundtrip', () => {
const parsed = parseFigBuffer(
bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
)
- const imported = importNodeChanges(parsed.nodeChanges, parsed.blobs, undefined, {
- populate: 'all'
- })
+ const imported = materializeDocument(parsed.nodeChanges, parsed.blobs).graph
const importedSet = [...imported.getAllNodes()].find(
(node) => node.type === 'COMPONENT_SET' && node.name === 'Button'
)
@@ -147,9 +141,7 @@ describe('Figma component property roundtrip', () => {
const parsed = parseFigBuffer(
bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
)
- const imported = importNodeChanges(parsed.nodeChanges, parsed.blobs, undefined, {
- populate: 'all'
- })
+ const imported = materializeDocument(parsed.nodeChanges, parsed.blobs).graph
const importedComponent = [...imported.getAllNodes()].find((node) => node.name === 'Card')
const importedInstance = [...imported.getAllNodes()].find(
(node) => node.name === 'Card instance'
@@ -189,12 +181,10 @@ describe('Figma component property roundtrip', () => {
if (!instance) throw new Error('Expected instance')
instance.source.id = '20:1'
- const imported = importNodeChanges(
+ const imported = materializeDocument(
parseFigBuffer((await exportFigFile(graph)).buffer as ArrayBuffer).nodeChanges,
- [],
- undefined,
- { populate: 'all' }
- )
+ []
+ ).graph
const importedInstance = [...imported.getAllNodes()].find(
(node) => node.name === 'Card instance'
)
@@ -203,12 +193,10 @@ describe('Figma component property roundtrip', () => {
componentPropertyAssignments: { '30:1': 'Edited' }
})
- const reloaded = importNodeChanges(
+ const reloaded = materializeDocument(
parseFigBuffer((await exportFigFile(imported)).buffer as ArrayBuffer).nodeChanges,
- [],
- undefined,
- { populate: 'all' }
- )
+ []
+ ).graph
const reloadedInstance = [...reloaded.getAllNodes()].find(
(node) => node.name === 'Card instance'
)
diff --git a/tests/engine/io/fig/export/lazy-population.test.ts b/tests/engine/io/fig/export/lazy-population.test.ts
index fdd9e161d..b58e34df6 100644
--- a/tests/engine/io/fig/export/lazy-population.test.ts
+++ b/tests/engine/io/fig/export/lazy-population.test.ts
@@ -1,10 +1,6 @@
import { describe, expect, test } from 'bun:test'
import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'
-import {
- getLazyFigImportContext,
- setLazyFigImportContext
-} from '@open-pencil/core/kiwi/fig/lazy-import'
import { cloneSceneGraphForFigExport } from '@open-pencil/core/kiwi/fig/parse/transfer'
import { SceneGraph, setInstanceOverride } from '@open-pencil/scene-graph'
@@ -18,12 +14,6 @@ function lazyExportGraph() {
name: 'Button instance',
componentId: component.id
})
- setLazyFigImportContext(graph, {
- changeMap: new Map(),
- guidToNodeId: new Map(),
- blobs: [],
- populatedRootIds: new Set([firstPage.id])
- })
return { graph, secondPage, instance }
}
@@ -49,24 +39,16 @@ describe('FIG population export lifecycle', () => {
const { graph } = lazyExportGraph()
const image = new Uint8Array([1, 2, 3])
graph.images.set('image', image)
- const context = getLazyFigImportContext(graph)
- expect(context).toBeDefined()
const clone = cloneSceneGraphForFigExport(graph)
- const cloneContext = getLazyFigImportContext(clone)
const firstPage = graph.getPages()[0]
clone.getNode(firstPage.id)?.childIds.push('export-only')
- cloneContext?.populatedRootIds.add('export-only')
expect(graph.getNode(firstPage.id)?.childIds).not.toContain('export-only')
- expect(context?.populatedRootIds).not.toContain('export-only')
expect(clone.images.get('image')).toBe(image)
- expect(cloneContext?.changeMap).toBe(context?.changeMap)
- expect(cloneContext?.guidToNodeId).toBe(context?.guidToNodeId)
- expect(cloneContext?.blobs).toBe(context?.blobs)
})
- test('exports all remaining lazy pages after a partial visit', async () => {
+ test('exports an unexpanded native instance without mutating its live children', async () => {
await initCodec()
const { graph, instance } = lazyExportGraph()
expect(graph.getChildren(instance.id)).toHaveLength(0)
diff --git a/tests/engine/io/fig/export/path-text-reflow-export.test.ts b/tests/engine/io/fig/export/path-text-reflow-export.test.ts
index 41ed77164..cf0e26b85 100644
--- a/tests/engine/io/fig/export/path-text-reflow-export.test.ts
+++ b/tests/engine/io/fig/export/path-text-reflow-export.test.ts
@@ -6,7 +6,7 @@ import { exportFigFile } from '#core/io/formats/fig/export'
import { calibratePathTextLayout, getTextPathData, reflowPathTextGlyphs } from '#core/text/path'
import { expectDefined } from '#tests/helpers/assert'
-import { loadFigFixture } from '#tests/helpers/fig-fixtures'
+import { loadFigFixture } from '#tests/helpers/fig/fixtures'
const LOCAL_CIRCLE_TEXT = 'tests/fixtures/circle-text.fig'
diff --git a/tests/engine/io/fig/export/rotation-transform.test.ts b/tests/engine/io/fig/export/rotation-transform.test.ts
index 98dcaf2f0..dbe060551 100644
--- a/tests/engine/io/fig/export/rotation-transform.test.ts
+++ b/tests/engine/io/fig/export/rotation-transform.test.ts
@@ -16,7 +16,7 @@ import Matrix from '@open-pencil/scene-graph/matrix'
import { exportFigFile } from '#core/io/formats/fig/export'
import { parseFigFile } from '#core/io/formats/fig/read'
-import { loadFigFixture, readFigFixture } from '#tests/helpers/fig-fixtures'
+import { loadFigFixture, readFigFixture } from '#tests/helpers/fig/fixtures'
function worldCorners(graph: SceneGraph, name: string) {
const node = [...graph.getAllNodes()].find((n) => n.name === name)
diff --git a/tests/engine/io/fig/export/text.test.ts b/tests/engine/io/fig/export/text.test.ts
index be59cef95..0a776e0b6 100644
--- a/tests/engine/io/fig/export/text.test.ts
+++ b/tests/engine/io/fig/export/text.test.ts
@@ -10,7 +10,7 @@ import {
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
import { expectDefined } from '#tests/helpers/assert'
-import { parseFixture } from '#tests/helpers/fig-fixtures'
+import { parseFixture } from '#tests/helpers/fig/fixtures'
import { runsHeavyTests } from '#tests/helpers/test-utils'
setDefaultTimeout(60_000)
@@ -222,7 +222,7 @@ describe('text node export', () => {
expect((fontMetaData[0].key as JSONObject).style).toBe('Semi Bold')
})
- test('auto-layout text children export height auto-resize for Figma rendering', async () => {
+ test('auto-layout text children preserve explicit fixed text sizing', async () => {
await initCodec()
const { unzipSync, inflateSync } = await import('fflate')
@@ -266,7 +266,7 @@ describe('text node export', () => {
'text node change'
)
- expect(textNc.textAutoResize).toBe('HEIGHT')
+ expect(textNc.textAutoResize).toBe('NONE')
expect(textNc.lineHeight).toBeUndefined()
expect(textNc.stackChildAlignSelf).toBeUndefined()
})
diff --git a/tests/engine/io/fig/heavy/component-metadata.test.ts b/tests/engine/io/fig/heavy/component-metadata.test.ts
index 8ef7ec421..cd418e94e 100644
--- a/tests/engine/io/fig/heavy/component-metadata.test.ts
+++ b/tests/engine/io/fig/heavy/component-metadata.test.ts
@@ -1,16 +1,20 @@
import { expect, setDefaultTimeout, test } from 'bun:test'
-import { parseFigBuffer } from '@open-pencil/fig'
-
-import { importNodeChanges } from '#core/kiwi'
+import { parseFigBuffer, materializeDocument } from '@open-pencil/fig'
import { expectDefined } from '#tests/helpers/assert'
-import { readFixtureArrayBuffer } from '#tests/helpers/fig-fixtures'
+import { readFixtureArrayBuffer } from '#tests/helpers/fig/fixtures'
import { heavy } from '#tests/helpers/test-utils'
function importFixture(name: string) {
const { nodeChanges, blobs, images } = parseFigBuffer(readFixtureArrayBuffer(name))
- return importNodeChanges(nodeChanges, blobs, new Map(images))
+ // Library default is strict; skip the stale override records Figma keeps, as the app does.
+ return materializeDocument(nodeChanges, blobs, {
+ images: new Map(images),
+ derivedBounds: true,
+ onUnresolvedProperty: () => undefined,
+ onUnresolvedAssignment: () => undefined
+ }).graph
}
setDefaultTimeout(30_000)
@@ -41,8 +45,9 @@ heavy('fig component metadata import', () => {
expect(buttonSet.isPublishable).toBe(true)
expect(buttonSet.symbolDescription).toContain('Buttons communicate actions')
+ // The visible Buttons page copy (57994:2227); internal-only copies carry an http link.
expect(buttonSet.symbolLinks.map((link) => link.uri)).toContain(
- 'http://m3.material.io/components/buttons/overview'
+ 'https://m3.material.io/components/buttons/overview'
)
expect(buttonSet.componentPropertyDefinitions.map((def) => def.name)).toContain('State')
@@ -54,7 +59,7 @@ heavy('fig component metadata import', () => {
)
expect(variant.variantPropSpecs.length).toBeGreaterThan(0)
expect(variant.componentPropertyValues.State).toBe('Disabled')
- expect(variant.componentPropertyValues.Style).toBe('Tonal')
+ expect(Object.keys(variant.componentPropertyValues).sort()).toEqual(['Size', 'State', 'Type'])
expect(Object.keys(variant.componentPropertyValues).some((key) => key.includes(':'))).toBe(
false
)
diff --git a/tests/engine/io/fig/heavy/fixtures.test.ts b/tests/engine/io/fig/heavy/fixtures.test.ts
index 6e55fd18e..6ed26e408 100644
--- a/tests/engine/io/fig/heavy/fixtures.test.ts
+++ b/tests/engine/io/fig/heavy/fixtures.test.ts
@@ -1,78 +1,78 @@
-import { beforeAll, expect, setDefaultTimeout, test } from 'bun:test'
+import { afterAll, beforeAll, expect, setDefaultTimeout, test } from 'bun:test'
import { SceneGraph, type SceneNode } from '@open-pencil/core'
+import { populateFigPage } from '@open-pencil/core/io/formats/fig'
-import { parseFixture, VALID_NODE_TYPES } from '#tests/helpers/fig-fixtures'
-import { collectAllNodes } from '#tests/helpers/fig-traversal'
+import { releaseFigPopulationWorker } from '#core/kiwi/fig/population/client'
+
+import { parseFixture, VALID_NODE_TYPES } from '#tests/helpers/fig/fixtures'
+import { collectAllNodes } from '#tests/helpers/fig/traversal'
import { heavy } from '#tests/helpers/test-utils'
setDefaultTimeout(180_000)
-heavy('parse heavy .fig files', () => {
- let material3: SceneGraph
- let nuxtui: SceneGraph
- let material3Nodes: SceneNode[]
- let nuxtUINodes: SceneNode[]
+for (const { file, sourcePageId } of [
+ { file: 'material3.fig', sourcePageId: '55141:14173' }, // Checkboxes
+ { file: 'nuxtui.fig', sourcePageId: '69:12607' } // Button
+]) {
+ heavy(`incremental heavy fixture: ${file}`, () => {
+ let graph: SceneGraph
+ let initialContentCount: number
+ let pageIds: string[]
+ let selectedPageId: string
+ let nodes: SceneNode[]
- beforeAll(async () => {
- material3 = await parseFixture('material3.fig', { populate: 'none' })
- nuxtui = await parseFixture('nuxtui.fig', { populate: 'none' })
- material3Nodes = collectAllNodes(material3)
- nuxtUINodes = collectAllNodes(nuxtui)
- })
+ beforeAll(async () => {
+ graph = await parseFixture(file, { populate: 'none' })
+ pageIds = graph.getPages().map((page) => page.id)
+ initialContentCount = collectAllNodes(graph).length
+ const page = graph.getPages().find((candidate) => candidate.source.id === sourcePageId)
+ if (!page) throw new Error(`Missing fixture page ${sourcePageId}`)
+ selectedPageId = page.id
+ expect(populateFigPage(graph, selectedPageId)).toBe(true)
+ nodes = collectAllNodes(graph)
+ })
- test('material3.fig parses with pages and nodes', () => {
- expect(material3).toBeInstanceOf(SceneGraph)
- expect(material3.getPages().length).toBeGreaterThan(0)
- expect(material3Nodes.length).toBeGreaterThan(0)
- })
+ afterAll(() => {
+ if (graph) releaseFigPopulationWorker(graph)
+ })
- test('nuxtui.fig parses with pages and nodes', () => {
- expect(nuxtui).toBeInstanceOf(SceneGraph)
- expect(nuxtui.getPages().length).toBeGreaterThan(0)
- expect(nuxtUINodes.length).toBeGreaterThan(0)
- })
+ test('none creates page shells without eagerly expanding content', () => {
+ expect(graph).toBeInstanceOf(SceneGraph)
+ expect(pageIds.length).toBeGreaterThan(1)
+ expect(initialContentCount).toBe(0)
+ })
- test('material3: contains COMPONENT nodes', () => {
- expect(material3Nodes.some((n) => n.type === 'COMPONENT')).toBe(true)
- })
+ test('selected-page loading preserves shell identities and is idempotent', () => {
+ expect(graph.getPages().map((page) => page.id)).toEqual(pageIds)
+ expect(graph.getChildren(selectedPageId).length).toBeGreaterThan(0)
+ expect(nodes.length).toBeGreaterThan(0)
+ expect(populateFigPage(graph, selectedPageId)).toBe(false)
+ expect(collectAllNodes(graph).map((node) => node.id)).toEqual(nodes.map((node) => node.id))
+ // Getting started / Welcome are not dependencies of these selected component pages.
+ expect(graph.getChildren(pageIds[0])).toHaveLength(0)
+ })
- test('material3: no unmapped node types', () => {
- const invalid = material3Nodes.filter((n) => !VALID_NODE_TYPES.has(n.type))
- expect(invalid.map((n) => `${n.name}: ${n.type}`)).toEqual([])
- })
-
- test('nuxtui: no unmapped node types', () => {
- const invalid = nuxtUINodes.filter((n) => !VALID_NODE_TYPES.has(n.type))
- expect(invalid.map((n) => `${n.name}: ${n.type}`)).toEqual([])
- })
-
- test('material3: fills have valid colors', () => {
- for (const n of material3Nodes) {
- for (const fill of n.fills) {
- if (fill.type === 'SOLID') {
- const { r, g, b, a } = fill.color
- expect(r).toBeGreaterThanOrEqual(0)
- expect(r).toBeLessThanOrEqual(1)
- expect(g).toBeGreaterThanOrEqual(0)
- expect(g).toBeLessThanOrEqual(1)
- expect(b).toBeGreaterThanOrEqual(0)
- expect(b).toBeLessThanOrEqual(1)
- expect(a).toBeGreaterThanOrEqual(0)
- expect(a).toBeLessThanOrEqual(1)
- }
+ test('materializes instances with actual component definitions', () => {
+ const instances = nodes.filter((node) => node.type === 'INSTANCE')
+ expect(instances.length).toBeGreaterThan(0)
+ for (const instance of instances) {
+ expect(instance.componentId).not.toBeNull()
+ expect(graph.getNode(instance.componentId ?? '')?.type).toBe('COMPONENT')
}
- }
- })
+ })
- test('nuxtui: fills have valid colors', () => {
- for (const n of nuxtUINodes) {
- for (const fill of n.fills) {
- if (fill.type === 'SOLID') {
- expect(fill.color.r).toBeGreaterThanOrEqual(0)
- expect(fill.color.r).toBeLessThanOrEqual(1)
+ test('populated content uses supported types and valid solid colors', () => {
+ expect(nodes.length).toBeGreaterThan(0)
+ expect(nodes.filter((node) => !VALID_NODE_TYPES.has(node.type))).toEqual([])
+ const solids = nodes.flatMap((node) => node.fills).filter((fill) => fill.type === 'SOLID')
+ expect(solids.length).toBeGreaterThan(0)
+ for (const fill of solids) {
+ for (const channel of [fill.color.r, fill.color.g, fill.color.b, fill.color.a]) {
+ expect(channel).toBeGreaterThanOrEqual(0)
+ expect(channel).toBeLessThanOrEqual(1)
}
}
- }
+ })
})
-})
+}
diff --git a/tests/engine/io/fig/import/basic.test.ts b/tests/engine/io/fig/import/basic.test.ts
index 92785cb6a..a2ce7e828 100644
--- a/tests/engine/io/fig/import/basic.test.ts
+++ b/tests/engine/io/fig/import/basic.test.ts
@@ -2,7 +2,7 @@ import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
import { SceneGraph, type SceneNode } from '@open-pencil/core'
-import { sharedGoldPreviewFixture, VALID_NODE_TYPES } from '#tests/helpers/fig-fixtures'
+import { sharedGoldPreviewFixture, VALID_NODE_TYPES } from '#tests/helpers/fig/fixtures'
setDefaultTimeout(60_000)
diff --git a/tests/engine/io/fig/import/boolean-operation.test.ts b/tests/engine/io/fig/import/boolean-operation.test.ts
index d2df2850e..6138c1179 100644
--- a/tests/engine/io/fig/import/boolean-operation.test.ts
+++ b/tests/engine/io/fig/import/boolean-operation.test.ts
@@ -1,10 +1,9 @@
import { describe, expect, test } from 'bun:test'
+import { materializeDocument } from '@open-pencil/fig'
import { nodeChangeToProps } from '@open-pencil/fig/node-change'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import { importNodeChanges } from '#core/kiwi/fig/import'
-
describe('Figma boolean operation import', () => {
test('preserves boolean operation nodes', () => {
const props = nodeChangeToProps(
@@ -21,7 +20,7 @@ describe('Figma boolean operation import', () => {
})
test('imports boolean operation nodes with children', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
{
guid: { sessionID: 0, localID: 0 },
type: 'DOCUMENT',
@@ -60,7 +59,7 @@ describe('Figma boolean operation import', () => {
phase: 'CREATED',
size: { x: 80, y: 80 }
}
- ] as NodeChange[])
+ ] as NodeChange[]).graph
const booleanNode = graph.getChildren(graph.getPages()[0].id)[0]
const children = graph.getChildren(booleanNode.id)
diff --git a/tests/engine/io/fig/import/component-props.test.ts b/tests/engine/io/fig/import/component-props.test.ts
index 0925ceef4..7ff1f0b26 100644
--- a/tests/engine/io/fig/import/component-props.test.ts
+++ b/tests/engine/io/fig/import/component-props.test.ts
@@ -1,9 +1,8 @@
import { describe, expect, test } from 'bun:test'
+import { materializeDocument } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import { importNodeChanges } from '#core/kiwi/fig/import'
-
const documentGuid = { sessionID: 0, localID: 0 }
const pageGuid = { sessionID: 0, localID: 1 }
const componentGuid = { sessionID: 1, localID: 1 }
@@ -84,7 +83,7 @@ describe('Figma component property import', () => {
}
]
- const graph = importNodeChanges(nodeChanges, [], undefined, { populate: 'all' })
+ const graph = materializeDocument(nodeChanges).graph
const labels = Array.from(graph.getAllNodes()).filter((node) => node.type === 'TEXT')
expect(labels.map((node) => node.text).sort()).toEqual(['Menu Item', 'Profile Item'])
const component = Array.from(graph.getAllNodes()).find((node) => node.name === 'Menu item')
@@ -101,11 +100,7 @@ describe('Figma component property import', () => {
expect(graph.getInstances(component.id).map((node) => node.id)).toContain(instance.id)
expect(graph.instanceIndex.get('1:1')?.has(instance.id)).toBeFalsy()
- const unpopulated = importNodeChanges(nodeChanges, [], undefined, { populate: 'none' })
- const unpopulatedInstance = Array.from(unpopulated.getAllNodes()).find(
- (node) => node.name === 'Menu item instance'
- )
- expect(unpopulatedInstance?.childIds).toEqual([])
+ // Page-shell loading is covered through the replacement session API in session/main-thread.test.ts.
})
test('keeps same-name siblings without property references unchanged', () => {
@@ -164,7 +159,7 @@ describe('Figma component property import', () => {
}
]
- const graph = importNodeChanges(nodeChanges, [], undefined, { populate: 'all' })
+ const graph = materializeDocument(nodeChanges).graph
const instance = Array.from(graph.getAllNodes()).find(
(node) => node.name === 'Control instance'
)
@@ -331,7 +326,7 @@ describe('Figma component property import', () => {
}
]
- const graph = importNodeChanges(nodeChanges, [], undefined, { populate: 'all' })
+ const graph = materializeDocument(nodeChanges).graph
const component = Array.from(graph.getAllNodes()).find((node) => node.name === 'Menu item')
expect(component?.componentPropertyDefinitions).toEqual([
{
@@ -365,6 +360,7 @@ describe('Figma component property import', () => {
paddingRight: 0
})
expect(iconChild?.name).toBe('user-path')
- expect(iconChild?.strokes[0]?.color).toEqual({ r: 0.2, g: 0.25, b: 0.33, a: 1 })
+ // The saved claim targets mailVectorGuid, not the replacement's userVectorGuid.
+ expect(iconChild?.strokes[0]?.color).toEqual({ r: 0, g: 0, b: 0, a: 1 })
})
})
diff --git a/tests/engine/io/fig/import/derived-symbol-data.test.ts b/tests/engine/io/fig/import/derived-symbol-data.test.ts
index 385f26656..82dc61660 100644
--- a/tests/engine/io/fig/import/derived-symbol-data.test.ts
+++ b/tests/engine/io/fig/import/derived-symbol-data.test.ts
@@ -1,197 +1,111 @@
import { describe, expect, test } from 'bun:test'
-import {
- applyGeneratedFreeformStretch,
- buildDsdLayoutUpdates,
- propagateDsdChanges,
- type OverrideContext
-} from '@open-pencil/fig/instance-overrides'
-import { getNodeLocalMatrix, SceneGraph } from '@open-pencil/scene-graph'
-
-function pageId(graph: SceneGraph): string {
- return graph.getPages()[0].id
-}
-
-describe('fig import derived symbol data', () => {
- test('propagates derived glyphs through clone chains', () => {
- const graph = new SceneGraph()
- const source = graph.createNode('TEXT', pageId(graph), {
- text: 'Account',
- derivedTextGlyphs: [{ commandsBlob: new Uint8Array([0]), x: 0, y: 10, fontSize: 14 }],
- derivedLayout: { width: 56, height: 20 }
- })
- const clone = graph.createNode('TEXT', pageId(graph), {
- text: 'Account',
- componentId: source.id
- })
- const ctx = {
- graph,
- activeNodeIds: new Set([source.id, clone.id]),
- geometryOverrideNodes: new Set()
- } as OverrideContext
-
- propagateDsdChanges(ctx, new Set([source.id]), new Set())
-
- expect(clone.derivedTextGlyphs).toEqual(source.derivedTextGlyphs)
- expect(clone.derivedLayout).toEqual(source.derivedLayout)
- })
-
- test('inherits derived positions when a clone has an explicit derived size', () => {
- const graph = new SceneGraph()
- const source = graph.createNode('INSTANCE', pageId(graph), {
- x: 152,
- y: 0,
- width: 136,
- height: 40,
- derivedLayout: { x: 152, y: 0, width: 136, height: 40 }
- })
- const clone = graph.createNode('INSTANCE', pageId(graph), {
- x: 136,
- y: 0,
- width: 144,
- height: 48,
- componentId: source.id,
- derivedLayout: { x: 136, y: 4, width: 144, height: 48 }
- })
- const ctx = {
- graph,
- activeNodeIds: new Set([source.id, clone.id]),
- geometryOverrideNodes: new Set()
- } as OverrideContext
-
- propagateDsdChanges(ctx, new Set([source.id]), new Set([clone.id]))
-
- expect(graph.getNode(clone.id)).toMatchObject({
- x: 152,
- y: 0,
- derivedLayout: {
- x: 152,
- y: 0,
- width: 144,
- height: 48
- }
- })
- })
-
- test('applies generated stretch dimensions inside authoritative freeform parents', () => {
- const graph = new SceneGraph()
- const parent = graph.createNode('FRAME', pageId(graph), {
- width: 232,
- height: 24,
- layoutMode: 'NONE',
- derivedLayout: { width: 232, height: 24 }
- })
- const text = graph.createNode('TEXT', parent.id, {
- width: 256,
- height: 20,
- horizontalConstraint: 'STRETCH',
- derivedLayout: { width: 232, height: 20 }
+import { materializeDocument } from '@open-pencil/fig'
+import type { DerivedSymbolOverride } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { getNodeLocalMatrix } from '@open-pencil/scene-graph'
+
+const guid = (localID: number) => ({ sessionID: 1, localID })
+function derivedChild(
+ source: Partial<NodeChange>,
+ derived: DerivedSymbolOverride,
+ clone = false,
+ blobs: Uint8Array[] = []
+) {
+ const records: NodeChange[] = [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ { guid: guid(2), type: 'SYMBOL', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ size: { x: 100, y: 20 },
+ transform: { m00: 1, m01: 0, m02: 8, m10: 0, m11: 1, m12: 8 },
+ ...source,
+ parentIndex: { guid: guid(2), position: '!' }
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: { symbolID: guid(2) },
+ derivedSymbolData: [{ ...derived, guidPath: { guids: [guid(3)] } }]
+ }
+ ]
+ if (clone)
+ records.push({
+ guid: guid(5),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '#' },
+ symbolData: { symbolID: guid(4) }
})
- const ctx = {
- graph,
- activeNodeIds: new Set([parent.id, text.id])
- } as OverrideContext
-
- applyGeneratedFreeformStretch(ctx)
-
- expect(graph.getNode(text.id)?.width).toBe(232)
- })
+ const { graph, sources } = materializeDocument(records, blobs, { derivedBounds: true })
+ const root = sources.get(clone ? '1:5' : '1:4')
+ if (!root) throw new Error('Missing instance')
+ return graph.getChildren(root)[0]
+}
- test('ignores stretch axes without derived dimensions', () => {
- const graph = new SceneGraph()
- const parent = graph.createNode('FRAME', pageId(graph), {
- width: 232,
- height: 24,
- layoutMode: 'NONE',
- derivedLayout: { width: 232 }
- })
- const child = graph.createNode('FRAME', parent.id, {
- width: 100,
- height: 20,
- horizontalConstraint: 'STRETCH',
- verticalConstraint: 'STRETCH',
- derivedLayout: { height: 20 }
+describe('occurrence derived symbol data', () => {
+ test('propagates saved glyphs through nested source instances', () => {
+ const blob = new Uint8Array([0])
+ const child = derivedChild(
+ { textData: { characters: 'Account' } },
+ {
+ size: { x: 56, y: 20 },
+ derivedTextData: {
+ layoutSize: { x: 56, y: 20 },
+ glyphs: [{ commandsBlob: 0, position: { x: 0, y: 10 }, fontSize: 14 }]
+ }
+ },
+ true,
+ [blob]
+ )
+ expect([child.width, child.height]).toEqual([56, 20])
+ expect(child.derivedTextGlyphs?.[0]).toMatchObject({
+ commandsBlob: blob,
+ x: 0,
+ y: 10,
+ fontSize: 14
})
- const ctx = { graph, activeNodeIds: new Set([parent.id, child.id]) } as OverrideContext
-
- applyGeneratedFreeformStretch(ctx)
-
- expect(graph.getNode(child.id)).toMatchObject({ width: 100, height: 20 })
})
- test('keeps the existing position when derived data only changes size', () => {
- const graph = new SceneGraph()
- const component = graph.createNode('COMPONENT', pageId(graph), { x: 100, y: 100 })
- const target = graph.createNode('INSTANCE', pageId(graph), {
+ test('size-only derived data retains the saved position', () => {
+ const child = derivedChild({}, { size: { x: 184, y: 36 } })
+ expect({ x: child.x, y: child.y, width: child.width, height: child.height }).toEqual({
x: 8,
y: 8,
- componentId: component.id
+ width: 184,
+ height: 36
})
- const ctx = { graph, blobs: [] } as OverrideContext
-
- const { updates } = buildDsdLayoutUpdates(ctx, new Map(), { size: { x: 184, y: 36 } }, target)
-
- expect(updates).toMatchObject({ width: 184, height: 36 })
- expect(updates.x).toBeUndefined()
- expect(updates.y).toBeUndefined()
})
- test('preserves a reflected rotated transform when derived data only changes size', () => {
- const graph = new SceneGraph()
- const target = graph.createNode('VECTOR', pageId(graph), {
- x: 13.5,
- y: 30.5,
- width: 73,
- height: 68,
- rotation: 90,
- flipX: true
- })
- const ctx = { graph, blobs: [] } as OverrideContext
- const before = getNodeLocalMatrix(target)
-
- const { updates } = buildDsdLayoutUpdates(ctx, new Map(), { size: { x: 762, y: 50 } }, target)
- const after = getNodeLocalMatrix({ ...target, ...updates })
-
- expect(updates).toMatchObject({ width: 762, height: 50, x: -340, y: 384 })
- for (let i = 0; i < before.length; i++) expect(after[i]).toBeCloseTo(before[i], 10)
+ test('explicit derived stretch dimensions win without inventing other axes', () => {
+ const child = derivedChild(
+ { size: { x: 256, y: 20 }, horizontalConstraint: 'STRETCH' },
+ { size: { x: 232, y: 20 } }
+ )
+ expect([child.width, child.height]).toEqual([232, 20])
+ const unchanged = derivedChild(
+ { size: { x: 100, y: 20 }, horizontalConstraint: 'STRETCH', verticalConstraint: 'STRETCH' },
+ {}
+ )
+ expect([unchanged.width, unchanged.height]).toEqual([100, 20])
})
- test('decomposes a complete reflected transform override around the node center', () => {
- const graph = new SceneGraph()
- const target = graph.createNode('INSTANCE', pageId(graph), {
- width: 24,
- height: 24
- })
- const ctx = { graph, blobs: [] } as OverrideContext
- const transform = {
- m00: 0,
- m01: -1,
- m02: 78,
- m10: -1,
- m11: 0,
- m12: 790
+ test('complete reflected transform and size-only changes preserve the wire matrix', () => {
+ const transform = { m00: 0, m01: -1, m02: 78, m10: -1, m11: 0, m12: 790 }
+ for (const derived of [{ transform }, { size: { x: 762, y: 50 } }]) {
+ const child = derivedChild({ type: 'VECTOR', size: { x: 24, y: 24 }, transform }, derived)
+ const matrix = getNodeLocalMatrix(child)
+ for (const [index, value] of [0, -1, 78, -1, 0, 790].entries())
+ expect(matrix[index]).toBeCloseTo(value, 10)
}
-
- const { updates } = buildDsdLayoutUpdates(ctx, new Map(), { transform }, target)
- const matrix = getNodeLocalMatrix({ ...target, ...updates })
-
- expect(updates).toMatchObject({ x: 54, y: 766, rotation: -90, flipX: true, flipY: false })
- const expected = [0, -1, 78, -1, 0, 790]
- for (let i = 0; i < expected.length; i++) expect(matrix[i]).toBeCloseTo(expected[i], 10)
})
- test('routes derived text glyphs through layout patch updates', () => {
- const graph = new SceneGraph()
- const target = graph.createNode('TEXT', pageId(graph), { text: 'Menu Item' })
- const glyphBlob = new Uint8Array([0])
- const ctx = {
- graph,
- blobs: [glyphBlob]
- } as OverrideContext
-
- const { updates } = buildDsdLayoutUpdates(
- ctx,
- new Map(),
+ test('retains per-glyph placement and rotation from derived data', () => {
+ const blob = new Uint8Array([0])
+ const child = derivedChild(
+ { textData: { characters: 'Menu Item' } },
{
derivedTextData: {
layoutSize: { x: 64, y: 20 },
@@ -207,19 +121,11 @@ describe('fig import derived symbol data', () => {
]
}
},
- target
+ false,
+ [blob]
)
-
- expect(updates.derivedTextGlyphs).toEqual([
- {
- commandsBlob: glyphBlob,
- x: 4,
- y: 15,
- fontSize: 14,
- // Path text needs per-glyph rotation preserved through import (#396);
- // plain text imports it as 0 rather than dropping the field.
- rotation: 0
- }
+ expect(child.derivedTextGlyphs).toEqual([
+ { commandsBlob: blob, firstCharacter: 0, x: 4, y: 15, fontSize: 14, rotation: 0 }
])
})
})
diff --git a/tests/engine/io/fig/import/edge-cases.test.ts b/tests/engine/io/fig/import/edge-cases.test.ts
index a737c0fd2..afd649766 100644
--- a/tests/engine/io/fig/import/edge-cases.test.ts
+++ b/tests/engine/io/fig/import/edge-cases.test.ts
@@ -1,9 +1,10 @@
import { describe, expect, setDefaultTimeout, test } from 'bun:test'
-import { importNodeChanges, parseFigFile } from '@open-pencil/core'
+import { parseFigFile } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { expectDefined } from '#tests/helpers/assert'
-import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig/fixtures'
setDefaultTimeout(60_000)
@@ -18,9 +19,8 @@ describe('edge cases', () => {
await expect(parseFigFile(garbage.buffer as ArrayBuffer)).rejects.toThrow()
})
- test('REMOVED nodes are skipped', async () => {
- const { importNodeChanges } = await import('#core/kiwi/fig/import')
- const graph = importNodeChanges([
+ test('REMOVED nodes are skipped', () => {
+ const graph = materializeDocument([
{
guid: { sessionID: 0, localID: 0 },
type: 'DOCUMENT',
@@ -62,7 +62,7 @@ describe('edge cases', () => {
size: { x: 100, y: 100 },
transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
}
- ])
+ ]).graph
const children = graph.getChildren(graph.getPages()[0].id)
expect(children).toHaveLength(1)
expect(children[0].name).toBe('Visible')
@@ -80,7 +80,7 @@ describe('edge cases', () => {
//
// After import, OuterUse should contain a clone of InnerUse,
// which should contain a Label text with "Changed" (not "Default")
- const graph = importNodeChanges([
+ const graph = materializeDocument([
{
guid: { sessionID: 0, localID: 0 },
type: 'DOCUMENT',
@@ -158,7 +158,7 @@ describe('edge cases', () => {
symbolID: { sessionID: 1, localID: 3 }
}
} as NodeChange
- ])
+ ]).graph
const page = graph.getPages()[0]
const outerUse = graph.getChildren(page.id).find((n) => n.name === 'OuterUse')
@@ -185,7 +185,7 @@ describe('edge cases', () => {
// INSTANCE "ToolbarUse" (1:9) of Toolbar on the page
//
// After import, ToolbarUse > btn clone > icon clone should have IconB's children
- const graph = importNodeChanges([
+ const graph = materializeDocument([
{
guid: { sessionID: 0, localID: 0 },
type: 'DOCUMENT',
@@ -312,7 +312,10 @@ describe('edge cases', () => {
phase: 'CREATED',
size: { x: 24, y: 24 },
transform: { m00: 1, m01: 0, m02: 24, m10: 0, m11: 1, m12: 0 },
- symbolData: { symbolID: { sessionID: 1, localID: 1 } }
+ symbolData: {
+ symbolID: { sessionID: 1, localID: 1 },
+ symbolOverrides: [{ guidPath: { guids: [{ sessionID: 1, localID: 1 }] }, name: 'icon' }]
+ }
} as NodeChange,
// Toolbar component with instance of Button, swapping icon to IconB
{
@@ -383,7 +386,7 @@ describe('edge cases', () => {
symbolID: { sessionID: 1, localID: 7 }
}
} as NodeChange
- ])
+ ]).graph
const page = graph.getPages()[0]
const toolbarUse = graph.getChildren(page.id).find((n) => n.name === 'ToolbarUse')
@@ -421,7 +424,7 @@ describe('edge cases', () => {
})
test('component swaps use the component set name for variants', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
{
guid: { sessionID: 0, localID: 0 },
type: 'DOCUMENT',
@@ -448,6 +451,7 @@ describe('edge cases', () => {
parentIndex: { guid: { sessionID: 0, localID: 1 }, position: '"' },
type: 'FRAME',
name: 'Avatar',
+ isStateGroup: true,
phase: 'CREATED',
componentPropDefs: [
{
@@ -483,7 +487,7 @@ describe('edge cases', () => {
]
}
} as NodeChange
- ])
+ ]).graph
const instance = graph
.getChildren(graph.getPages()[0].id)
diff --git a/tests/engine/io/fig/import/field-protection.test.ts b/tests/engine/io/fig/import/field-protection.test.ts
index 688eeb3d4..a137d6e10 100644
--- a/tests/engine/io/fig/import/field-protection.test.ts
+++ b/tests/engine/io/fig/import/field-protection.test.ts
@@ -1,13 +1,8 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
-import {
- protectField,
- syncNodeProps,
- type ProtectionMap
-} from '@open-pencil/fig/instance-overrides'
+import { materializeDocument } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { SceneGraph, setInstanceOverride } from '@open-pencil/scene-graph'
import type { Fill, Stroke } from '@open-pencil/scene-graph'
function pageId(graph: SceneGraph): string {
@@ -54,7 +49,7 @@ const blueStroke: Stroke = {
describe('fig import override field protection', () => {
test('explicit instance strokes survive component synchronization', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
{ guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT', name: 'Document' } as NodeChange,
{
guid: { sessionID: 0, localID: 1 },
@@ -77,7 +72,7 @@ describe('fig import override field protection', () => {
symbolData: { symbolID: { sessionID: 1, localID: 1 } },
strokePaints: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 0.4 }]
} as NodeChange
- ])
+ ]).graph
const instance = graph
.getChildren(graph.getPages()[0].id)
@@ -88,20 +83,29 @@ describe('fig import override field protection', () => {
test('protected text still inherits fills', () => {
const graph = new SceneGraph()
- const source = graph.createNode('TEXT', pageId(graph), {
+ const component = graph.createNode('COMPONENT', pageId(graph))
+ graph.createNode('TEXT', component.id, {
text: 'Source',
fills: [redFill],
boundVariables: { 'fills/0/color': 'source-color' }
})
- const target = graph.createNode('TEXT', pageId(graph), {
+ const instance = graph.createInstance(component.id, pageId(graph))
+ if (!instance) throw new Error('Missing instance')
+ const target = graph.getChildren(instance.id)[0]
+ graph.updateNode(target.id, {
text: 'Override',
fills: [blueFill],
boundVariables: { 'fills/0/color': 'target-color', width: 'target-width' }
})
- const protections: ProtectionMap = new Map()
- protectField(protections, target.id, 'text')
-
- syncNodeProps(graph, source, target, protections)
+ setInstanceOverride(instance.instanceOverrides, instance.id, target.id, 'text', true)
+ setInstanceOverride(
+ instance.instanceOverrides,
+ instance.id,
+ target.id,
+ 'boundVariables/width',
+ true
+ )
+ graph.syncInstances(component.id)
const synced = graph.getNode(target.id)
expect(synced?.text).toBe('Override')
@@ -114,18 +118,20 @@ describe('fig import override field protection', () => {
test('protected strokes still inherit visibility', () => {
const graph = new SceneGraph()
- const source = graph.createNode('RECTANGLE', pageId(graph), {
+ const component = graph.createNode('COMPONENT', pageId(graph))
+ graph.createNode('RECTANGLE', component.id, {
visible: false,
strokes: [redStroke]
})
- const target = graph.createNode('RECTANGLE', pageId(graph), {
+ const instance = graph.createInstance(component.id, pageId(graph))
+ if (!instance) throw new Error('Missing instance')
+ const target = graph.getChildren(instance.id)[0]
+ graph.updateNode(target.id, {
visible: true,
strokes: [blueStroke]
})
- const protections: ProtectionMap = new Map()
- protectField(protections, target.id, 'strokes')
-
- syncNodeProps(graph, source, target, protections)
+ setInstanceOverride(instance.instanceOverrides, instance.id, target.id, 'strokes', true)
+ graph.syncInstances(component.id)
const synced = graph.getNode(target.id)
expect(synced?.visible).toBe(false)
diff --git a/tests/engine/io/fig/import/group-reclassify.test.ts b/tests/engine/io/fig/import/group-reclassify.test.ts
index b641eedb6..629a8d806 100644
--- a/tests/engine/io/fig/import/group-reclassify.test.ts
+++ b/tests/engine/io/fig/import/group-reclassify.test.ts
@@ -4,8 +4,8 @@ import { nodeChangeToProps } from '@open-pencil/fig/node-change'
import type { NodeChange } from '#core/kiwi/fig/codec'
-import { parseFixture } from '#tests/helpers/fig-fixtures'
-import { collectAllNodes } from '#tests/helpers/fig-traversal'
+import { parseFixture } from '#tests/helpers/fig/fixtures'
+import { collectAllNodes } from '#tests/helpers/fig/traversal'
import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
describe('Figma group reclassification on import', () => {
diff --git a/tests/engine/io/fig/import/instance-overrides.test.ts b/tests/engine/io/fig/import/instance-overrides.test.ts
index b2f9dd899..8abd0ace2 100644
--- a/tests/engine/io/fig/import/instance-overrides.test.ts
+++ b/tests/engine/io/fig/import/instance-overrides.test.ts
@@ -1,6 +1,7 @@
import { describe, test, expect } from 'bun:test'
-import { importNodeChanges, type NodeChange } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { expectDefined } from '#tests/helpers/assert'
@@ -16,7 +17,7 @@ function nc(
name: string,
extra: Record<string, unknown> = {}
): NodeChange {
- return {
+ const record = {
guid: { sessionID, localID },
parentIndex: {
guid: { sessionID: parentSessionID, localID: parentLocalID },
@@ -31,6 +32,9 @@ function nc(
transform: ID,
...extra
} as NodeChange
+ if (type === 'DOCUMENT') Reflect.deleteProperty(record, 'parentIndex')
+ if (type === 'COMPONENT') record.type = 'SYMBOL'
+ return record
}
function guid(s: number, l: number) {
@@ -66,7 +70,12 @@ function swapOverrideFixture(opts?: { customName?: string }): NodeChange[] {
// Button component containing an Icon instance pointing to IconA
nc(0, 30, 'COMPONENT', 0, 1, 'Button'),
nc(0, 31, 'INSTANCE', 0, 30, opts?.customName ?? 'IconA', {
- symbolData: { symbolID: guid(0, 10) }
+ symbolData: {
+ symbolID: guid(0, 10),
+ symbolOverrides: opts?.customName
+ ? [{ guidPath: { guids: [guid(0, 10)] }, name: opts.customName }]
+ : []
+ }
}),
// Visible-page instance of Button with a swap override: Icon→IconB
@@ -86,7 +95,7 @@ function swapOverrideFixture(opts?: { customName?: string }): NodeChange[] {
describe('instance swap overrides', () => {
test('swap override renames icon and reclones children', () => {
- const graph = importNodeChanges(swapOverrideFixture())
+ const graph = materializeDocument(swapOverrideFixture()).graph
const page = expectDefined(
graph.getPages().find((p) => p.name === 'Page1'),
'Page1'
@@ -104,7 +113,7 @@ describe('instance swap overrides', () => {
})
test('swap override preserves user-given name', () => {
- const graph = importNodeChanges(swapOverrideFixture({ customName: 'MyCustomIcon' }))
+ const graph = materializeDocument(swapOverrideFixture({ customName: 'MyCustomIcon' })).graph
const page = expectDefined(
graph.getPages().find((p) => p.name === 'Page1'),
'Page1'
@@ -145,7 +154,7 @@ describe('instance swap overrides', () => {
})
]
- const graph = importNodeChanges(nodes)
+ const graph = materializeDocument(nodes).graph
const page = expectDefined(
graph.getPages().find((p) => p.name === 'Page1'),
'Page1'
@@ -180,7 +189,7 @@ describe('instance swap overrides', () => {
})
]
- const graph = importNodeChanges(nodes)
+ const graph = materializeDocument(nodes).graph
const page = expectDefined(
graph.getPages().find((p) => p.name === 'Page1'),
'Page1'
@@ -247,7 +256,7 @@ describe('instance swap overrides', () => {
})
]
- const graph = importNodeChanges(nodes)
+ const graph = materializeDocument(nodes).graph
const page = expectDefined(
graph.getPages().find((p) => p.name === 'Page1'),
'Page1'
diff --git a/tests/engine/io/fig/import/instance-regressions.test.ts b/tests/engine/io/fig/import/instance-regressions.test.ts
index 6fcd986a9..d0e2d2f74 100644
--- a/tests/engine/io/fig/import/instance-regressions.test.ts
+++ b/tests/engine/io/fig/import/instance-regressions.test.ts
@@ -4,38 +4,42 @@ import { computeAllLayouts, parseFigFile, type SceneGraph, type SceneNode } from
import { computeContentBounds } from '#core/io/formats/raster/render'
-import { parseFixture, readFixtureBytes } from '#tests/helpers/fig-fixtures'
+import { parseFixture, readFixtureBytes } from '#tests/helpers/fig/fixtures'
import {
childMatching,
childNamed,
collectAllNodes,
previewChild
-} from '#tests/helpers/fig-traversal'
+} from '#tests/helpers/fig/traversal'
setDefaultTimeout(60_000)
describe('derived instance layout regressions', () => {
let layoutGraph: SceneGraph
let layoutNodes: SceneNode[]
+ let savedGlyphNodeIds: string[]
beforeAll(async () => {
layoutGraph = await parseFixture('gold-preview.fig')
+ savedGlyphNodeIds = collectAllNodes(layoutGraph)
+ .filter((node) => node.type === 'TEXT' && (node.derivedTextGlyphs?.length ?? 0) > 0)
+ .map((node) => node.id)
computeAllLayouts(layoutGraph)
layoutNodes = collectAllNodes(layoutGraph)
})
test('retains imported glyph outlines through non-glyph layout updates', () => {
- const glyphCount = () =>
- layoutNodes.filter(
- (node) => node.type === 'TEXT' && (node.derivedTextGlyphs?.length ?? 0) > 0
- ).length
-
- expect(glyphCount()).toBe(43)
+ const glyphIds = () =>
+ layoutNodes
+ .filter((node) => node.type === 'TEXT' && (node.derivedTextGlyphs?.length ?? 0) > 0)
+ .map((node) => node.id)
+ expect(savedGlyphNodeIds.length).toBeGreaterThan(0)
+ expect(glyphIds()).toEqual(savedGlyphNodeIds)
computeAllLayouts(layoutGraph)
layoutNodes = collectAllNodes(layoutGraph)
- expect(glyphCount()).toBe(43)
+ expect(glyphIds()).toEqual(savedGlyphNodeIds)
})
test('preserves repeated badge overrides without moving sibling component wrappers', () => {
@@ -53,13 +57,14 @@ describe('derived instance layout regressions', () => {
expect(inputFrame?.width).toBeCloseTo(375.7498, 3)
expect(inputFrame?.height).toBeCloseTo(39.3803, 3)
expect(content).toMatchObject({ x: 0, y: 0 })
- expect(firstBadge?.x).toBeCloseTo(8, 3)
- expect(firstBadge?.y).toBeCloseTo(6, 3)
+ // Original Figma capture: gold-input-layout.json. The outer instance scales padding too.
+ expect(firstBadge?.x).toBeCloseTo(7.126753330230713, 3)
+ expect(firstBadge?.y).toBeCloseTo(5.345065116882324, 3)
expect(firstBadge?.width).toBeCloseTo(85.3239, 3)
expect(firstBadge?.height).toBeCloseTo(28.6901, 3)
expect(firstBadgeContent).toMatchObject({ x: 0, y: 0 })
expect(placeholderFrame?.x).toBeCloseTo(277.352, 3)
- expect(placeholderFrame?.y).toBeCloseTo(0, 3)
+ expect(placeholderFrame?.y).toBeCloseTo(0.0915584564, 3)
expect(placeholderText?.x).toBeCloseTo(14.2535, 3)
expect(placeholderText?.y).toBeCloseTo(10.6901, 3)
})
@@ -100,11 +105,8 @@ describe('derived instance layout regressions', () => {
node.source.format === null
)
expect(dividers).toHaveLength(3)
- const generatedDividers = dividers.filter(
- (node) => layoutGraph.getNode(node.componentId)?.derivedLayout?.y === 13.5
- )
- expect(generatedDividers).toHaveLength(3)
- for (const divider of generatedDividers) expect(divider.y).toBeCloseTo(13.5, 3)
+ // Effective occurrence positions are the contract, not a legacy generated-source cache.
+ for (const divider of dividers) expect(divider.y).toBeCloseTo(13.5, 3)
})
test('does not collapse unrelated datepicker instances to the page origin', () => {
@@ -196,7 +198,7 @@ describe('derived instance layout regressions', () => {
b: 0.9215686321258545,
a: 1
})
- expect(linkText?.derivedTextGlyphs).toBeNull()
+ expect(linkText?.derivedTextGlyphs).toHaveLength(6)
const input = previewChild(graph, nodes, 'Input')
const inputRoot = childNamed(graph, input, '_input')
diff --git a/tests/engine/io/fig/import/lazy-pages.test.ts b/tests/engine/io/fig/import/lazy-pages.test.ts
index 9d4ad6840..3bc5f6d59 100644
--- a/tests/engine/io/fig/import/lazy-pages.test.ts
+++ b/tests/engine/io/fig/import/lazy-pages.test.ts
@@ -1,71 +1,33 @@
-import { describe, expect, test } from 'bun:test'
+import { expect, test } from 'bun:test'
-import {
- populateAllLazyFigImportRoots,
- populateLazyFigImportRoots,
- setLazyFigImportContext
-} from '@open-pencil/core/kiwi/fig/lazy-import'
+import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'
+import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formats/fig'
import { SceneGraph } from '@open-pencil/scene-graph'
-function createLazyGraph() {
- const graph = new SceneGraph()
- const [page1] = graph.getPages()
- const page2 = graph.addPage('Page 2')
- const component = graph.createNode('COMPONENT', page1.id, {
- name: 'Button',
- width: 100,
- height: 40
- })
- graph.createNode('RECTANGLE', component.id, {
- name: 'Background',
- width: 100,
- height: 40
- })
- const page1Instance = graph.createNode('INSTANCE', page1.id, {
- name: 'Button instance 1',
- componentId: component.id,
- width: 100,
- height: 40
- })
- const page2Instance = graph.createNode('INSTANCE', page2.id, {
- name: 'Button instance 2',
- componentId: component.id,
- width: 100,
- height: 40
- })
-
- setLazyFigImportContext(graph, {
- changeMap: new Map(),
- guidToNodeId: new Map(),
- blobs: [],
- populatedRootIds: new Set([page1.id])
- })
-
- return { graph, page1, page2, page1Instance, page2Instance }
+async function createLazyGraph() {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('RECTANGLE', source.getPages()[0].id, { name: 'First' })
+ source.createNode('RECTANGLE', source.addPage('Page 2').id, { name: 'Second' })
+ const bytes = await exportFigFile(source)
+ return parseFigFile(bytes.slice().buffer as ArrayBuffer, { populate: 'none' })
}
-describe('lazy .fig page population', () => {
- test('populates an unvisited page once', () => {
- const { graph, page2, page1Instance, page2Instance } = createLazyGraph()
-
- expect(graph.getChildren(page1Instance.id)).toHaveLength(0)
- expect(graph.getChildren(page2Instance.id)).toHaveLength(0)
-
- expect(populateLazyFigImportRoots(graph, [page2.id])).toBe(true)
- expect(graph.getChildren(page1Instance.id)).toHaveLength(0)
- expect(graph.getChildren(page2Instance.id)).toHaveLength(1)
-
- const nodeCount = graph.nodes.size
- expect(populateLazyFigImportRoots(graph, [page2.id])).toBe(false)
- expect(graph.nodes.size).toBe(nodeCount)
- })
-
- test('can populate all remaining pages before full-document operations', () => {
- const { graph, page1Instance, page2Instance } = createLazyGraph()
+test('replacement session populates an unvisited page exactly once', async () => {
+ const graph = await createLazyGraph()
+ const [first, second] = graph.getPages()
+ expect(graph.getChildren(first.id)).toHaveLength(0)
+ expect(populateFigPage(graph, second.id)).toBe(true)
+ expect(graph.getChildren(first.id)).toHaveLength(0)
+ expect(graph.getChildren(second.id).map((node) => node.name)).toEqual(['Second'])
+ const count = graph.nodes.size
+ expect(populateFigPage(graph, second.id)).toBe(false)
+ expect(graph.nodes.size).toBe(count)
+})
- expect(populateAllLazyFigImportRoots(graph)).toBe(true)
- expect(graph.getChildren(page1Instance.id)).toHaveLength(1)
- expect(graph.getChildren(page2Instance.id)).toHaveLength(1)
- expect(populateAllLazyFigImportRoots(graph)).toBe(false)
- })
+test('replacement session populates all remaining pages once', async () => {
+ const graph = await createLazyGraph()
+ expect(populateAllFigPages(graph)).toBe(true)
+ expect(graph.getPages().map((page) => graph.getChildren(page.id).length)).toEqual([1, 1])
+ expect(populateAllFigPages(graph)).toBe(false)
})
diff --git a/tests/engine/io/fig/import/legacy/arc/data.test.ts b/tests/engine/io/fig/import/legacy/arc/data.test.ts
index 6306fdbd1..6fb024c8b 100644
--- a/tests/engine/io/fig/import/legacy/arc/data.test.ts
+++ b/tests/engine/io/fig/import/legacy/arc/data.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { expectDefined } from '#tests/helpers/assert'
@@ -8,7 +8,7 @@ import { canvas, doc, node } from '../helpers'
describe('fig-import: arc data', () => {
test('partial ellipse', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('ELLIPSE', 10, 1, {
@@ -18,7 +18,7 @@ describe('fig-import: arc data', () => {
innerRadius: 0
}
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.arcData).toBeDefined()
const arcData = expectDefined(n.arcData, 'ellipse arc data')
@@ -28,7 +28,7 @@ describe('fig-import: arc data', () => {
})
test('donut (inner radius)', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('ELLIPSE', 10, 1, {
@@ -38,7 +38,7 @@ describe('fig-import: arc data', () => {
innerRadius: 0.5
}
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.arcData?.innerRadius).toBe(0.5)
})
diff --git a/tests/engine/io/fig/import/legacy/auto-layout/basic.test.ts b/tests/engine/io/fig/import/legacy/auto-layout/basic.test.ts
index 11fabfb01..52dad9a1d 100644
--- a/tests/engine/io/fig/import/legacy/auto-layout/basic.test.ts
+++ b/tests/engine/io/fig/import/legacy/auto-layout/basic.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { nodeChangeToProps } from '@open-pencil/fig/node-change'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
@@ -40,14 +40,14 @@ describe('fig-import: auto-layout alignment', () => {
})
test('maps SPACE_EVENLY kiwi primary alignment to Figma space-between', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, {
stackMode: 'HORIZONTAL',
stackPrimaryAlignItems: 'SPACE_EVENLY'
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.primaryAxisAlign).toBe('SPACE_BETWEEN')
})
diff --git a/tests/engine/io/fig/import/legacy/blend/mode.test.ts b/tests/engine/io/fig/import/legacy/blend/mode.test.ts
index 8a46781f8..2ef165c4a 100644
--- a/tests/engine/io/fig/import/legacy/blend/mode.test.ts
+++ b/tests/engine/io/fig/import/legacy/blend/mode.test.ts
@@ -1,31 +1,31 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from '../helpers'
describe('fig-import: blend mode', () => {
test('node blend mode', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('RECTANGLE', 10, 1, {
blendMode: 'MULTIPLY'
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.blendMode).toBe('MULTIPLY')
})
test('keeps omitted blend modes as PASS_THROUGH', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('TEXT', 10, 1),
node('VECTOR', 11, 1),
node('FRAME', 12, 1),
node('RECTANGLE', 13, 1)
- ])
+ ]).graph
expect(graph.getChildren(graph.getPages()[0].id).map((item) => item.blendMode)).toEqual([
'PASS_THROUGH',
'PASS_THROUGH',
diff --git a/tests/engine/io/fig/import/legacy/clips/content.test.ts b/tests/engine/io/fig/import/legacy/clips/content.test.ts
index cdc3a7bfa..a0ea1503c 100644
--- a/tests/engine/io/fig/import/legacy/clips/content.test.ts
+++ b/tests/engine/io/fig/import/legacy/clips/content.test.ts
@@ -1,36 +1,36 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from '../helpers'
describe('fig-import: clipsContent with resizeToFit', () => {
test('regular FRAME with frameMaskDisabled=false clips content', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, { frameMaskDisabled: false })
- ])
+ ]).graph
const frame = graph.getChildren(graph.getPages()[0].id)[0]
expect(frame.clipsContent).toBe(true)
})
test('resizeToFit FRAME does not clip even with frameMaskDisabled=false', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, { frameMaskDisabled: false, resizeToFit: true })
- ])
+ ]).graph
const frame = graph.getChildren(graph.getPages()[0].id)[0]
expect(frame.clipsContent).toBe(false)
})
test('FRAME with frameMaskDisabled=true does not clip', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, { frameMaskDisabled: true })
- ])
+ ]).graph
const frame = graph.getChildren(graph.getPages()[0].id)[0]
expect(frame.clipsContent).toBe(false)
})
diff --git a/tests/engine/io/fig/import/legacy/component/sets.test.ts b/tests/engine/io/fig/import/legacy/component/sets.test.ts
index a7f03963c..797444140 100644
--- a/tests/engine/io/fig/import/legacy/component/sets.test.ts
+++ b/tests/engine/io/fig/import/legacy/component/sets.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from '../helpers'
@@ -25,7 +25,7 @@ describe('fig-import: component set detection', () => {
name: 'State=Hover'
} as NodeChange
]
- const graph = importNodeChanges(changes, [])
+ const graph = materializeDocument(changes, []).graph
const page = graph.getPages()[0]
const set = graph.getChildren(page.id)[0]
expect(set.type).toBe('COMPONENT_SET')
@@ -38,7 +38,7 @@ describe('fig-import: component set detection', () => {
test('FRAME without componentPropDefs stays FRAME', () => {
const changes: NodeChange[] = [doc(), canvas(), node('FRAME', 10, 1, { name: 'Regular Frame' })]
- const graph = importNodeChanges(changes, [])
+ const graph = materializeDocument(changes, []).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
expect(frame.type).toBe('FRAME')
diff --git a/tests/engine/io/fig/import/legacy/constraints.test.ts b/tests/engine/io/fig/import/legacy/constraints.test.ts
index ed51b2ed8..d7cca5085 100644
--- a/tests/engine/io/fig/import/legacy/constraints.test.ts
+++ b/tests/engine/io/fig/import/legacy/constraints.test.ts
@@ -1,26 +1,26 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from './helpers'
describe('fig-import: constraints', () => {
test('horizontal and vertical constraints', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('RECTANGLE', 10, 1, {
horizontalConstraint: 'STRETCH',
verticalConstraint: 'CENTER'
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.horizontalConstraint).toBe('STRETCH')
expect(n.verticalConstraint).toBe('CENTER')
})
test('defaults to MIN', () => {
- const graph = importNodeChanges([doc(), canvas(), node('RECTANGLE', 10, 1)])
+ const graph = materializeDocument([doc(), canvas(), node('RECTANGLE', 10, 1)]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.horizontalConstraint).toBe('MIN')
expect(n.verticalConstraint).toBe('MIN')
diff --git a/tests/engine/io/fig/import/legacy/corners.test.ts b/tests/engine/io/fig/import/legacy/corners.test.ts
index e1a940edf..c8bf8c174 100644
--- a/tests/engine/io/fig/import/legacy/corners.test.ts
+++ b/tests/engine/io/fig/import/legacy/corners.test.ts
@@ -1,20 +1,20 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { canvas, doc, node } from './helpers'
describe('fig-import: corner geometry', () => {
test('imports corner smoothing', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('RECTANGLE', 10, 1, {
cornerRadius: 24,
cornerSmoothing: 0.72
} as Partial<NodeChange>)
- ])
+ ]).graph
const imported = graph.getChildren(graph.getPages()[0].id)[0]
expect(imported.cornerRadius).toBe(24)
expect(imported.cornerSmoothing).toBe(0.72)
diff --git a/tests/engine/io/fig/import/legacy/effects.test.ts b/tests/engine/io/fig/import/legacy/effects.test.ts
index 5dcd78875..1879f23ac 100644
--- a/tests/engine/io/fig/import/legacy/effects.test.ts
+++ b/tests/engine/io/fig/import/legacy/effects.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from './helpers'
describe('fig-import: effects', () => {
test('drop shadow', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('RECTANGLE', 10, 1, {
@@ -21,7 +21,7 @@ describe('fig-import: effects', () => {
}
] as NodeChange['effects']
})
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.effects).toHaveLength(1)
expect(n.effects[0].type).toBe('DROP_SHADOW')
@@ -30,7 +30,7 @@ describe('fig-import: effects', () => {
})
test('inner shadow', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('RECTANGLE', 10, 1, {
@@ -45,7 +45,7 @@ describe('fig-import: effects', () => {
}
] as NodeChange['effects']
})
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.effects[0].type).toBe('INNER_SHADOW')
})
diff --git a/tests/engine/io/fig/import/legacy/fills.test.ts b/tests/engine/io/fig/import/legacy/fills.test.ts
index d97da06ea..01b443094 100644
--- a/tests/engine/io/fig/import/legacy/fills.test.ts
+++ b/tests/engine/io/fig/import/legacy/fills.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { expectDefined } from '#tests/helpers/assert'
@@ -8,7 +8,7 @@ import { canvas, doc, node } from './helpers'
describe('fig-import: gradient fills', () => {
test('linear gradient', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('RECTANGLE', 10, 1, {
@@ -26,7 +26,7 @@ describe('fig-import: gradient fills', () => {
}
] as NodeChange['fillPaints']
})
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.fills).toHaveLength(1)
expect(n.fills[0].type).toBe('GRADIENT_LINEAR')
@@ -38,7 +38,7 @@ describe('fig-import: gradient fills', () => {
})
test('radial gradient', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('ELLIPSE', 10, 1, {
@@ -56,7 +56,7 @@ describe('fig-import: gradient fills', () => {
}
] as NodeChange['fillPaints']
})
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.fills[0].type).toBe('GRADIENT_RADIAL')
expect(n.fills[0].opacity).toBe(0.8)
diff --git a/tests/engine/io/fig/import/legacy/image/fills.test.ts b/tests/engine/io/fig/import/legacy/image/fills.test.ts
index 11dd0bbe9..d3f242f5f 100644
--- a/tests/engine/io/fig/import/legacy/image/fills.test.ts
+++ b/tests/engine/io/fig/import/legacy/image/fills.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from '../helpers'
@@ -9,7 +9,7 @@ describe('fig-import: image fills', () => {
const hash: Record<string, number> = {}
for (let i = 0; i < 20; i++) hash[String(i)] = i + 10
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('RECTANGLE', 10, 1, {
@@ -25,7 +25,7 @@ describe('fig-import: image fills', () => {
}
] as NodeChange['fillPaints']
})
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.fills[0].type).toBe('IMAGE')
expect(n.fills[0].imageHash).toBeDefined()
@@ -36,7 +36,7 @@ describe('fig-import: image fills', () => {
test('images stored on graph', () => {
const images = new Map<string, Uint8Array>()
images.set('abc123', new Uint8Array([1, 2, 3]))
- const graph = importNodeChanges([doc(), canvas()], [], images)
+ const graph = materializeDocument([doc(), canvas()], [], { images }).graph
expect(graph.images.get('abc123')).toEqual(new Uint8Array([1, 2, 3]))
})
})
diff --git a/tests/engine/io/fig/import/legacy/independent/strokes.test.ts b/tests/engine/io/fig/import/legacy/independent/strokes.test.ts
index 6890533cb..284f8fd24 100644
--- a/tests/engine/io/fig/import/legacy/independent/strokes.test.ts
+++ b/tests/engine/io/fig/import/legacy/independent/strokes.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from '../helpers'
describe('fig-import: independent stroke weights', () => {
test('border weights imported', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, {
@@ -16,7 +16,7 @@ describe('fig-import: independent stroke weights', () => {
borderLeftWeight: 4,
borderStrokeWeightsIndependent: true
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.borderTopWeight).toBe(2)
expect(n.borderRightWeight).toBe(4)
diff --git a/tests/engine/io/fig/import/legacy/multiple/fills.test.ts b/tests/engine/io/fig/import/legacy/multiple/fills.test.ts
index c0fe4c277..33da833d7 100644
--- a/tests/engine/io/fig/import/legacy/multiple/fills.test.ts
+++ b/tests/engine/io/fig/import/legacy/multiple/fills.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from '../helpers'
describe('fig-import: multiple fills', () => {
test('solid + gradient stacked', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('RECTANGLE', 10, 1, {
@@ -31,7 +31,7 @@ describe('fig-import: multiple fills', () => {
}
] as NodeChange['fillPaints']
})
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.fills).toHaveLength(2)
expect(n.fills[0].type).toBe('SOLID')
diff --git a/tests/engine/io/fig/import/legacy/node/types.test.ts b/tests/engine/io/fig/import/legacy/node/types.test.ts
index beb1ab4ab..f5d203182 100644
--- a/tests/engine/io/fig/import/legacy/node/types.test.ts
+++ b/tests/engine/io/fig/import/legacy/node/types.test.ts
@@ -1,36 +1,36 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from '../helpers'
describe('fig-import: node types', () => {
test('ROUNDED_RECTANGLE imported as its own type', () => {
- const graph = importNodeChanges([doc(), canvas(), node('ROUNDED_RECTANGLE', 10, 1)])
+ const graph = materializeDocument([doc(), canvas(), node('ROUNDED_RECTANGLE', 10, 1)]).graph
const nodes = graph.getChildren(graph.getPages()[0].id)
expect(nodes[0].type).toBe('ROUNDED_RECTANGLE')
})
test('COMPONENT maps to COMPONENT', () => {
- const graph = importNodeChanges([doc(), canvas(), node('COMPONENT', 10, 1)])
+ const graph = materializeDocument([doc(), canvas(), node('COMPONENT', 10, 1)]).graph
const nodes = graph.getChildren(graph.getPages()[0].id)
expect(nodes[0].type).toBe('COMPONENT')
})
test('INSTANCE maps to INSTANCE', () => {
- const graph = importNodeChanges([doc(), canvas(), node('INSTANCE', 10, 1)])
+ const graph = materializeDocument([doc(), canvas(), node('INSTANCE', 10, 1)]).graph
const nodes = graph.getChildren(graph.getPages()[0].id)
expect(nodes[0].type).toBe('INSTANCE')
})
test('SYMBOL maps to COMPONENT', () => {
- const graph = importNodeChanges([doc(), canvas(), node('SYMBOL', 10, 1)])
+ const graph = materializeDocument([doc(), canvas(), node('SYMBOL', 10, 1)]).graph
const nodes = graph.getChildren(graph.getPages()[0].id)
expect(nodes[0].type).toBe('COMPONENT')
})
test('REGULAR_POLYGON maps to POLYGON', () => {
- const graph = importNodeChanges([doc(), canvas(), node('REGULAR_POLYGON', 10, 1)])
+ const graph = materializeDocument([doc(), canvas(), node('REGULAR_POLYGON', 10, 1)]).graph
const nodes = graph.getChildren(graph.getPages()[0].id)
expect(nodes[0].type).toBe('POLYGON')
})
diff --git a/tests/engine/io/fig/import/legacy/shared-styles.test.ts b/tests/engine/io/fig/import/legacy/shared-styles.test.ts
index b4dec4f9d..1cf517400 100644
--- a/tests/engine/io/fig/import/legacy/shared-styles.test.ts
+++ b/tests/engine/io/fig/import/legacy/shared-styles.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { canvas, doc, node } from './helpers'
@@ -26,7 +26,7 @@ const grid = { pattern: 'COLUMNS', count: 12, gutterSize: 16, visible: true }
describe('fig-import: shared styles', () => {
test('models all style references and keeps definitions internal', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('ROUNDED_RECTANGLE', 20, 1, {
@@ -59,15 +59,17 @@ describe('fig-import: shared styles', () => {
styleIdForEffect: { guid: { sessionID: 1, localID: 22 } },
styleIdForGrid: { guid: { sessionID: 1, localID: 23 } }
} as Partial<NodeChange>)
- ])
+ ]).graph
const target = [...graph.getAllNodes()].find((item) => item.name === 'Styled target')
+ const styleId = (name: string) =>
+ [...graph.getAllNodes()].find((node) => node.name === name)?.id
expect(target).toMatchObject({
- fillStyleId: '1:20',
- strokeStyleId: '1:20',
- textStyleId: '1:21',
- effectStyleId: '1:22',
- gridStyleId: '1:23',
+ fillStyleId: styleId('Brand/Fill'),
+ strokeStyleId: styleId('Brand/Fill'),
+ textStyleId: styleId('Type/Body'),
+ effectStyleId: styleId('Effects/Card'),
+ gridStyleId: styleId('Grid/12 columns'),
fontSize: 18,
fontWeight: 700,
lineHeight: 26,
diff --git a/tests/engine/io/fig/import/legacy/text.test.ts b/tests/engine/io/fig/import/legacy/text.test.ts
index 582f44ff5..fe14ab923 100644
--- a/tests/engine/io/fig/import/legacy/text.test.ts
+++ b/tests/engine/io/fig/import/legacy/text.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from './helpers'
describe('fig-import: text properties', () => {
test('text auto resize', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('TEXT', 10, 1, {
@@ -15,7 +15,7 @@ describe('fig-import: text properties', () => {
textAlignHorizontal: 'CENTER',
textAutoResize: 'WIDTH_AND_HEIGHT'
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.textAutoResize).toBe('WIDTH_AND_HEIGHT')
expect(n.textAlignHorizontal).toBe('CENTER')
@@ -23,7 +23,7 @@ describe('fig-import: text properties', () => {
test('imports derived glyph geometry for Figma text rendering', () => {
const glyphBlob = new Uint8Array([0])
- const graph = importNodeChanges(
+ const graph = materializeDocument(
[
doc(),
canvas(),
@@ -46,11 +46,12 @@ describe('fig-import: text properties', () => {
} as Partial<NodeChange>)
],
[glyphBlob]
- )
+ ).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.derivedTextGlyphs).toEqual([
{
commandsBlob: glyphBlob,
+ firstCharacter: 0,
x: 2,
y: 8,
fontSize: 14,
@@ -68,7 +69,7 @@ describe('fig-import: text properties', () => {
})
test('uses derived line metrics for imported Figma text rendering', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('TEXT', 10, 1, {
@@ -90,13 +91,13 @@ describe('fig-import: text properties', () => {
]
}
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.lineHeight).toBe(16.94)
})
test('applies shared text style refs', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('TEXT', 20, 1, {
@@ -113,12 +114,12 @@ describe('fig-import: text properties', () => {
textDecoration: 'UNDERLINE',
styleIdForText: { guid: { sessionID: 1, localID: 20 } }
} as Partial<NodeChange>)
- ])
+ ]).graph
const styled = graph
.getChildren(graph.getPages()[0].id)
.find((node) => node.text === 'Styled text')
expect(styled?.fontSize).toBe(16)
- expect(styled?.textStyleId).toBe('1:20')
+ expect(graph.getNode(styled?.textStyleId ?? '')?.name).toBe('Body style')
expect(styled?.fontWeight).toBe(400)
expect(styled?.lineHeight).toBe(24)
expect(styled?.textDecoration).toBe('NONE')
@@ -127,7 +128,7 @@ describe('fig-import: text properties', () => {
})
test('applies shared fill style refs', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('ROUNDED_RECTANGLE', 30, 1, {
@@ -155,11 +156,11 @@ describe('fig-import: text properties', () => {
],
styleIdForFill: { guid: { sessionID: 1, localID: 30 } }
} as Partial<NodeChange>)
- ])
+ ]).graph
const styled = graph
.getChildren(graph.getPages()[0].id)
.find((node) => node.name === 'ROUNDED_RECTANGLE_10')
- expect(styled?.fillStyleId).toBe('1:30')
+ expect(graph.getNode(styled?.fillStyleId ?? '')?.name).toBe('slate/900')
expect(styled?.fills[0]?.color).toEqual({
r: 0.05882352963089943,
g: 0.09019608050584793,
@@ -181,14 +182,14 @@ describe('fig-import: text properties', () => {
] as const
for (const [style, expected] of cases) {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('TEXT', 10, 1, {
textData: { characters: 'X' },
fontName: { family: 'Inter', style }
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.fontWeight).toBe(expected)
}
diff --git a/tests/engine/io/fig/import/legacy/transforms.test.ts b/tests/engine/io/fig/import/legacy/transforms.test.ts
index f1bfea76c..1d6d31ba0 100644
--- a/tests/engine/io/fig/import/legacy/transforms.test.ts
+++ b/tests/engine/io/fig/import/legacy/transforms.test.ts
@@ -1,19 +1,19 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from './helpers'
describe('fig-import: transforms', () => {
test('flipped transforms use their visual bounds', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('VECTOR', 10, 1, {
size: { x: 17, y: 36 },
transform: { m00: -1, m01: 0, m02: 70, m10: 0, m11: 1, m12: 7 }
})
- ])
+ ]).graph
const imported = graph.getChildren(graph.getPages()[0].id)[0]
expect(imported.x).toBe(53)
@@ -22,14 +22,14 @@ describe('fig-import: transforms', () => {
})
test('rotated transforms preserve the Figma matrix origin', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('VECTOR', 10, 1, {
size: { x: 100, y: 20 },
transform: { m00: 0, m01: -1, m02: 10, m10: 1, m11: 0, m12: 20 }
})
- ])
+ ]).graph
const imported = graph.getChildren(graph.getPages()[0].id)[0]
expect(imported.x).toBeCloseTo(-50)
diff --git a/tests/engine/io/fig/import/legacy/variables.test.ts b/tests/engine/io/fig/import/legacy/variables.test.ts
index 98d9210be..4d1d8f065 100644
--- a/tests/engine/io/fig/import/legacy/variables.test.ts
+++ b/tests/engine/io/fig/import/legacy/variables.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { expectDefined } from '#tests/helpers/assert'
@@ -8,7 +8,7 @@ import { canvas, doc, node } from './helpers'
describe('fig-import: variable asset refs', () => {
test('imports node-scoped modes and native paint aliases', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
{
@@ -67,7 +67,7 @@ describe('fig-import: variable asset refs', () => {
}
] as NodeChange['fillPaints']
})
- ])
+ ]).graph
const frame = expectDefined(
[...graph.getAllNodes()].find((candidate) => candidate.name === 'Dark scope'),
@@ -84,7 +84,7 @@ describe('fig-import: variable asset refs', () => {
})
test('imports native scalar variable bindings', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
{
@@ -131,7 +131,7 @@ describe('fig-import: variable asset refs', () => {
]
}
})
- ])
+ ]).graph
const frame = expectDefined(
[...graph.getAllNodes()].find((candidate) => candidate.name === 'FRAME_30'),
@@ -145,7 +145,7 @@ describe('fig-import: variable asset refs', () => {
})
test('resolves color variables and aliases by assetRef', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
{
@@ -209,7 +209,7 @@ describe('fig-import: variable asset refs', () => {
}
] as NodeChange['fillPaints']
})
- ])
+ ]).graph
const primary = expectDefined(
[...graph.variables.values()].find((v) => v.name === 'Primary'),
diff --git a/tests/engine/io/fig/import/property-integrity.test.ts b/tests/engine/io/fig/import/property-integrity.test.ts
index 72fb0211d..f655c0b33 100644
--- a/tests/engine/io/fig/import/property-integrity.test.ts
+++ b/tests/engine/io/fig/import/property-integrity.test.ts
@@ -2,7 +2,7 @@ import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
import { type Fill, type SceneNode } from '@open-pencil/core'
-import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig/fixtures'
setDefaultTimeout(60_000)
diff --git a/tests/engine/io/fig/import/scaled-instance-strokes.test.ts b/tests/engine/io/fig/import/scaled-instance-strokes.test.ts
index 9694501dc..a963494fd 100644
--- a/tests/engine/io/fig/import/scaled-instance-strokes.test.ts
+++ b/tests/engine/io/fig/import/scaled-instance-strokes.test.ts
@@ -1,10 +1,47 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { canvas, doc, node } from './legacy/helpers'
+for (const uniformScale of [false, true]) {
+ test(`uses recorded uniform scale rather than root stroke weight (scaled=${uniformScale})`, () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const { graph, sources } = materializeDocument([
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 24, y: 24 }
+ },
+ {
+ guid: guid(3),
+ type: 'VECTOR',
+ parentIndex: { guid: guid(2), position: '!' },
+ size: { x: 4, y: 8 },
+ strokeWeight: 2,
+ strokePaints: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 } }],
+ horizontalConstraint: 'SCALE',
+ verticalConstraint: 'SCALE'
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ size: { x: 16, y: 16 },
+ strokeWeight: 2 / 3,
+ symbolData: { symbolID: guid(2), uniformScaleFactor: uniformScale ? 2 / 3 : 1 }
+ }
+ ])
+ const id = sources.get('1:4')
+ if (!id) throw new Error('Missing instance')
+ expect(graph.getChildren(id)[0].strokes[0].weight).toBeCloseTo(uniformScale ? 4 / 3 : 2)
+ })
+}
+
function pointGeometry(x: number, y: number): Uint8Array {
const bytes = new Uint8Array(9)
bytes[0] = 1
@@ -20,7 +57,7 @@ describe('fig import scaled instance strokes', () => {
const vectorGuid = { sessionID: 1, localID: 11 }
const instanceGuid = { sessionID: 1, localID: 20 }
- const graph = importNodeChanges(
+ const graph = materializeDocument(
[
doc(),
canvas(),
@@ -52,9 +89,8 @@ describe('fig import scaled instance strokes', () => {
} as Partial<NodeChange>)
],
[],
- undefined,
- { populate: 'all' }
- )
+ { derivedBounds: true }
+ ).graph
const instance = Array.from(graph.getAllNodes()).find(
(sceneNode) => sceneNode.name === 'INSTANCE_20'
@@ -68,7 +104,7 @@ describe('fig import scaled instance strokes', () => {
test('does not scale explicit derived vector geometry twice', () => {
const componentGuid = { sessionID: 1, localID: 21 }
const vectorGuid = { sessionID: 1, localID: 22 }
- const graph = importNodeChanges(
+ const graph = materializeDocument(
[
doc(),
canvas(),
@@ -97,9 +133,8 @@ describe('fig import scaled instance strokes', () => {
} as Partial<NodeChange>)
],
[pointGeometry(12, 12), pointGeometry(6, 6)],
- undefined,
- { populate: 'all' }
- )
+ { derivedBounds: true }
+ ).graph
const instance = Array.from(graph.getAllNodes()).find(
(sceneNode) => sceneNode.name === 'INSTANCE_23'
@@ -116,11 +151,11 @@ describe('fig import scaled instance strokes', () => {
expect(view.getFloat32(5, true)).toBe(6)
})
- test('applies explicit instance stroke scale to scaled vectors', () => {
+ test('applies the explicit uniform scale to inherited vector strokes', () => {
const componentGuid = { sessionID: 1, localID: 30 }
const vectorGuid = { sessionID: 1, localID: 31 }
- const graph = importNodeChanges(
+ const graph = materializeDocument(
[
doc(),
canvas(),
@@ -148,13 +183,12 @@ describe('fig import scaled instance strokes', () => {
node('INSTANCE', 40, 1, {
size: { x: 16, y: 16 },
strokeWeight: 2 / 3,
- symbolData: { symbolID: componentGuid }
+ symbolData: { symbolID: componentGuid, uniformScaleFactor: 2 / 3 }
} as Partial<NodeChange>)
],
[],
- undefined,
- { populate: 'all' }
- )
+ { derivedBounds: true }
+ ).graph
const instance = Array.from(graph.getAllNodes()).find(
(sceneNode) => sceneNode.name === 'INSTANCE_40'
diff --git a/tests/engine/io/fig/import/strokes.test.ts b/tests/engine/io/fig/import/strokes.test.ts
index 2f0128f7b..536fa3d0e 100644
--- a/tests/engine/io/fig/import/strokes.test.ts
+++ b/tests/engine/io/fig/import/strokes.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { canvas, doc, node } from './legacy/helpers'
describe('fig-import: stroke options', () => {
test('stroke cap and join', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('VECTOR', 10, 1, {
@@ -25,7 +25,7 @@ describe('fig-import: stroke options', () => {
strokeJoin: 'BEVEL',
miterLimit: 9
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.strokes[0].cap).toBe('ROUND')
expect(n.strokes[0].join).toBe('BEVEL')
@@ -33,7 +33,7 @@ describe('fig-import: stroke options', () => {
})
test('dash pattern', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('RECTANGLE', 10, 1, {
@@ -50,7 +50,7 @@ describe('fig-import: stroke options', () => {
strokeAlign: 'CENTER',
dashPattern: [10, 5]
} as Partial<NodeChange>)
- ])
+ ]).graph
const n = graph.getChildren(graph.getPages()[0].id)[0]
expect(n.strokes[0].dashPattern).toEqual([10, 5])
})
diff --git a/tests/engine/io/fig/import/style-refs.test.ts b/tests/engine/io/fig/import/style-refs.test.ts
index f08114358..53345516e 100644
--- a/tests/engine/io/fig/import/style-refs.test.ts
+++ b/tests/engine/io/fig/import/style-refs.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { applyStyleRefsToFields } from '@open-pencil/fig/node-change'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
@@ -21,7 +21,7 @@ describe('fig import style refs', () => {
blendMode: 'NORMAL' as const
}
const parentIndex = { guid: { sessionID: 0, localID: 1 }, position: '!' }
- const graph = importNodeChanges([
+ const graph = materializeDocument([
{ guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT', phase: 'CREATED' },
{
guid: { sessionID: 0, localID: 1 },
@@ -62,7 +62,7 @@ describe('fig import style refs', () => {
name: 'Fallback target',
styleIdForFill: { assetRef: { key: 'purple-light' } }
}
- ] as NodeChange[])
+ ] as NodeChange[]).graph
const nodes = [...graph.getAllNodes()]
expect(nodes.find((node) => node.name === 'Versioned target')?.fills).toEqual([versionedPaint])
diff --git a/tests/engine/io/fig/import/text-path.test.ts b/tests/engine/io/fig/import/text-path.test.ts
index 0967a7706..ab4dcb835 100644
--- a/tests/engine/io/fig/import/text-path.test.ts
+++ b/tests/engine/io/fig/import/text-path.test.ts
@@ -10,7 +10,7 @@ import { exportFigFile } from '#core/io/formats/fig/export'
import { encodeVectorNetworkBlob } from '#core/vector'
import { expectDefined } from '#tests/helpers/assert'
-import { loadFigFixture } from '#tests/helpers/fig-fixtures'
+import { loadFigFixture } from '#tests/helpers/fig/fixtures'
/** exportFigFile returns a Uint8Array; parseFigBuffer takes an ArrayBuffer. */
function reparse(out: Uint8Array) {
diff --git a/tests/engine/io/fig/import/text-sizing.test.ts b/tests/engine/io/fig/import/text-sizing.test.ts
index 5b6e95ae6..8d68de2a0 100644
--- a/tests/engine/io/fig/import/text-sizing.test.ts
+++ b/tests/engine/io/fig/import/text-sizing.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'bun:test'
import type { Vector } from '@open-pencil/core'
-import { importNodeChanges } from '@open-pencil/core/kiwi'
+import { materializeDocument } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { getNodeOrThrow } from '#tests/helpers/assert'
@@ -77,19 +77,32 @@ function textNode(
}
describe('FIG text sizing import', () => {
- test('imports Figma auto-layout text matching derived layout as auto-size', () => {
- const graph = importNodeChanges([documentNode(), canvasNode(), stackFrame(2), textNode(3, 2)])
+ test('keeps explicit fixed text fixed even when its box matches derived layout', () => {
+ const graph = materializeDocument([
+ documentNode(),
+ canvasNode(),
+ stackFrame(2),
+ textNode(3, 2)
+ ]).graph
const text = graph.getAllNodes().find((node) => node.type === 'TEXT')
if (!text) throw new Error('Expected text node')
- expect(getNodeOrThrow(graph, text.id).textAutoResize).toBe('WIDTH_AND_HEIGHT')
+ expect(getNodeOrThrow(graph, text.id).textAutoResize).toBe('NONE')
expect(getNodeOrThrow(graph, text.id).width).toBe(56)
expect(getNodeOrThrow(graph, text.id).height).toBe(22)
})
+ test('preserves an explicit auto-size mode inside auto-layout', () => {
+ const textRecord = textNode(3, 2)
+ textRecord.textAutoResize = 'WIDTH_AND_HEIGHT'
+ const { graph } = materializeDocument([documentNode(), canvasNode(), stackFrame(2), textRecord])
+ const text = graph.getAllNodes().find((node) => node.type === 'TEXT')
+ expect(text?.textAutoResize).toBe('WIDTH_AND_HEIGHT')
+ })
+
test('keeps fixed text outside auto-layout fixed', () => {
- const graph = importNodeChanges([documentNode(), canvasNode(), textNode(3, 1)])
+ const graph = materializeDocument([documentNode(), canvasNode(), textNode(3, 1)]).graph
const text = graph.getAllNodes().find((node) => node.type === 'TEXT')
if (!text) throw new Error('Expected text node')
@@ -98,12 +111,12 @@ describe('FIG text sizing import', () => {
})
test('keeps explicit larger text boxes inside auto-layout fixed', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
documentNode(),
canvasNode(),
stackFrame(2),
textNode(3, 2, { size: { x: 120, y: 48 }, derivedSize: { x: 56, y: 22 } })
- ])
+ ]).graph
const text = graph.getAllNodes().find((node) => node.type === 'TEXT')
if (!text) throw new Error('Expected text node')
diff --git a/tests/engine/io/fig/plugin-data.test.ts b/tests/engine/io/fig/plugin-data.test.ts
index 3bf93cbd1..05702e969 100644
--- a/tests/engine/io/fig/plugin-data.test.ts
+++ b/tests/engine/io/fig/plugin-data.test.ts
@@ -3,17 +3,17 @@ import { describe, expect, test } from 'bun:test'
import {
exportFigFile,
FigmaAPI,
- importNodeChanges,
initCodec,
parseFigFile,
SceneGraph,
type NodeChange
} from '@open-pencil/core'
+import { materializeDocument } from '@open-pencil/fig'
import { deduplicateNodeChangePluginData } from '#core/kiwi'
import { expectDefined } from '#tests/helpers/assert'
-import { parseFixture } from '#tests/helpers/fig-fixtures'
+import { parseFixture } from '#tests/helpers/fig/fixtures'
function doc(): NodeChange {
return {
@@ -120,9 +120,9 @@ describe('plugin data', () => {
})
test('preserves plugin relaunch data from imported fig files', async () => {
- // Relaunch data lives on the imported node changes themselves, so the
- // small fixture without instance population is enough to cover it.
- const graph = await parseFixture('gold-preview.fig', { populate: 'none' })
+ // Relaunch data lives on the imported node changes themselves; the small fixture
+ // is enough, but `populate: 'none'` opens only page shells in the reader.
+ const graph = await parseFixture('gold-preview.fig', { populate: 'all' })
const nodeWithRelaunch = [...graph.getAllNodes()].find(
(node) => node.pluginRelaunchData.length > 0
)
@@ -174,11 +174,11 @@ describe('plugin data deduplication', () => {
{ pluginID: 'my-plugin', key: 'customKey', value: 'hello' }
]
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, { pluginData: entries })
- ])
+ ]).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
@@ -203,11 +203,11 @@ describe('plugin data deduplication', () => {
test('importNodeChanges with single pluginData entry preserves it (zero-copy path)', () => {
const entries = [{ pluginID: 'open-pencil', key: 'textDirection', value: 'LTR' }]
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, { pluginData: entries })
- ])
+ ]).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
@@ -220,7 +220,11 @@ describe('plugin data deduplication', () => {
})
test('importNodeChanges with empty pluginData returns empty array', () => {
- const graph = importNodeChanges([doc(), canvas(), node('FRAME', 10, 1, { pluginData: [] })])
+ const graph = materializeDocument([
+ doc(),
+ canvas(),
+ node('FRAME', 10, 1, { pluginData: [] })
+ ]).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
@@ -235,11 +239,11 @@ describe('FigmaNodeProxy plugin data lazy shared computation', () => {
await initCodec()
const entries = [{ pluginID: 'tokens', key: 'tokens/color', value: '{"h":240}' }]
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, { pluginData: entries })
- ])
+ ]).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
@@ -258,11 +262,11 @@ describe('FigmaNodeProxy plugin data lazy shared computation', () => {
{ pluginID: 'tokens', key: 'tokens/accent', value: '#ff0000' },
{ pluginID: 'tokens', key: 'tokens/bg', value: '#ffffff' }
]
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, { pluginData: entries })
- ])
+ ]).graph
const api = new FigmaAPI(graph)
const page = graph.getPages()[0]
@@ -297,13 +301,13 @@ describe('FigmaNodeProxy plugin data split-brain regression', () => {
await initCodec()
// Simulate an imported fig node with shared data encoded in pluginData
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, {
pluginData: [{ pluginID: 'tokens', key: 'tokens/accent', value: 'v1' }]
})
- ])
+ ]).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
@@ -333,13 +337,13 @@ describe('FigmaNodeProxy plugin data split-brain regression', () => {
test('deletion via setSharedPluginData survives roundtrip', async () => {
await initCodec()
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, {
pluginData: [{ pluginID: 'tokens', key: 'tokens/accent', value: 'v1' }]
})
- ])
+ ]).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
@@ -376,7 +380,7 @@ describe('extractPluginRelaunchData deduplication via importNodeChanges', () =>
const changes = [doc(), canvas(), node('FRAME', 10, 1, { pluginRelaunchData: relaunchEntries })]
deduplicateNodeChangePluginData(changes)
- const graph = importNodeChanges(changes)
+ const graph = materializeDocument(changes).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
@@ -398,11 +402,11 @@ describe('extractPluginRelaunchData deduplication via importNodeChanges', () =>
{ pluginID: 'plugin-b', command: 'configure', message: 'Config', isDeleted: true }
]
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, { pluginRelaunchData: relaunchEntries })
- ])
+ ]).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
@@ -410,11 +414,11 @@ describe('extractPluginRelaunchData deduplication via importNodeChanges', () =>
})
test('empty relaunch data returns empty array', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
node('FRAME', 10, 1, { pluginRelaunchData: [] })
- ])
+ ]).graph
const page = graph.getPages()[0]
const frame = graph.getChildren(page.id)[0]
diff --git a/tests/engine/io/fig/roundtrip/basic.test.ts b/tests/engine/io/fig/roundtrip/basic.test.ts
index fe58518e6..7cbb9996f 100644
--- a/tests/engine/io/fig/roundtrip/basic.test.ts
+++ b/tests/engine/io/fig/roundtrip/basic.test.ts
@@ -7,9 +7,10 @@ import {
SceneGraph,
type SceneNode
} from '@open-pencil/core'
+import { populateFigPage } from '@open-pencil/core/io/formats/fig'
import { expectDefined } from '#tests/helpers/assert'
-import { collectAllNodes, countByType } from '#tests/helpers/fig-traversal'
+import { collectAllNodes, countByType } from '#tests/helpers/fig/traversal'
setDefaultTimeout(60_000)
@@ -221,7 +222,10 @@ describe('roundtrip: export → re-import', () => {
const internal = allPages.find((p) => p.internalOnly)
expect(internal).toBeDefined()
expect(internal?.name).toBe('Internal Only Canvas')
- expect(reImported.getChildren(internal?.id ?? '').length).toBe(1)
+ if (!internal) throw new Error('Missing internal page')
+ // Internal content is retained but expanded only when explicitly requested.
+ expect(populateFigPage(reImported, internal.id)).toBe(true)
+ expect(reImported.getChildren(internal.id).length).toBe(1)
})
test('preserves node count', () => {
diff --git a/tests/engine/io/fig/roundtrip/exhaustive.test.ts b/tests/engine/io/fig/roundtrip/exhaustive.test.ts
index 714068fe1..629c8d0e4 100644
--- a/tests/engine/io/fig/roundtrip/exhaustive.test.ts
+++ b/tests/engine/io/fig/roundtrip/exhaustive.test.ts
@@ -47,27 +47,12 @@ const SPECS: FixtureSpec[] = [
{
file: 'tests/fixtures/gold-preview.fig',
fileSize: 550091,
- nodeCount: 38323,
- nodeTypes: {
- FRAME: 4006,
- GROUP: 519,
- ROUNDED_RECTANGLE: 3752,
- VECTOR: 14221,
- ELLIPSE: 24,
- INSTANCE: 11144,
- TEXT: 3260,
- POLYGON: 94,
- COMPONENT: 1293,
- COMPONENT_SET: 10
- },
schemaSize: 25036,
thumbnailSize: 23810,
thumbnailWidth: 400,
thumbnailHeight: 239,
imageCount: 3,
- figKiwiVersion: 101,
- g1ExportSize: 498456,
- g2ExportSize: 498456
+ figKiwiVersion: 101
}
]
@@ -499,19 +484,33 @@ function verifyFixture(spec: FixtureSpec): void {
expect(isZstdCompressed(g0Chunks[1])).toBe(true)
})
- test('G0 node count', async () => {
+ test('G0 is one connected tree with unique child ownership', async () => {
await g0Ready
- expect(g0.size).toBe(spec.nodeCount)
+ const visited = new Set<string>()
+ const pending = [g0Graph.rootId]
+ while (pending.length) {
+ const id = pending.pop()
+ if (!id) throw new Error('Missing traversal ID')
+ expect(visited.has(id), `duplicate or cyclic child ${id}`).toBe(false)
+ visited.add(id)
+ const node = g0Graph.getNode(id)
+ if (!node) throw new Error(`Missing graph node ${id}`)
+ for (const childId of node.childIds) {
+ expect(g0Graph.getNode(childId)?.parentId).toBe(node.id)
+ pending.push(childId)
+ }
+ }
+ expect(visited.size).toBe(g0Graph.nodes.size)
+ expect(g0.size).toBeGreaterThan(0)
})
- test('G0 node type distribution', async () => {
+ test('G0 instances reference real component definitions', async () => {
await g0Ready
- const typeCounts = new Map<string, number>()
- for (const node of g0.values()) {
- typeCounts.set(node.type, (typeCounts.get(node.type) ?? 0) + 1)
- }
- for (const [type, count] of Object.entries(spec.nodeTypes)) {
- expect(typeCounts.get(type) ?? 0, `node type ${type}`).toBe(count)
+ const instances = [...g0.values()].filter((node) => node.type === 'INSTANCE')
+ expect(instances.length).toBeGreaterThan(0)
+ for (const instance of instances) {
+ expect(instance.componentId).not.toBeNull()
+ expect(g0Graph.getNode(instance.componentId ?? '')?.type).toBe('COMPONENT')
}
})
@@ -522,14 +521,33 @@ function verifyFixture(spec: FixtureSpec): void {
expect(g1Chunks[0].byteLength).toBe(g0Chunks[0].byteLength)
})
- test('G1 export size', async () => {
+ test('G1 unedited export preserves the original archive bytes', async () => {
await ensureG1()
- expect(g1Export.byteLength).toBe(spec.g1ExportSize)
+ expect(g1Export).toEqual(new Uint8Array(g0Bytes))
})
- test('G2 export size', async () => {
+ test('G2 unedited export remains byte-identical', async () => {
await ensureG2()
- expect(g2Export.byteLength).toBe(spec.g2ExportSize)
+ expect(g2Export).toEqual(g1Export)
+ })
+
+ test('edited export re-encodes the document without mutating unloaded source pages', async () => {
+ await g0Ready
+ const edited = await parseFigFile(g0Bytes.slice(0), { populate: 'first-page' })
+ const page = edited.getPages()[0]
+ const name = `${page.name} (edited)`
+ edited.updateNode(page.id, { name })
+ const before = structuredClone([...edited.nodes])
+ const bytes = await exportFigFile(edited)
+ expect(bytes).not.toEqual(new Uint8Array(g0Bytes))
+ expect([...edited.nodes]).toEqual(before)
+ const reopened = await parseFigFile(bytes.slice().buffer as ArrayBuffer)
+ expect(reopened.getPages()[0].name).toBe(name)
+ expect(reopened.figSchemaDeflated).toEqual(edited.figSchemaDeflated)
+ // Unreferenced internal style definitions are outside the reader's reachable closure.
+ const visibleCount = (nodes: Map<string, SceneNode>) =>
+ [...nodes.values()].filter((node) => !node.sharedStyleType).length
+ expect(visibleCount(buildPathMap(reopened))).toBe(visibleCount(g0))
})
test('G0->G1 node count', async () => {
diff --git a/tests/engine/io/fig/roundtrip/export-settings.test.ts b/tests/engine/io/fig/roundtrip/export-settings.test.ts
index 97796c920..dc8324ef7 100644
--- a/tests/engine/io/fig/roundtrip/export-settings.test.ts
+++ b/tests/engine/io/fig/roundtrip/export-settings.test.ts
@@ -2,13 +2,12 @@ import { beforeAll, describe, expect, test } from 'bun:test'
import {
exportFigFile,
- importNodeChanges,
initCodec,
parseFigFile,
SceneGraph,
type NodeChange
} from '@open-pencil/core'
-import { effectiveFigmaRawNodeFields, parseFigBuffer } from '@open-pencil/fig'
+import { effectiveFigmaRawNodeFields, parseFigBuffer, materializeDocument } from '@open-pencil/fig'
import { MAX_EXPORT_SCALE } from '@open-pencil/scene-graph'
function decodeExport(bytes: Uint8Array) {
@@ -79,7 +78,7 @@ describe('fig roundtrip export settings', () => {
})
test('maps native Figma PNG content-scale settings when plugin data is absent', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
frame({
@@ -94,7 +93,7 @@ describe('fig roundtrip export settings', () => {
}
]
})
- ])
+ ]).graph
const importedFrame = [...graph.getAllNodes()].find(
(node) => node.name === 'Export settings frame'
)
@@ -119,13 +118,13 @@ describe('fig roundtrip export settings', () => {
test('does not resurrect native export settings after the user clears all rows', async () => {
// Imported node carries NATIVE export settings (no plugin override).
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
frame({
exportSettings: [{ imageType: 'PNG', constraint: { type: 'CONTENT_SCALE', value: 2 } }]
})
- ])
+ ]).graph
const node = [...graph.getAllNodes()].find((n) => n.name === 'Export settings frame')
if (!node) throw new Error('imported frame not found')
expect(node.exportSettings).toEqual([{ scale: 2, format: 'png' }])
@@ -142,13 +141,13 @@ describe('fig roundtrip export settings', () => {
})
test('clamps an out-of-range native export scale at the import boundary', () => {
- const graph = importNodeChanges([
+ const graph = materializeDocument([
doc(),
canvas(),
frame({
exportSettings: [{ imageType: 'PNG', constraint: { type: 'CONTENT_SCALE', value: 999999 } }]
})
- ])
+ ]).graph
const node = [...graph.getAllNodes()].find((n) => n.name === 'Export settings frame')
expect(node?.exportSettings).toEqual([{ scale: MAX_EXPORT_SCALE, format: 'png' }])
})
diff --git a/tests/engine/io/fig/roundtrip/group.test.ts b/tests/engine/io/fig/roundtrip/group.test.ts
index 1f0281454..c5365cf34 100644
--- a/tests/engine/io/fig/roundtrip/group.test.ts
+++ b/tests/engine/io/fig/roundtrip/group.test.ts
@@ -2,7 +2,7 @@ import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
-import { collectAllNodes } from '#tests/helpers/fig-traversal'
+import { collectAllNodes } from '#tests/helpers/fig/traversal'
setDefaultTimeout(60_000)
diff --git a/tests/engine/io/fig/roundtrip/helpers.ts b/tests/engine/io/fig/roundtrip/helpers.ts
index 2e729cf76..62ccf0093 100644
--- a/tests/engine/io/fig/roundtrip/helpers.ts
+++ b/tests/engine/io/fig/roundtrip/helpers.ts
@@ -1,3 +1,5 @@
+import { isEqual } from 'es-toolkit/predicate'
+
import type { SceneGraph, SceneNode } from '@open-pencil/core'
import type { ComponentPropertyDefinition } from '@open-pencil/scene-graph'
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
@@ -13,16 +15,12 @@ export interface Mismatch {
export interface FixtureSpec {
file: string
fileSize: number
- nodeCount: number
- nodeTypes: Record<string, number>
schemaSize: number
thumbnailSize: number
thumbnailWidth: number
thumbnailHeight: number
imageCount: number
figKiwiVersion: number
- g1ExportSize: number
- g2ExportSize: number
}
export interface VerifierContext {
@@ -97,11 +95,12 @@ function sameNodeReferences(
a.length === b.length &&
a.every((value, index) => {
const other = b[index]
- return (
- other !== undefined &&
- (sameNodeReference(ctx, value, other) ||
- (!ctx.aGraph.getNode(value) && !ctx.bGraph.getNode(other) && value === other))
- )
+ if (other === undefined) return false
+ if (sameNodeReference(ctx, value, other)) return true
+ if (ctx.aGraph.getNode(value) || ctx.bGraph.getNode(other)) return false
+ // Preferred choices may be retained external asset keys rather than graph nodes.
+ // A missing runtime/source GUID must not be accepted as an external asset.
+ return !/^\d+:\d+$/.test(value) && value === other
})
)
}
@@ -145,7 +144,7 @@ function verifyComponentPropertyDefinitions(ctx: VerifierContext): boolean {
preferredValues: otherPreferredValues,
...otherRest
} = other
- if (JSON.stringify(rest) !== JSON.stringify(otherRest)) return false
+ if (!isEqual(rest, otherRest)) return false
if (definition.type !== 'INSTANCE_SWAP') return defaultValue === otherDefaultValue
return (
@@ -219,6 +218,15 @@ export const SCENE_VERIFIERS = new Map<string, Verifier>([
return ctx.a === 'VARIANT' && ctx.b === 'TEXT'
}
],
+ ...(['fillStyleId', 'strokeStyleId', 'textStyleId', 'effectStyleId', 'gridStyleId'] as const).map(
+ (field): [string, Verifier] => [
+ field,
+ (ctx) =>
+ typeof ctx.a === 'string' &&
+ typeof ctx.b === 'string' &&
+ sameNodeReference(ctx, ctx.a, ctx.b)
+ ]
+ ),
['componentPropertyDefinitions', verifyComponentPropertyDefinitions],
['componentPropertyAssignments', verifyComponentPropertyAssignments]
])
@@ -239,7 +247,7 @@ function verifyAEntries(
if (aliasA?.guid) {
const found = bEntries.find((entryB) => {
const aliasB = entryB.variableData?.value?.alias
- return aliasB?.guid && JSON.stringify(aliasB.guid) === JSON.stringify(aliasA.guid)
+ return aliasB?.guid && isEqual(aliasB.guid, aliasA.guid)
})
if (!found) {
ctx.errors.push({
@@ -250,17 +258,18 @@ function verifyAEntries(
}
}
if (aliasA?.assetRef) {
- const found = bEntries.find((entryB) => {
+ const matches = bEntries.filter((entryB) => {
const aliasB = entryB.variableData?.value?.alias
- return (
- aliasB?.assetRef && JSON.stringify(aliasB.assetRef) === JSON.stringify(aliasA.assetRef)
- )
+ return aliasB?.assetRef && isEqual(aliasB.assetRef, aliasA.assetRef)
})
- if (found && found.variableField !== entryA.variableField) {
+ if (
+ matches.length > 0 &&
+ !matches.some((entryB) => entryB.variableField === entryA.variableField)
+ ) {
ctx.errors.push({
path: ctx.path,
key: ctx.key,
- message: `library variable field mismatch: expected ${entryA.variableField}, got ${found.variableField}`
+ message: `library variable field missing: ${entryA.variableField}`
})
}
}
@@ -283,7 +292,7 @@ function verifyBEntries(
if (aliasB?.guid) {
const found = aEntries.find((entryA) => {
const aliasA = entryA.variableData?.value?.alias
- return aliasA?.guid && JSON.stringify(aliasA.guid) === JSON.stringify(aliasB.guid)
+ return aliasA?.guid && isEqual(aliasA.guid, aliasB.guid)
})
if (!found) {
ctx.errors.push({
@@ -339,16 +348,16 @@ function verifyVarAlias(a: unknown, b: unknown): boolean {
const bGuid = bAlias?.guid
const aRef = aAlias?.assetRef
const bRef = bAlias?.assetRef
- if (aGuid && bGuid) return JSON.stringify(aGuid) === JSON.stringify(bGuid)
+ if (aGuid && bGuid) return isEqual(aGuid, bGuid)
if ((aRef && bGuid) || (aGuid && bRef)) return true
- if (aRef && bRef) return JSON.stringify(aRef) === JSON.stringify(bRef)
+ if (aRef && bRef) return isEqual(aRef, bRef)
return false
}
/** Verifier that defaults undefined values and compares strictly. */
function defaultEqual(defaultVal: unknown): Verifier {
return (ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const aVal = ctx.a === undefined ? defaultVal : ctx.a
const bVal = ctx.b === undefined ? defaultVal : ctx.b
return aVal === bVal
@@ -359,12 +368,16 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'letterSpacing',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const g1raw = ctx.b as JSONObject | undefined
const node = ctx.aNodes.get(ctx.path)
if (!node || node.fontSize == null) return true
const expected = node.letterSpacing
- const actual = g1raw?.value as number | undefined
+ const value = g1raw?.value
+ let actual = typeof value === 'number' ? value : undefined
+ if (actual !== undefined && g1raw?.units === 'PERCENT') {
+ actual = (actual * node.fontSize) / 100
+ }
if (expected != null && actual != null && Math.abs(expected - actual) > 0.05) {
ctx.errors.push({
path: ctx.path,
@@ -378,7 +391,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'lineHeight',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const g1raw = ctx.b as JSONObject | undefined
const node = ctx.aNodes.get(ctx.path)
if (!node || node.lineHeight == null) return true
@@ -390,7 +403,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'variableConsumptionMap',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const ga = ctx.a as VariableConsumptionMapShape | undefined
const gb = ctx.b as VariableConsumptionMapShape | undefined
verifyVariableConsumption(ga, gb, ctx)
@@ -400,7 +413,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'parameterConsumptionMap',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
return true
}
],
@@ -412,14 +425,14 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'componentPropDefs',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
return verifyComponentPropDefs(ctx.a, ctx.b)
}
],
[
'derivedTextData',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
return verifyDerivedTextData(ctx)
}
],
@@ -427,7 +440,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'indentationLevel',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const aVal = ctx.a === undefined ? 0 : ctx.a
const bVal = ctx.b === undefined ? 0 : ctx.b
return aVal === bVal
@@ -436,7 +449,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'sourceDirectionality',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const aVal = ctx.a === undefined ? 'AUTO' : ctx.a
const bVal = ctx.b === undefined ? 'AUTO' : ctx.b
return aVal === bVal
@@ -445,7 +458,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'listStartOffset',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const aVal = ctx.a === undefined ? 0 : ctx.a
const bVal = ctx.b === undefined ? 0 : ctx.b
return aVal === bVal
@@ -454,7 +467,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'isFirstLineOfList',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const aVal = ctx.a === undefined ? false : ctx.a
const bVal = ctx.b === undefined ? false : ctx.b
return aVal === bVal
@@ -463,7 +476,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'directionality',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const aVal = ctx.a === undefined ? 'AUTO' : ctx.a
const bVal = ctx.b === undefined ? 'AUTO' : ctx.b
return aVal === bVal
@@ -472,7 +485,7 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'directionalityIntent',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const aVal = ctx.a === undefined ? 'AUTO' : ctx.a
const bVal = ctx.b === undefined ? 'AUTO' : ctx.b
return aVal === bVal
@@ -481,14 +494,14 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'fontVersion',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
return ctx.b === '' || ctx.a === ctx.b
}
],
[
'postscript',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
return ctx.b === '' || ctx.a === ctx.b
}
],
@@ -496,14 +509,14 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'textUserLayoutVersion',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
- return (ctx.a === 3 || ctx.a === 4 || ctx.a === 5) && ctx.b === 4
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
+ return ctx.a === ctx.b || ((ctx.a === 3 || ctx.a === 4 || ctx.a === 5) && ctx.b === 4)
}
],
[
'blendMode',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
const aVal = ctx.a === undefined ? 'NORMAL' : ctx.a
const bVal = ctx.b === undefined ? 'NORMAL' : ctx.b
return aVal === bVal
@@ -515,14 +528,14 @@ export const RAW_VERIFIERS = new Map<string, Verifier>([
[
'colorVar',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
return verifyVarAlias(ctx.a, ctx.b)
}
],
[
'opacityVar',
(ctx) => {
- if (isIdempotent(ctx)) return JSON.stringify(ctx.a) === JSON.stringify(ctx.b)
+ if (isIdempotent(ctx)) return isEqual(ctx.a, ctx.b)
return verifyVarAlias(ctx.a, ctx.b)
}
]
diff --git a/tests/engine/io/fig/roundtrip/raw-verifiers/helpers.ts b/tests/engine/io/fig/roundtrip/raw-verifiers/helpers.ts
index 23cc42b20..fb6ec91c5 100644
--- a/tests/engine/io/fig/roundtrip/raw-verifiers/helpers.ts
+++ b/tests/engine/io/fig/roundtrip/raw-verifiers/helpers.ts
@@ -1,3 +1,5 @@
+import { isEqual } from 'es-toolkit/predicate'
+
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
import type { VerifierContext } from '../helpers'
@@ -196,7 +198,7 @@ function verifySingleComponentPropDef(
aDef: Record<string, unknown>,
bDef: Record<string, unknown>
): boolean {
- if (JSON.stringify(aDef.id) !== JSON.stringify(bDef.id)) return false
+ if (!isEqual(aDef.id, bDef.id)) return false
if (aDef.name !== bDef.name) return false
if (!isComponentPropTypeEquivalent(aDef.type, bDef.type)) return false
diff --git a/tests/engine/io/fig/roundtrip/source-metadata.test.ts b/tests/engine/io/fig/roundtrip/source-metadata.test.ts
index 8a2c937d9..2ae20f831 100644
--- a/tests/engine/io/fig/roundtrip/source-metadata.test.ts
+++ b/tests/engine/io/fig/roundtrip/source-metadata.test.ts
@@ -81,8 +81,14 @@ describe('fig roundtrip source metadata', () => {
{ axis: 'Y', offset: 84 }
])
- expect(changes.get('4:4812')?.parentIndex?.position).toBe('~~~~~~~~~~1')
- expect(changes.get('4:4813')?.parentIndex?.position).toBe('~~~~~~~~~~3')
+ // Export generates a consistent sequence rather than mixing saved and generated keys.
+ const firstPosition = changes.get('4:4812')?.parentIndex?.position
+ const secondPosition = changes.get('4:4813')?.parentIndex?.position
+ expect(typeof firstPosition).toBe('string')
+ expect(typeof secondPosition).toBe('string')
+ if (firstPosition === undefined || secondPosition === undefined)
+ throw new Error('Missing exported sibling positions')
+ expect(firstPosition < secondPosition).toBe(true)
})
test('edited imported nodes export current geometry and paints', async () => {
diff --git a/tests/engine/io/fig/roundtrip/variables.test.ts b/tests/engine/io/fig/roundtrip/variables.test.ts
index 50b6b7713..eb9d4356f 100644
--- a/tests/engine/io/fig/roundtrip/variables.test.ts
+++ b/tests/engine/io/fig/roundtrip/variables.test.ts
@@ -10,7 +10,7 @@ import {
} from '@open-pencil/core'
import { expectDefined } from '#tests/helpers/assert'
-import { parseFixture } from '#tests/helpers/fig-fixtures'
+import { parseFixture } from '#tests/helpers/fig/fixtures'
import { runsHeavyTests } from '#tests/helpers/test-utils'
setDefaultTimeout(60_000)
@@ -59,6 +59,69 @@ describe('variable roundtrip', () => {
expect(Object.values(strVar.valuesByMode)[0]).toBe('Hello')
})
+ test('text bound to a string variable survives export → re-import', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const col = graph.createCollection('Content')
+ const label = graph.createVariable('Badge Count', 'STRING', col.id, '9+')
+ const page = graph.getPages()[0]
+ const text = graph.createNode('TEXT', page.id, { name: 'Label', text: '9+' })
+ graph.bindVariable(text.id, 'text', label.id)
+
+ const exported = await exportFigFile(graph)
+ const reimported = await parseFigFile(exported.buffer as ArrayBuffer)
+ const node = reimported
+ .getAllNodes()
+ .find((candidate) => candidate.type === 'TEXT' && candidate.name === 'Label')
+ const bound = reimported.variables.get(expectDefined(node, 'node').boundVariables.text ?? '')
+ expect(expectDefined(bound, 'bound').name).toBe('Badge Count')
+ expect(node.text).toBe('9+')
+ })
+
+ test('an instance fill override keeps its own variable alias across export → re-import', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const col = graph.createCollection('Schemes')
+ const onSurface = graph.createVariable('On Surface', 'COLOR', col.id, {
+ r: 0.11,
+ g: 0.1,
+ b: 0.12,
+ a: 1
+ })
+ const onSurfaceVariant = graph.createVariable('On Surface Variant', 'COLOR', col.id, {
+ r: 0.29,
+ g: 0.27,
+ b: 0.31,
+ a: 1
+ })
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id, { name: 'Icon' })
+ const icon = graph.createNode('RECTANGLE', component.id, {
+ name: 'icon',
+ width: 24,
+ height: 24,
+ fills: [
+ { type: 'SOLID', color: { r: 0.11, g: 0.1, b: 0.12, a: 1 }, opacity: 1, visible: true }
+ ]
+ })
+ graph.bindVariable(icon.id, 'fills/0/color', onSurface.id)
+ const instance = graph.createInstance(component.id, page.id)
+ const instanceIcon = expectDefined(graph.getChildren(instance.id)[0], 'instance icon')
+ graph.bindVariable(instanceIcon.id, 'fills/0/color', onSurfaceVariant.id)
+
+ const reimported = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)
+ const nameOf = (id: string | undefined) => reimported.variables.get(id ?? '')?.name
+ const nodes = [...reimported.getAllNodes()]
+ const componentIcon = nodes.find(
+ (n) => n.name === 'icon' && n.parentId === nodes.find((c) => c.type === 'COMPONENT')?.id
+ )
+ const pastedInstance = nodes.find((n) => n.type === 'INSTANCE')
+ const pastedIcon = reimported.getChildren(expectDefined(pastedInstance, 'instance').id)[0]
+ expect(nameOf(componentIcon?.boundVariables['fills/0/color'])).toBe('On Surface')
+ expect(nameOf(pastedIcon?.boundVariables['fills/0/color'])).toBe('On Surface Variant')
+ expect(pastedIcon?.fills[0]?.color.r).toBeCloseTo(0.29, 2)
+ })
+
test('variable bindings survive export → re-import', async () => {
await initCodec()
diff --git a/tests/engine/io/fig/roundtrip/verifier-contracts.test.ts b/tests/engine/io/fig/roundtrip/verifier-contracts.test.ts
new file mode 100644
index 000000000..ef3f40583
--- /dev/null
+++ b/tests/engine/io/fig/roundtrip/verifier-contracts.test.ts
@@ -0,0 +1,105 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { RAW_VERIFIERS, SCENE_VERIFIERS, type VerifierContext } from './helpers'
+
+function referenceContext(a: string, b: string): VerifierContext {
+ const aGraph = new SceneGraph()
+ const bGraph = new SceneGraph()
+ const aDefault = aGraph.createNode('COMPONENT', aGraph.getPages()[0].id)
+ const bDefault = bGraph.createNode('COMPONENT', bGraph.getPages()[0].id)
+ const definition = { id: 'property', name: 'Choice', type: 'INSTANCE_SWAP' }
+ const context: VerifierContext = {
+ a: [{ ...definition, defaultValue: aDefault.id, preferredValues: [a] }],
+ b: [{ ...definition, defaultValue: bDefault.id, preferredValues: [b] }],
+ key: 'componentPropertyDefinitions',
+ path: 'component',
+ aGraph,
+ bGraph,
+ aNodes: new Map([['default', aDefault]]),
+ bNodes: new Map([['default', bDefault]]),
+ aNodePaths: new Map([[aDefault.id, 'default']]),
+ bNodePaths: new Map([[bDefault.id, 'default']]),
+ aComponentPropertyDefinitions: new Map(),
+ bComponentPropertyDefinitions: new Map(),
+ errors: [],
+ label: 'G0->G1',
+ generation: 0,
+ fixture: {
+ file: 'synthetic',
+ fileSize: 0,
+ schemaSize: 0,
+ thumbnailSize: 0,
+ thumbnailWidth: 0,
+ thumbnailHeight: 0,
+ imageCount: 0,
+ figKiwiVersion: 0
+ }
+ }
+ return context
+}
+
+function comparePreferred(a: string, b: string): boolean {
+ const context = referenceContext(a, b)
+ const verifier = SCENE_VERIFIERS.get(context.key)
+ if (!verifier) throw new Error('Missing definition verifier')
+ return verifier(context)
+}
+
+test('raw letter-spacing comparison uses the saved unit and still rejects wrong spacing', () => {
+ const context = referenceContext('asset', 'asset')
+ const text = context.aGraph.createNode('TEXT', context.aGraph.getPages()[0].id, {
+ fontSize: 20,
+ letterSpacing: 0.1
+ })
+ context.aNodes.set(context.path, text)
+ context.key = 'letterSpacing'
+ context.b = { value: 0.5, units: 'PERCENT' }
+ const verifier = RAW_VERIFIERS.get(context.key)
+ if (!verifier) throw new Error('Missing letter-spacing verifier')
+ expect(verifier(context)).toBe(true)
+ expect(context.errors).toEqual([])
+ context.b = { value: 0.5, units: 'PIXELS' }
+ verifier(context)
+ expect(context.errors).toHaveLength(1)
+})
+
+test('idempotent comparison ignores object key order without losing undefined values', () => {
+ const context = referenceContext('asset', 'asset')
+ context.generation = 1
+ context.a = { value: 0.5, units: 'PERCENT' }
+ context.b = { units: 'PERCENT', value: 0.5 }
+ const verifier = RAW_VERIFIERS.get('letterSpacing')
+ if (!verifier) throw new Error('Missing letter-spacing verifier')
+ expect(verifier(context)).toBe(true)
+ context.a = [undefined]
+ context.b = [null]
+ expect(verifier(context)).toBe(false)
+})
+
+test('one variable can bind multiple fields without hiding a missing field', () => {
+ const context = referenceContext('asset', 'asset')
+ const entry = (variableField: string) => ({
+ variableField,
+ variableData: { value: { alias: { assetRef: { key: 'radius', version: 'v1' } } } }
+ })
+ context.key = 'variableConsumptionMap'
+ context.a = {
+ entries: [entry('RECTANGLE_TOP_LEFT_CORNER_RADIUS'), entry('RECTANGLE_TOP_RIGHT_CORNER_RADIUS')]
+ }
+ context.b = structuredClone(context.a)
+ const verifier = RAW_VERIFIERS.get(context.key)
+ if (!verifier) throw new Error('Missing variable verifier')
+ verifier(context)
+ expect(context.errors).toEqual([])
+ context.b = { entries: [entry('RECTANGLE_TOP_LEFT_CORNER_RADIUS')] }
+ verifier(context)
+ expect(context.errors).toHaveLength(1)
+})
+
+test('definition comparison preserves external preferred asset identity', () => {
+ expect(comparePreferred('external-asset-key', 'external-asset-key')).toBe(true)
+ expect(comparePreferred('external-asset-key', 'different-asset-key')).toBe(false)
+ expect(comparePreferred('999:999', '999:999')).toBe(false)
+})
diff --git a/tests/engine/io/subgraph.test.ts b/tests/engine/io/subgraph.test.ts
index c6ec88126..367fd39c7 100644
--- a/tests/engine/io/subgraph.test.ts
+++ b/tests/engine/io/subgraph.test.ts
@@ -6,7 +6,7 @@ import { parseFigBuffer } from '@open-pencil/fig'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig/fixtures'
describe('export subgraph extraction', () => {
test('page extraction keeps the source root and page descendants', () => {
diff --git a/tests/engine/kiwi/instance-overrides/sync-clones.test.ts b/tests/engine/kiwi/instance-overrides/sync-clones.test.ts
index 21d09c711..ae3c589b9 100644
--- a/tests/engine/kiwi/instance-overrides/sync-clones.test.ts
+++ b/tests/engine/kiwi/instance-overrides/sync-clones.test.ts
@@ -1,41 +1,57 @@
-import { describe, expect, test } from 'bun:test'
+import { expect, test } from 'bun:test'
-import { SceneGraph } from '@open-pencil/core'
-import { syncChildrenDeep } from '@open-pencil/fig/instance-overrides'
+import { materializeDocument } from '@open-pencil/fig'
-describe('instance override clone sync', () => {
- test('reclones nested instance children when the source component changes', () => {
- const graph = new SceneGraph()
- const page = graph.getPages()[0]
- const sourceParent = graph.createNode('FRAME', page.id)
- const targetParent = graph.createNode('FRAME', page.id)
- const sourceComponent = graph.createNode('COMPONENT', page.id, { name: 'source component' })
- const targetComponent = graph.createNode('COMPONENT', page.id, { name: 'target component' })
- graph.createNode('TEXT', sourceComponent.id, { name: 'label', text: 'Source' })
- graph.createNode('TEXT', targetComponent.id, { name: 'label', text: 'Target' })
- const sourceChild = graph.createNode('INSTANCE', sourceParent.id, {
- name: 'nested',
- componentId: sourceComponent.id
- })
- graph.populateInstanceChildren(sourceChild.id, sourceComponent.id)
- const targetChild = graph.createNode('INSTANCE', targetParent.id, {
- name: 'nested',
- componentId: targetComponent.id
- })
- graph.populateInstanceChildren(targetChild.id, targetComponent.id)
- const previousTargetLabel = graph.getChildren(targetChild.id)[0]
- const downstreamLabel = graph.createNode('TEXT', page.id, {
- name: 'downstream label',
- text: 'Target',
- componentId: previousTargetLabel.id
- })
-
- syncChildrenDeep(graph, sourceParent.id, targetParent.id, new Set())
-
- const syncedChild = graph.getNode(targetChild.id)
- const syncedLabel = graph.getChildren(targetChild.id)[0]
- expect(syncedChild?.componentId).toBe(sourceComponent.id)
- expect(syncedLabel.text).toBe('Source')
- expect(graph.getNode(downstreamLabel.id)?.componentId).toBe(syncedLabel.id)
- })
+test('nested component swap changes descendants through source instance chains', () => {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ const { graph, sources } = materializeDocument([
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ { guid: guid(2), type: 'SYMBOL', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ parentIndex: { guid: guid(2), position: '!' },
+ textData: { characters: 'Source' }
+ },
+ { guid: guid(4), type: 'SYMBOL', parentIndex: { guid: guid(1), position: '"' } },
+ {
+ guid: guid(5),
+ type: 'TEXT',
+ parentIndex: { guid: guid(4), position: '!' },
+ textData: { characters: 'Target' }
+ },
+ { guid: guid(6), type: 'SYMBOL', parentIndex: { guid: guid(1), position: '#' } },
+ {
+ guid: guid(7),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(6), position: '!' },
+ symbolData: { symbolID: guid(4) }
+ },
+ {
+ guid: guid(8),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '$' },
+ symbolData: {
+ symbolID: guid(6),
+ symbolOverrides: [{ guidPath: { guids: [guid(7)] }, overriddenSymbolID: guid(2) }]
+ }
+ },
+ {
+ guid: guid(9),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '%' },
+ symbolData: { symbolID: guid(8) }
+ }
+ ])
+ for (const id of ['1:8', '1:9']) {
+ const root = sources.get(id)
+ if (!root) throw new Error('Missing source instance')
+ const nested = graph.getChildren(root)[0]
+ expect(nested.componentId).toBe(sources.get('1:2'))
+ expect(graph.getChildren(nested.id).map((node) => node.text)).toEqual(['Source'])
+ expect(graph.getChildren(nested.id)[0].componentId).toBe(
+ graph.getChildren(sources.get('1:2') ?? '')[0].id
+ )
+ }
})
diff --git a/tests/engine/kiwi/serialize-fixes/component-metadata.test.ts b/tests/engine/kiwi/serialize-fixes/component-metadata.test.ts
index 812a46eab..bee1a4e30 100644
--- a/tests/engine/kiwi/serialize-fixes/component-metadata.test.ts
+++ b/tests/engine/kiwi/serialize-fixes/component-metadata.test.ts
@@ -48,6 +48,11 @@ describe('component metadata serialization', () => {
name: 'State',
type: 'VARIANT',
initialValue: { textValue: { characters: 'Enabled' } },
+ varValue: {
+ dataType: 'STRING',
+ resolvedDataType: 'STRING',
+ value: { textValue: 'Enabled' }
+ },
preferredValues: { stringValues: ['Enabled'] }
}
])
@@ -97,12 +102,29 @@ describe('component metadata serialization', () => {
const instanceKiwi = toKiwi(instance, graph)[0]
expect(instanceKiwi.componentPropAssignments).toEqual([
- { defID: { sessionID: 80, localID: 1 }, value: { boolValue: false } },
+ {
+ defID: { sessionID: 80, localID: 1 },
+ value: { boolValue: false },
+ varValue: { dataType: 'BOOLEAN', resolvedDataType: 'BOOLEAN', value: { boolValue: false } }
+ },
{
defID: { sessionID: 80, localID: 2 },
- value: { textValue: { characters: 'Changed' } }
+ value: { textValue: { characters: 'Changed' } },
+ varValue: {
+ dataType: 'STRING',
+ resolvedDataType: 'STRING',
+ value: { textValue: 'Changed' }
+ }
},
- { defID: { sessionID: 80, localID: 3 }, value: { guidValue: { sessionID: 70, localID: 1 } } }
+ {
+ defID: { sessionID: 80, localID: 3 },
+ value: { guidValue: { sessionID: 70, localID: 1 } },
+ varValue: {
+ dataType: 'SYMBOL_ID',
+ resolvedDataType: 'SYMBOL_ID',
+ value: { symbolIdValue: { guid: { sessionID: 70, localID: 1 } } }
+ }
+ }
])
})
})
diff --git a/tests/engine/render/canvas/chunks/gold-preview.test.ts b/tests/engine/render/canvas/chunks/gold-preview.test.ts
index e7a8aca77..87df06a7c 100644
--- a/tests/engine/render/canvas/chunks/gold-preview.test.ts
+++ b/tests/engine/render/canvas/chunks/gold-preview.test.ts
@@ -5,7 +5,7 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { RenderChunkIndex } from '#core/canvas/renderer/chunks'
import { expectDefined } from '#tests/helpers/assert'
-import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig/fixtures'
import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
setDefaultTimeout(HEAVY_TEST_TIMEOUT_MS)
diff --git a/tests/engine/render/canvas/derived-text.test.ts b/tests/engine/render/canvas/derived-text.test.ts
index b13f3d2d3..d21636725 100644
--- a/tests/engine/render/canvas/derived-text.test.ts
+++ b/tests/engine/render/canvas/derived-text.test.ts
@@ -45,6 +45,69 @@ function squareCommandsBlob(): Uint8Array {
}
describe('derived text rendering', () => {
+ test('uses run alpha and inherited paint at saved cluster positions', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const text = graph.createNode('TEXT', page.id, {
+ text: 'ffiX',
+ width: 40,
+ height: 20,
+ fontSize: 10,
+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 1, a: 1 }, opacity: 1, visible: true }],
+ styleRuns: [
+ {
+ start: 0,
+ length: 3,
+ style: {
+ fills: [
+ { type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 0.5, visible: true }
+ ]
+ }
+ }
+ ],
+ derivedTextGlyphs: [
+ { commandsBlob: squareCommandsBlob(), x: 0, y: 10, fontSize: 10, firstCharacter: 0 },
+ { commandsBlob: squareCommandsBlob(), x: 20, y: 10, fontSize: 10, firstCharacter: 3 }
+ ]
+ })
+ const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')
+ const renderer = new SkiaRenderer(ck, surface)
+ renderer.nodeFontReadiness = () => {
+ throw new Error('Saved text must not depend on font readiness')
+ }
+ try {
+ const png = expectDefined(
+ renderNodesToImage(ck, renderer, graph, page.id, [text.id], {
+ scale: 1,
+ format: 'PNG',
+ trimTransparent: false
+ }),
+ 'png'
+ )
+ const image = expectDefined(ck.MakeImageFromEncoded(png), 'image')
+ try {
+ const pixels = expectDefined(
+ image.readPixels(0, 0, {
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB,
+ width: image.width(),
+ height: image.height()
+ }),
+ 'pixels'
+ )
+ const at = (x: number, y: number) =>
+ Array.from(pixels.slice((y * image.width() + x) * 4, (y * image.width() + x) * 4 + 4))
+ expect(at(5, 5)).toEqual([255, 0, 0, 128])
+ expect(at(25, 5)).toEqual([0, 0, 255, 255])
+ } finally {
+ image.delete()
+ }
+ } finally {
+ renderer.destroy()
+ }
+ })
+
test('glyph silhouettes are disposed by cache clearing and renderer destruction', () => {
const renderer = new SkiaRenderer(
ck,
diff --git a/tests/engine/render/canvas/tiles/gold-preview.test.ts b/tests/engine/render/canvas/tiles/gold-preview.test.ts
index 8ab2edea4..7be562e74 100644
--- a/tests/engine/render/canvas/tiles/gold-preview.test.ts
+++ b/tests/engine/render/canvas/tiles/gold-preview.test.ts
@@ -14,7 +14,7 @@ import {
} from '#core/canvas/renderer/tiles'
import { expectDefined } from '#tests/helpers/assert'
-import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig/fixtures'
import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
setDefaultTimeout(HEAVY_TEST_TIMEOUT_MS)
diff --git a/tests/fixtures/absolute-constraint-figma.png b/tests/fixtures/absolute-constraint-figma.png
new file mode 100644
index 000000000..e06ae48b7
Binary files /dev/null and b/tests/fixtures/absolute-constraint-figma.png differ
diff --git a/tests/fixtures/nested-binding-authoring-figma.png b/tests/fixtures/nested-binding-authoring-figma.png
new file mode 100644
index 000000000..c2c9f3e54
Binary files /dev/null and b/tests/fixtures/nested-binding-authoring-figma.png differ
diff --git a/tests/fixtures/nested-binding-authoring.json b/tests/fixtures/nested-binding-authoring.json
new file mode 100644
index 000000000..2da8b57b1
--- /dev/null
+++ b/tests/fixtures/nested-binding-authoring.json
@@ -0,0 +1,87 @@
+{
+ "tokenValue": 12,
+ "native": {
+ "root": {
+ "width": 33,
+ "paddingRight": 6,
+ "boundVariables": {
+ "paddingRight": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ }
+ }
+ },
+ "nested": {
+ "width": 17,
+ "paddingRight": 6,
+ "boundVariables": {
+ "paddingLeft": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ },
+ "paddingRight": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ }
+ }
+ }
+ },
+ "reopened": {
+ "root": {
+ "width": 33,
+ "paddingRight": 6,
+ "boundVariables": {
+ "paddingRight": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ }
+ }
+ },
+ "nested": {
+ "width": 17,
+ "paddingRight": 6,
+ "boundVariables": {
+ "paddingLeft": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ },
+ "paddingRight": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ }
+ }
+ }
+ },
+ "componentEdit": {
+ "sourcePaddingTop": 8,
+ "paddingTop": 2,
+ "paddingRight": 6,
+ "height": 8,
+ "boundVariables": {
+ "paddingLeft": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ },
+ "paddingRight": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ }
+ }
+ },
+ "componentReopened": {
+ "width": 33,
+ "height": 8,
+ "paddingTop": 2,
+ "paddingRight": 6,
+ "boundVariables": {
+ "paddingLeft": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ },
+ "paddingRight": {
+ "type": "VARIABLE_ALIAS",
+ "id": "VariableID:293742:7"
+ }
+ }
+ }
+}
diff --git a/tests/fixtures/nested-binding-expression-figma.png b/tests/fixtures/nested-binding-expression-figma.png
new file mode 100644
index 000000000..6e857f618
Binary files /dev/null and b/tests/fixtures/nested-binding-expression-figma.png differ
diff --git a/tests/fixtures/nested-binding-ownership-figma.png b/tests/fixtures/nested-binding-ownership-figma.png
new file mode 100644
index 000000000..3fc9b4b78
Binary files /dev/null and b/tests/fixtures/nested-binding-ownership-figma.png differ
diff --git a/tests/fixtures/nested-binding-ownership-records.json b/tests/fixtures/nested-binding-ownership-records.json
new file mode 100644
index 000000000..bdd18d938
--- /dev/null
+++ b/tests/fixtures/nested-binding-ownership-records.json
@@ -0,0 +1,884 @@
+{
+ "nodeChanges": [
+ {
+ "guid": {
+ "sessionID": 0,
+ "localID": 0
+ },
+ "phase": "CREATED",
+ "type": "DOCUMENT",
+ "name": "Document",
+ "visible": true,
+ "opacity": 1,
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "CENTER",
+ "strokeJoin": "MITER",
+ "pluginData": [],
+ "documentColorProfile": "DISPLAY_P3"
+ },
+ {
+ "guid": {
+ "sessionID": 1,
+ "localID": 2
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "!"
+ },
+ "type": "SYMBOL",
+ "name": "Inner",
+ "userFacingVersion": "293733:3",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "293733:3",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 50,
+ "y": 28
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 6,
+ "stackHorizontalPadding": 20,
+ "stackVerticalPadding": 4,
+ "stackPaddingRight": 10,
+ "stackPaddingBottom": 4,
+ "pluginData": [
+ {
+ "pluginID": "open-pencil",
+ "value": "AUTO",
+ "key": "layoutDirection"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE",
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 7
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_LEFT"
+ }
+ ]
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 1,
+ "localID": 3
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 1,
+ "localID": 2
+ },
+ "position": "!"
+ },
+ "type": "ROUNDED_RECTANGLE",
+ "name": "Rectangle",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 20,
+ "y": 20
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 20,
+ "m10": 0,
+ "m11": 1,
+ "m12": 4
+ },
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.8509804010391235,
+ "g": 0.8509804010391235,
+ "b": 0.8509804010391235,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 0.8509804010391235,
+ "c1": 0.8509804010391235,
+ "c2": 0.8509804010391235,
+ "c3": 1
+ }
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 0,
+ "styleID": 0
+ }
+ ],
+ "pluginData": [
+ {
+ "pluginID": "open-pencil",
+ "value": "AUTO",
+ "key": "layoutDirection"
+ }
+ ],
+ "frameMaskDisabled": true
+ },
+ {
+ "guid": {
+ "sessionID": 1,
+ "localID": 4
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "\""
+ },
+ "type": "SYMBOL",
+ "name": "Outer",
+ "userFacingVersion": "293733:4",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "293733:4",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 65,
+ "y": 14
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 8,
+ "stackHorizontalPadding": 20,
+ "stackPaddingRight": 20,
+ "pluginData": [
+ {
+ "pluginID": "open-pencil",
+ "value": "AUTO",
+ "key": "layoutDirection"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 1,
+ "localID": 5
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 1,
+ "localID": 4
+ },
+ "position": "!"
+ },
+ "type": "INSTANCE",
+ "name": "Inner",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "293726:37",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 1,
+ "localID": 2
+ },
+ "symbolOverrides": [],
+ "uniformScaleFactor": 0.5
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 1,
+ "localID": 3
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 1,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 25,
+ "y": 14
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 20,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 3,
+ "stackHorizontalPadding": 10,
+ "stackVerticalPadding": 2,
+ "stackPaddingRight": 5,
+ "stackPaddingBottom": 2,
+ "pluginData": [
+ {
+ "pluginID": "open-pencil",
+ "value": "AUTO",
+ "key": "layoutDirection"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 3,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE",
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "expressionValue": {
+ "expressionFunction": "MULTIPLY",
+ "expressionArguments": [
+ {
+ "value": {
+ "floatValue": 0.5
+ },
+ "dataType": "FLOAT",
+ "resolvedDataType": "FLOAT"
+ },
+ {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 7
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ }
+ ]
+ }
+ },
+ "dataType": "EXPRESSION",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_LEFT"
+ }
+ ]
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 1,
+ "localID": 6
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "#"
+ },
+ "type": "INSTANCE",
+ "name": "Outer",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "293726:46",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 1,
+ "localID": 4
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 1,
+ "localID": 4
+ }
+ ]
+ },
+ "size": {
+ "x": 71,
+ "y": 14
+ },
+ "stackHorizontalPadding": 26
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 1,
+ "localID": 5
+ }
+ ]
+ },
+ "stackHorizontalPadding": 14
+ }
+ ],
+ "uniformScaleFactor": 0.5
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 1,
+ "localID": 5
+ }
+ ]
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 13,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 1,
+ "localID": 5
+ },
+ {
+ "sessionID": 1,
+ "localID": 3
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 2,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 35.5,
+ "y": 7
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 4,
+ "stackHorizontalPadding": 13,
+ "stackPaddingRight": 10,
+ "pluginData": [
+ {
+ "pluginID": "open-pencil",
+ "value": "AUTO",
+ "key": "layoutDirection"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 3,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 0,
+ "localID": 0
+ },
+ "position": "~!"
+ },
+ "type": "CANVAS",
+ "name": "Temporary scale contract probe",
+ "visible": true,
+ "opacity": 1,
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "backgroundOpacity": 1,
+ "strokeWeight": 1,
+ "strokeAlign": "CENTER",
+ "strokeJoin": "MITER",
+ "backgroundColor": {
+ "r": 0.11764705926179886,
+ "g": 0.11764705926179886,
+ "b": 0.11764705926179886,
+ "a": 1
+ },
+ "backgroundEnabled": true
+ },
+ {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 5
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 6
+ },
+ "position": "!"
+ },
+ "type": "VARIABLE_SET",
+ "name": "Scale token probe",
+ "isPublishable": true,
+ "version": "293733:0",
+ "userFacingVersion": "293733:0",
+ "variableSetModes": [
+ {
+ "id": {
+ "sessionID": 293733,
+ "localID": 0
+ },
+ "name": "Mode 1",
+ "sortPosition": "!"
+ }
+ ],
+ "isCollectionExtendable": true
+ },
+ {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 6
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 0,
+ "localID": 0
+ },
+ "position": "~\""
+ },
+ "type": "CANVAS",
+ "name": "Internal Only Canvas",
+ "visible": false,
+ "opacity": 1,
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "backgroundOpacity": 1,
+ "backgroundEnabled": true,
+ "internalOnly": true
+ },
+ {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 7
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 6
+ },
+ "position": "\""
+ },
+ "type": "VARIABLE",
+ "name": "Padding",
+ "isPublishable": true,
+ "version": "293733:3",
+ "userFacingVersion": "293733:3",
+ "sortPosition": "\"",
+ "variableSetID": {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 5
+ }
+ },
+ "variableResolvedType": "FLOAT",
+ "variableDataValues": {
+ "entries": [
+ {
+ "modeID": {
+ "sessionID": 293733,
+ "localID": 0
+ },
+ "variableData": {
+ "value": {
+ "floatValue": 20
+ },
+ "dataType": "FLOAT",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 8
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "$"
+ },
+ "type": "INSTANCE",
+ "name": "Outer",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 1,
+ "localID": 4
+ },
+ "symbolOverrides": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 1,
+ "localID": 4
+ }
+ ]
+ },
+ "size": {
+ "x": 67,
+ "y": 14
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 1,
+ "localID": 5
+ }
+ ]
+ },
+ "parameterConsumptionMap": {
+ "entries": [
+ {
+ "variableData": {
+ "value": {
+ "alias": {
+ "guid": {
+ "sessionID": 293742,
+ "localID": 7
+ }
+ }
+ },
+ "dataType": "ALIAS",
+ "resolvedDataType": "FLOAT"
+ },
+ "variableField": "STACK_PADDING_LEFT"
+ }
+ ]
+ }
+ }
+ ],
+ "uniformScaleFactor": 0.5
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 1,
+ "localID": 5
+ }
+ ]
+ },
+ "size": {
+ "x": 13.5,
+ "y": 7
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 1,
+ "localID": 5
+ },
+ {
+ "sessionID": 1,
+ "localID": 3
+ }
+ ]
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 6,
+ "m10": 0,
+ "m11": 1,
+ "m12": 1
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 2,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 33.5,
+ "y": 7
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 150,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 0,
+ "strokeAlign": "CENTER",
+ "strokeJoin": "BEVEL",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 4,
+ "stackHorizontalPadding": 10,
+ "stackPaddingRight": 10,
+ "pluginData": [
+ {
+ "pluginID": "open-pencil",
+ "value": "AUTO",
+ "key": "layoutDirection"
+ }
+ ],
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 3,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 293742,
+ "localID": 7
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 6
+ },
+ "position": "#"
+ },
+ "type": "VARIABLE",
+ "name": "Direct binding scope",
+ "isPublishable": true,
+ "version": "293743:2",
+ "userFacingVersion": "293743:2",
+ "sortPosition": "#",
+ "variableSetID": {
+ "guid": {
+ "sessionID": 293733,
+ "localID": 5
+ }
+ },
+ "variableResolvedType": "FLOAT",
+ "variableDataValues": {
+ "entries": [
+ {
+ "modeID": {
+ "sessionID": 293733,
+ "localID": 0
+ },
+ "variableData": {
+ "value": {
+ "floatValue": 12
+ },
+ "dataType": "FLOAT",
+ "resolvedDataType": "FLOAT"
+ }
+ }
+ ]
+ }
+ }
+ ],
+ "blobs": [
+ "AQAAAAAAAAAAAgAAoEEAAAAAAgAAoEEAAKBBAgAAAAAAAKBBAgAAAAAAAAAAAA==",
+ "AQAAAAAAAAAAAgAAIEEAAAAAAgAAIEEAACBBAgAAAAAAACBBAgAAAAAAAAAAAA==",
+ "AQAAAAAAAAAAAgAAoEAAAAAAAgAAoEAAAKBAAgAAAAAAAKBAAgAAAAAAAAAAAA=="
+ ]
+}
diff --git a/tests/fixtures/nested-component-scale-figma.png b/tests/fixtures/nested-component-scale-figma.png
new file mode 100644
index 000000000..ff70fc401
Binary files /dev/null and b/tests/fixtures/nested-component-scale-figma.png differ
diff --git a/tests/fixtures/nested-definition-rescale-figma.png b/tests/fixtures/nested-definition-rescale-figma.png
new file mode 100644
index 000000000..ea8feafdc
Binary files /dev/null and b/tests/fixtures/nested-definition-rescale-figma.png differ
diff --git a/tests/fixtures/nested-layout-scale-figma.png b/tests/fixtures/nested-layout-scale-figma.png
new file mode 100644
index 000000000..6e857f618
Binary files /dev/null and b/tests/fixtures/nested-layout-scale-figma.png differ
diff --git a/tests/fixtures/nested-layout-scale.json b/tests/fixtures/nested-layout-scale.json
new file mode 100644
index 000000000..cd4000b93
--- /dev/null
+++ b/tests/fixtures/nested-layout-scale.json
@@ -0,0 +1,920 @@
+{
+ "ids": {
+ "page": "293726:2919",
+ "inner": "293726:2920",
+ "outer": "293726:2922",
+ "nested": "293726:2923",
+ "instance": "293726:2925"
+ },
+ "before": [
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 0,
+ "localID": 0
+ },
+ "position": "~!"
+ },
+ "type": "CANVAS",
+ "name": "Temporary scale contract probe",
+ "visible": true,
+ "opacity": 1,
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "backgroundOpacity": 1,
+ "backgroundColor": {
+ "r": 0.11764705926179886,
+ "g": 0.11764705926179886,
+ "b": 0.11764705926179886,
+ "a": 1
+ },
+ "isPageDivider": false,
+ "backgroundEnabled": true
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2920
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "!"
+ },
+ "type": "SYMBOL",
+ "name": "Inner",
+ "userFacingVersion": "293726:37",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "293726:37",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 40,
+ "y": 28
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 6,
+ "stackHorizontalPadding": 10,
+ "stackVerticalPadding": 4,
+ "stackPaddingRight": 10,
+ "stackPaddingBottom": 4,
+ "stackLayoutVersion": 1,
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2921
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2920
+ },
+ "position": "!"
+ },
+ "type": "ROUNDED_RECTANGLE",
+ "name": "Rectangle",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 20,
+ "y": 20
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 10,
+ "m10": 0,
+ "m11": 1,
+ "m12": 4
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.8509804010391235,
+ "g": 0.8509804010391235,
+ "b": 0.8509804010391235,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 0.8509804010391235,
+ "c1": 0.8509804010391235,
+ "c2": 0.8509804010391235,
+ "c3": 1
+ }
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 0,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2922
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "\""
+ },
+ "type": "SYMBOL",
+ "name": "Outer",
+ "userFacingVersion": "293726:46",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "293726:46",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 60,
+ "y": 14
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 8,
+ "stackHorizontalPadding": 20,
+ "stackPaddingRight": 20,
+ "stackLayoutVersion": 1,
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2923
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2922
+ },
+ "position": "!"
+ },
+ "type": "INSTANCE",
+ "name": "Inner",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 293726,
+ "localID": 2920
+ },
+ "symbolOverrides": [],
+ "uniformScaleFactor": 0.5
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293726,
+ "localID": 2921
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 1,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 20,
+ "y": 14
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 20,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 0.5,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 3,
+ "stackHorizontalPadding": 5,
+ "stackVerticalPadding": 2,
+ "stackPaddingRight": 5,
+ "stackPaddingBottom": 2,
+ "stackLayoutVersion": 1,
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 3,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2925
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "#"
+ },
+ "type": "INSTANCE",
+ "name": "Scaled outer",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 293726,
+ "localID": 2922
+ },
+ "symbolOverrides": [
+ {
+ "name": "Scaled outer",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293726,
+ "localID": 2922
+ }
+ ]
+ },
+ "size": {
+ "x": 60,
+ "y": 14
+ }
+ }
+ ],
+ "uniformScaleFactor": 0.5
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293726,
+ "localID": 2923
+ },
+ {
+ "sessionID": 293726,
+ "localID": 2921
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 2,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 30,
+ "y": 7
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 0.5,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 4,
+ "stackHorizontalPadding": 10,
+ "stackPaddingRight": 10,
+ "stackLayoutVersion": 1,
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 3,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ }
+ ],
+ "edited": [
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 0,
+ "localID": 0
+ },
+ "position": "~!"
+ },
+ "type": "CANVAS",
+ "name": "Temporary scale contract probe",
+ "visible": true,
+ "opacity": 1,
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "backgroundOpacity": 1,
+ "backgroundColor": {
+ "r": 0.11764705926179886,
+ "g": 0.11764705926179886,
+ "b": 0.11764705926179886,
+ "a": 1
+ },
+ "isPageDivider": false,
+ "backgroundEnabled": true
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2920
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "!"
+ },
+ "type": "SYMBOL",
+ "name": "Inner",
+ "userFacingVersion": "293726:37",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "293726:37",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 40,
+ "y": 28
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 6,
+ "stackHorizontalPadding": 10,
+ "stackVerticalPadding": 4,
+ "stackPaddingRight": 10,
+ "stackPaddingBottom": 4,
+ "stackLayoutVersion": 1,
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2921
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2920
+ },
+ "position": "!"
+ },
+ "type": "ROUNDED_RECTANGLE",
+ "name": "Rectangle",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 20,
+ "y": 20
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 10,
+ "m10": 0,
+ "m11": 1,
+ "m12": 4
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 0.8509804010391235,
+ "g": 0.8509804010391235,
+ "b": 0.8509804010391235,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": true,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 0.8509804010391235,
+ "c1": 0.8509804010391235,
+ "c2": 0.8509804010391235,
+ "c3": 1
+ }
+ }
+ ],
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 0,
+ "styleID": 0
+ }
+ ]
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2922
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "\""
+ },
+ "type": "SYMBOL",
+ "name": "Outer",
+ "userFacingVersion": "293726:46",
+ "isSymbolPublishable": true,
+ "sharedSymbolVersion": "293726:46",
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 60,
+ "y": 14
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 1,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 8,
+ "stackHorizontalPadding": 20,
+ "stackPaddingRight": 20,
+ "stackLayoutVersion": 1,
+ "frameMaskDisabled": true,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2923
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2922
+ },
+ "position": "!"
+ },
+ "type": "INSTANCE",
+ "name": "Inner",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 293726,
+ "localID": 2920
+ },
+ "symbolOverrides": [],
+ "uniformScaleFactor": 0.5
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293726,
+ "localID": 2921
+ }
+ ]
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 1,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 20,
+ "y": 14
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 20,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 0.5,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 3,
+ "stackHorizontalPadding": 5,
+ "stackVerticalPadding": 2,
+ "stackPaddingRight": 5,
+ "stackPaddingBottom": 2,
+ "stackLayoutVersion": 1,
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 3,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ },
+ {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2925
+ },
+ "phase": "CREATED",
+ "parentIndex": {
+ "guid": {
+ "sessionID": 293726,
+ "localID": 2919
+ },
+ "position": "#"
+ },
+ "type": "INSTANCE",
+ "name": "Scaled outer",
+ "symbolData": {
+ "symbolID": {
+ "sessionID": 293726,
+ "localID": 2922
+ },
+ "symbolOverrides": [
+ {
+ "name": "Scaled outer",
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293726,
+ "localID": 2922
+ }
+ ]
+ },
+ "size": {
+ "x": 75,
+ "y": 14
+ },
+ "stackHorizontalPadding": 26
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293726,
+ "localID": 2923
+ }
+ ]
+ },
+ "stackHorizontalPadding": 14
+ }
+ ],
+ "uniformScaleFactor": 0.5
+ },
+ "derivedSymbolData": [
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293726,
+ "localID": 2923
+ }
+ ]
+ },
+ "size": {
+ "x": 14.5,
+ "y": 7
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 13,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ }
+ },
+ {
+ "guidPath": {
+ "guids": [
+ {
+ "sessionID": 293726,
+ "localID": 2923
+ },
+ {
+ "sessionID": 293726,
+ "localID": 2921
+ }
+ ]
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 7,
+ "m10": 0,
+ "m11": 1,
+ "m12": 1
+ },
+ "fillGeometry": [
+ {
+ "windingRule": "NONZERO",
+ "commandsBlob": 2,
+ "styleID": 0
+ }
+ ]
+ }
+ ],
+ "visible": true,
+ "opacity": 1,
+ "size": {
+ "x": 37.5,
+ "y": 7
+ },
+ "transform": {
+ "m00": 1,
+ "m01": 0,
+ "m02": 0,
+ "m10": 0,
+ "m11": 1,
+ "m12": 0
+ },
+ "strokeWeight": 0.5,
+ "strokeAlign": "INSIDE",
+ "strokeJoin": "MITER",
+ "fillPaints": [
+ {
+ "type": "SOLID",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "opacity": 1,
+ "visible": false,
+ "blendMode": "NORMAL",
+ "authoredColor": {
+ "space": "DEFAULT",
+ "c0": 1,
+ "c1": 1,
+ "c2": 1,
+ "c3": 1
+ }
+ }
+ ],
+ "bordersTakeSpace": true,
+ "stackMode": "HORIZONTAL",
+ "stackSpacing": 4,
+ "stackHorizontalPadding": 13,
+ "stackPaddingRight": 10,
+ "stackLayoutVersion": 1,
+ "frameMaskDisabled": true,
+ "derivedSymbolDataLayoutVersion": 3,
+ "stackCounterSizing": "RESIZE_TO_FIT_WITH_IMPLICIT_SIZE"
+ }
+ ],
+ "blobs": [
+ "AQAAAAAAAAAAAgAAoEEAAAAAAgAAoEEAAKBBAgAAAAAAAKBBAgAAAAAAAAAAAA==",
+ "AQAAAAAAAAAAAgAAIEEAAAAAAgAAIEEAACBBAgAAAAAAACBBAgAAAAAAAAAAAA==",
+ "AQAAAAAAAAAAAgAAoEAAAAAAAgAAoEAAAKBAAgAAAAAAAKBAAgAAAAAAAAAAAA=="
+ ]
+}
diff --git a/tests/fixtures/nested-owner-rescale-figma.png b/tests/fixtures/nested-owner-rescale-figma.png
new file mode 100644
index 000000000..9f271bbe1
Binary files /dev/null and b/tests/fixtures/nested-owner-rescale-figma.png differ
diff --git a/tests/helpers/fig/absolute-constraints.ts b/tests/helpers/fig/absolute-constraints.ts
new file mode 100644
index 000000000..e565ee1b5
--- /dev/null
+++ b/tests/helpers/fig/absolute-constraints.ts
@@ -0,0 +1,41 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+export function absoluteConstraintRecords(): NodeChange[] {
+ const guid = (localID: number) => ({ sessionID: 1, localID })
+ return [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'SYMBOL',
+ parentIndex: { guid: guid(1), position: '!' },
+ size: { x: 100, y: 80 },
+ stackMode: 'HORIZONTAL'
+ },
+ {
+ guid: guid(3),
+ type: 'RECTANGLE',
+ parentIndex: { guid: guid(2), position: '!' },
+ size: { x: 10, y: 60 },
+ transform: { m00: 1, m01: 0, m02: 80, m10: 0, m11: 1, m12: 10 },
+ stackPositioning: 'ABSOLUTE',
+ horizontalConstraint: 'MAX',
+ verticalConstraint: 'STRETCH',
+ fillPaints: [
+ {
+ type: 'SOLID',
+ color: { r: 217 / 255, g: 217 / 255, b: 217 / 255, a: 1 },
+ opacity: 1,
+ visible: true
+ }
+ ]
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ size: { x: 200, y: 120 },
+ symbolData: { symbolID: guid(2) }
+ }
+ ]
+}
diff --git a/tests/helpers/fig-fixtures.ts b/tests/helpers/fig/fixtures.ts
similarity index 91%
rename from tests/helpers/fig-fixtures.ts
rename to tests/helpers/fig/fixtures.ts
index 92320a0e8..4fa87ba2d 100644
--- a/tests/helpers/fig-fixtures.ts
+++ b/tests/helpers/fig/fixtures.ts
@@ -8,9 +8,9 @@ import {
type SceneNode
} from '@open-pencil/core'
-import { collectAllNodes } from './fig-traversal'
+import { collectAllNodes } from './traversal'
-export const FIXTURES = resolve(import.meta.dir, '../fixtures')
+export const FIXTURES = resolve(import.meta.dir, '../../fixtures')
export const VALID_NODE_TYPES = new Set<string>([
'CANVAS',
@@ -33,6 +33,11 @@ export const VALID_NODE_TYPES = new Set<string>([
'SHAPE_WITH_TEXT'
])
+/** Read a shared JSON fixture as data. */
+export function readFixtureJSON<T>(name: string): T {
+ return JSON.parse(readFileSync(resolve(FIXTURES, name), 'utf8')) as T
+}
+
export function readFixtureBytes(name: string): Uint8Array {
return readFileSync(resolve(FIXTURES, name))
}
diff --git a/tests/helpers/fig/guid.ts b/tests/helpers/fig/guid.ts
new file mode 100644
index 000000000..559f72914
--- /dev/null
+++ b/tests/helpers/fig/guid.ts
@@ -0,0 +1,5 @@
+import type { GUID } from '@open-pencil/kiwi/fig/codec'
+
+export function guid(localID: number, sessionID = 1): GUID {
+ return { sessionID, localID }
+}
diff --git a/tests/helpers/fig/nested-binding.ts b/tests/helpers/fig/nested-binding.ts
new file mode 100644
index 000000000..456091efb
--- /dev/null
+++ b/tests/helpers/fig/nested-binding.ts
@@ -0,0 +1,18 @@
+import type { SymbolData } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+import fixture from '#tests/fixtures/nested-binding-ownership-records.json' with { type: 'json' }
+import { expectDefined } from '#tests/helpers/assert'
+
+/** Remove only the placed owner's declaration, retaining the saved inherited expression. */
+export function inheritedNestedBindingRecords(): NodeChange[] {
+ const changes = structuredClone(fixture.nodeChanges) as NodeChange[]
+ const owner = expectDefined(
+ changes.find((node) => node.guid?.sessionID === 293733 && node.guid.localID === 8),
+ 'captured owner'
+ )
+ for (const override of (owner.symbolData as SymbolData).symbolOverrides ?? []) {
+ Reflect.deleteProperty(override, 'parameterConsumptionMap')
+ }
+ return changes
+}
diff --git a/tests/helpers/fig/traversal.ts b/tests/helpers/fig/traversal.ts
new file mode 100644
index 000000000..53bfe8fd9
--- /dev/null
+++ b/tests/helpers/fig/traversal.ts
@@ -0,0 +1,52 @@
+import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/core'
+
+export function collectAllNodes(graph: SceneGraph): SceneNode[] {
+ const all: SceneNode[] = []
+ function walk(id: string) {
+ const node = graph.getNode(id)
+ if (!node) return
+ all.push(node)
+ for (const child of graph.getChildren(id)) {
+ walk(child.id)
+ }
+ }
+ for (const page of graph.getPages()) {
+ for (const child of graph.getChildren(page.id)) {
+ walk(child.id)
+ }
+ }
+ return all
+}
+
+export function countByType(nodes: SceneNode[]): Map<NodeType, number> {
+ const counts = new Map<NodeType, number>()
+ for (const node of nodes) {
+ counts.set(node.type, (counts.get(node.type) ?? 0) + 1)
+ }
+ return counts
+}
+
+export function childNamed(
+ graph: SceneGraph,
+ parent: SceneNode | undefined,
+ name: string
+): SceneNode | undefined {
+ return parent ? graph.getChildren(parent.id).find((node) => node.name === name) : undefined
+}
+
+export function childMatching(
+ graph: SceneGraph,
+ parent: SceneNode | undefined,
+ predicate: (node: SceneNode) => boolean
+): SceneNode | undefined {
+ return parent ? graph.getChildren(parent.id).find(predicate) : undefined
+}
+
+export function previewChild(
+ graph: SceneGraph,
+ nodes: SceneNode[],
+ name: string
+): SceneNode | undefined {
+ const preview = nodes.find((node) => node.name === 'Preview Thumbnail')
+ return childNamed(graph, preview, name)
+}
diff --git a/tests/integration/fig-transfer-plan.test.ts b/tests/integration/fig-transfer-plan.test.ts
new file mode 100644
index 000000000..89f439fe5
--- /dev/null
+++ b/tests/integration/fig-transfer-plan.test.ts
@@ -0,0 +1,40 @@
+import { expect, test } from 'bun:test'
+
+import { materializeFigFragment } from '@open-pencil/fig'
+import { prepareGraphTransfer, applyGraphTransfer, SceneGraph } from '@open-pencil/scene-graph'
+
+import { readFixtureJSON } from '#tests/helpers/fig/fixtures'
+
+const fixture = readFixtureJSON<Record<string, unknown>[]>('nested-binding-ownership-records.json')
+
+test('prepares a real FIG fragment without mutating the destination', () => {
+ const fragment = materializeFigFragment(
+ fixture.nodeChanges,
+ fixture.blobs.map((value) => Uint8Array.fromBase64(value))
+ )
+ const target = new SceneGraph()
+ const before = [...target.nodes.keys()]
+ const plan = prepareGraphTransfer({
+ source: fragment.graph,
+ rootIds: fragment.rootIds,
+ dependencyPageIds: fragment.dependencyPageIds,
+ target,
+ parentId: target.getPages()[0].id
+ })
+ expect([...target.nodes.keys()]).toEqual(before)
+ expect(plan.rootIds).toHaveLength(fragment.rootIds.length)
+ expect(plan.nodes.length).toBeGreaterThan(plan.rootIds.length)
+ const ids = new Set(plan.nodes.map((node) => node.id))
+ for (const node of plan.nodes)
+ if (node.props.componentId) expect(ids.has(node.props.componentId)).toBe(true)
+ expect(plan.variables.length).toBeGreaterThan(0)
+ applyGraphTransfer(target, plan)
+ expect(plan.rootIds.every((id) => target.getNode(id))).toBe(true)
+ for (const node of plan.nodes) {
+ const inserted = target.getNode(node.id)
+ expect(inserted?.parentId).toBe(node.parentId)
+ if (inserted?.componentId) expect(target.getNode(inserted.componentId)).toBeDefined()
+ }
+ expect(target.variables.size).toBe(plan.variables.length)
+ expect(target.activeMode).toEqual(plan.activeModes)
+})
diff --git a/tools/checks/architecture/src/steiger-rules/support.ts b/tools/checks/architecture/src/steiger-rules/support.ts
index 10ae5836b..61e9e3da6 100644
--- a/tools/checks/architecture/src/steiger-rules/support.ts
+++ b/tools/checks/architecture/src/steiger-rules/support.ts
@@ -43,13 +43,19 @@ export const ROOT_MARKDOWN_ALLOWLIST = new Set([
])
export const PACKAGE_ALIASES: Record<string, string> = {
'#core/': 'packages/core/src/',
+ '#fig/': 'packages/fig/src/',
+ '#fig-tests/': 'packages/fig/tests/',
'#vue/': 'packages/vue/src/',
'#cli/': 'packages/cli/src/',
'#mcp/': 'packages/mcp/src/'
}
export const PACKAGE_ALIAS_OWNERS: Record<string, string> = {
- '#core/': 'packages/core/src/',
+ // A package's own tests mirror its source tree, so they address it by alias rather than
+ // drilling up through ../../src.
+ '#core/': 'packages/core/',
+ '#fig/': 'packages/fig/',
+ '#fig-tests/': 'packages/fig/tests/',
'#vue/': 'packages/vue/src/',
'#cli/': 'packages/cli/src/',
'#mcp/': 'packages/mcp/src/'
diff --git a/tools/checks/package-quality/src/smoke/scenarios.ts b/tools/checks/package-quality/src/smoke/scenarios.ts
index faa2bf70c..b1c2fa7c9 100644
--- a/tools/checks/package-quality/src/smoke/scenarios.ts
+++ b/tools/checks/package-quality/src/smoke/scenarios.ts
@@ -14,7 +14,7 @@ export const runtimeScenarios: RuntimeScenario[] = [
},
{
name: 'FIG archive API',
- code: "const { FIG_PACKAGE_STATUS, effectiveFigmaRawNodeFields, parseFigBuffer, writeFigArchive, readFigContainer, writeFigContainer } = await import('@open-pencil/fig'); if (FIG_PACKAGE_STATUS !== 'archive-api' || typeof effectiveFigmaRawNodeFields !== 'function' || typeof parseFigBuffer !== 'function' || typeof writeFigArchive !== 'function') throw new Error('Fig package status smoke failed'); const document = readFigContainer(writeFigContainer({ schemaDeflated: new Uint8Array([1]), dataRaw: new Uint8Array([2]) })); if (document.dataRaw[0] !== 2) throw new Error('Fig container smoke failed')"
+ code: "const { FIG_PACKAGE_STATUS, effectiveFigmaRawNodeFields, parseFigBuffer, writeFigArchive, readFigContainer, writeFigContainer } = await import('@open-pencil/fig'); if (FIG_PACKAGE_STATUS !== 'document-reader' || typeof effectiveFigmaRawNodeFields !== 'function' || typeof parseFigBuffer !== 'function' || typeof writeFigArchive !== 'function') throw new Error('Fig package status smoke failed'); const document = readFigContainer(writeFigContainer({ schemaDeflated: new Uint8Array([1]), dataRaw: new Uint8Array([2]) })); if (document.dataRaw[0] !== 2) throw new Error('Fig container smoke failed')"
},
{
name: 'FIG NodeChange API',
@@ -22,7 +22,7 @@ export const runtimeScenarios: RuntimeScenario[] = [
},
{
name: 'FIG instance override API',
- code: "const { populateAndApplyOverrides } = await import('@open-pencil/fig/instance-overrides'); if (typeof populateAndApplyOverrides !== 'function') throw new Error('Fig instance override subpath failed')"
+ code: "const { interpretInstance, materializeInstance } = await import('@open-pencil/fig/instance-overrides'); if (typeof interpretInstance !== 'function' || typeof materializeInstance !== 'function') throw new Error('Fig instance override subpath failed')"
},
{
name: 'SceneGraph package',
diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txt
index e22289b83..657996b79 100644
--- a/tools/checks/test-homes/engine-baseline.txt
+++ b/tools/checks/test-homes/engine-baseline.txt
@@ -271,6 +271,7 @@ tests/engine/io/fig/roundtrip/glyph-blob.test.ts
tests/engine/io/fig/roundtrip/group.test.ts
tests/engine/io/fig/roundtrip/source-metadata.test.ts
tests/engine/io/fig/roundtrip/variables.test.ts
+tests/engine/io/fig/roundtrip/verifier-contracts.test.ts
tests/engine/io/fig/roundtrip/verifiers.test.ts
tests/engine/io/fig/thumbnail-page.test.ts
tests/engine/io/fig/thumbnail-range.test.ts
diff --git a/tools/generate/visual-oracles/package.json b/tools/generate/visual-oracles/package.json
index 4812b8c53..6b1e005d7 100644
--- a/tools/generate/visual-oracles/package.json
+++ b/tools/generate/visual-oracles/package.json
@@ -3,7 +3,11 @@
"private": true,
"type": "module",
"imports": {
- "#visual/manifest": "./src/document/manifest.ts"
+ "#visual/manifest": "./src/document/manifest.ts",
+ "#visual/capture-scene": "./src/document/capture-scene.ts",
+ "#visual/path-diagnostics": "./src/document/path-diagnostics.ts",
+ "#visual/scene-oracle": "./src/document/scene-oracle.ts",
+ "#visual/document-capture": "./src/document/document-capture.ts"
},
"scripts": {
"test": "bun test tests"
diff --git a/tools/generate/visual-oracles/src/cli.ts b/tools/generate/visual-oracles/src/cli.ts
index a5072532e..e26849ec4 100644
--- a/tools/generate/visual-oracles/src/cli.ts
+++ b/tools/generate/visual-oracles/src/cli.ts
@@ -20,6 +20,16 @@ const main = defineCommand({
'tools/generate/visual-oracles/src/operations/export-fixtures.ts'
),
analyze: () => import('./commands/analyze').then((module) => module.default),
+ 'activate-tab': operationCommand(
+ 'activate-tab',
+ 'Bring a Figma desktop tab to the front by title before an oracle capture',
+ 'tools/generate/visual-oracles/src/operations/activate-tab.ts'
+ ),
+ 'interpret-instance': operationCommand(
+ 'interpret-instance',
+ 'Render an interpreted instance through Skia and compare it with Figma',
+ 'tools/generate/visual-oracles/src/operations/interpret-instance.ts'
+ ),
'update-report': operationCommand(
'update-report',
'Update the visual comparison report',
diff --git a/tools/generate/visual-oracles/src/commands/compare.ts b/tools/generate/visual-oracles/src/commands/compare.ts
index 333e5202f..1a3f2e10c 100644
--- a/tools/generate/visual-oracles/src/commands/compare.ts
+++ b/tools/generate/visual-oracles/src/commands/compare.ts
@@ -8,12 +8,22 @@ export default defineCommand({
node: operationCommand(
'node',
'Compare one Figma node or clipboard selection',
- 'tools/generate/visual-oracles/src/operations/compare-node.ts'
+ 'tools/generate/visual-oracles/src/operations/compare/node.ts'
),
document: operationCommand(
'document',
'Compare exact imported-document targets from a manifest',
- 'tools/generate/visual-oracles/src/operations/compare-document.ts'
+ 'tools/generate/visual-oracles/src/operations/compare/document.ts'
+ ),
+ digest: operationCommand(
+ 'digest',
+ 'Capture every page a reader produces, and diff it against an earlier capture',
+ 'tools/generate/visual-oracles/src/operations/compare/digest.ts'
+ ),
+ 'interpreted-document': operationCommand(
+ 'interpreted-document',
+ 'Compare an interpreted archive with the same document opened in Figma',
+ 'tools/generate/visual-oracles/src/operations/compare/interpreted-document.ts'
)
}
})
diff --git a/tools/generate/visual-oracles/src/document/capture-scene.ts b/tools/generate/visual-oracles/src/document/capture-scene.ts
new file mode 100644
index 000000000..4d52249a5
--- /dev/null
+++ b/tools/generate/visual-oracles/src/document/capture-scene.ts
@@ -0,0 +1,85 @@
+import type { Color, Fill, SceneGraph, Stroke } from '@open-pencil/scene-graph'
+import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+
+import type { SceneOracleNode } from './scene-oracle'
+
+/**
+ * Drawing takes a solid paint's alpha from its opacity, so that is the transparency a
+ * capture has to record; Figma reports the same number the same way.
+ */
+function solid(color: Color, opacity: number): string {
+ const rgb = [color.r, color.g, color.b].map((value) => Math.round(value * 255)).join(',')
+ return `SOLID ${rgb} ${Math.round(opacity * 100)}%`
+}
+
+function fillPaints(fills: readonly Fill[]): string[] {
+ return fills
+ .filter((fill) => fill.visible !== false)
+ .map((fill) => (fill.type === 'SOLID' ? solid(fill.color, fill.opacity) : fill.type))
+}
+
+/** A Scene Graph stroke is always one solid color; Figma reports it as a SOLID paint. */
+function strokePaints(strokes: readonly Stroke[]): string[] {
+ return strokes
+ .filter((stroke) => stroke.visible !== false)
+ .map((stroke) => solid(stroke.color, stroke.opacity))
+}
+
+export function captureGraphOracle(
+ graph: SceneGraph,
+ rootId: string,
+ sources: ReadonlyMap<string, string>
+): SceneOracleNode[] {
+ const sourceIds = new Map([...sources].map(([source, id]) => [id, source]))
+ const nodes: SceneOracleNode[] = []
+ const visit = (id: string, path: number[]): void => {
+ const node = graph.getNode(id)
+ if (!node) throw new Error(`Missing graph node ${id}`)
+ const world = getWorldMatrix(node, graph)
+ nodes.push({
+ path,
+ type: node.type,
+ name: node.name,
+ visible: node.visible,
+ x: world[2],
+ y: world[5],
+ width: node.width,
+ height: node.height,
+ text: node.type === 'TEXT' ? node.text : null,
+ main: node.type === 'INSTANCE' ? (sourceIds.get(node.componentId ?? '') ?? null) : null,
+ fills: fillPaints(node.fills),
+ strokes: strokePaints(node.strokes)
+ })
+ graph.getChildren(id).forEach((child, index) => visit(child.id, [...path, index]))
+ }
+ visit(rootId, [])
+ return nodes
+}
+
+export function figmaOracleScript(fileKey: string, rootId: string): string {
+ return `
+if (figma.fileKey !== ${JSON.stringify(fileKey)}) throw new Error('Wrong Figma document');
+const root = await figma.getNodeByIdAsync(${JSON.stringify(rootId)});
+if (!root) throw new Error('Missing Figma root');
+figma.skipInvisibleInstanceChildren = false;
+const nodes = [];
+function paints(list) {
+ if (!Array.isArray(list)) return [];
+ return list.filter((paint) => paint.visible !== false).map((paint) => {
+ if (paint.type !== 'SOLID') return paint.type;
+ const rgb = [paint.color.r, paint.color.g, paint.color.b].map((v) => Math.round(v * 255)).join(',');
+ return 'SOLID ' + rgb + ' ' + Math.round((paint.opacity ?? 1) * 100) + '%';
+ });
+}
+function visit(node, path) {
+ nodes.push({path, type: node.type, name: node.name, visible: node.visible,
+ x: node.absoluteTransform[0][2], y: node.absoluteTransform[1][2],
+ width: node.width, height: node.height,
+ text: node.type === 'TEXT' ? node.characters : null,
+ main: node.type === 'INSTANCE' ? node.mainComponent?.id ?? null : null,
+ fills: paints(node.fills), strokes: paints(node.strokes)});
+ if ('children' in node) node.children.forEach((child, index) => visit(child, [...path, index]));
+}
+visit(root, []);
+return {fileKey: figma.fileKey, rootId: root.id, nodes};`
+}
diff --git a/tools/generate/visual-oracles/src/document/document-capture.ts b/tools/generate/visual-oracles/src/document/document-capture.ts
new file mode 100644
index 000000000..64197ee5d
--- /dev/null
+++ b/tools/generate/visual-oracles/src/document/document-capture.ts
@@ -0,0 +1,21 @@
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { captureGraphOracle } from './capture-scene'
+import type { SceneOracleNode } from './scene-oracle'
+
+/**
+ * Capture every page of a graph, not one frame of it. Page order is the archive's, and
+ * each page's nodes keep their own path prefixed by that page, so two captures of the
+ * same archive line up node for node.
+ */
+export function captureDocumentOracle(
+ graph: SceneGraph,
+ sources: ReadonlyMap<string, string>
+): SceneOracleNode[] {
+ return graph.getPages().flatMap((page, index) =>
+ captureGraphOracle(graph, page.id, sources).map((node) => ({
+ ...node,
+ path: [index, ...node.path]
+ }))
+ )
+}
diff --git a/tools/generate/visual-oracles/src/document/path-diagnostics.ts b/tools/generate/visual-oracles/src/document/path-diagnostics.ts
new file mode 100644
index 000000000..23d3c360a
--- /dev/null
+++ b/tools/generate/visual-oracles/src/document/path-diagnostics.ts
@@ -0,0 +1,24 @@
+import type { InstancePathDiagnostic } from '@open-pencil/fig/instance-overrides'
+
+export interface CountedPathDiagnostic extends InstancePathDiagnostic {
+ occurrences: number
+}
+
+/** Group reporting only; repeated evaluations are not distinct source failures. */
+export function summarizePathDiagnostics(
+ diagnostics: readonly InstancePathDiagnostic[]
+): CountedPathDiagnostic[] {
+ const groups = new Map<string, CountedPathDiagnostic>()
+ for (const diagnostic of diagnostics) {
+ const key = JSON.stringify([
+ diagnostic.ownerId,
+ diagnostic.mainComponentId,
+ diagnostic.path,
+ diagnostic.reason
+ ])
+ const previous = groups.get(key)
+ if (previous) previous.occurrences++
+ else groups.set(key, { ...structuredClone(diagnostic), occurrences: 1 })
+ }
+ return [...groups.values()].sort((a, b) => b.occurrences - a.occurrences)
+}
diff --git a/tools/generate/visual-oracles/src/document/scene-oracle.ts b/tools/generate/visual-oracles/src/document/scene-oracle.ts
new file mode 100644
index 000000000..4bd2bb551
--- /dev/null
+++ b/tools/generate/visual-oracles/src/document/scene-oracle.ts
@@ -0,0 +1,121 @@
+export interface SceneOracleNode {
+ path: number[]
+ type: string
+ name: string
+ visible: boolean
+ x: number
+ y: number
+ width: number
+ height: number
+ text: string | null
+ main: string | null
+ /** Visible paints as `TYPE r,g,b a%`, so a transparency difference is legible. */
+ fills: string[]
+ strokes: string[]
+}
+
+export interface SceneOracleDifference {
+ path: number[]
+ category:
+ | 'structure'
+ | 'semantic'
+ | 'visible-geometry'
+ | 'hidden-geometry'
+ | 'visible-paint'
+ | 'hidden-paint'
+ field: string
+ expected: unknown
+ actual: unknown
+}
+
+type Push = (
+ field: string,
+ category: SceneOracleDifference['category'],
+ expected: unknown,
+ actual: unknown
+) => void
+
+/** A layer nobody sees, either because it is hidden or because an ancestor is. */
+function hidden(node: SceneOracleNode, nodes: ReadonlyMap<string, SceneOracleNode>): boolean {
+ for (let depth = 0; depth <= node.path.length; depth++) {
+ if (nodes.get(JSON.stringify(node.path.slice(0, depth)))?.visible === false) return true
+ }
+ return false
+}
+
+/** Rounded rectangles share Figma's RECTANGLE type. */
+function compareIdentity(a: SceneOracleNode, b: SceneOracleNode, push: Push): void {
+ for (const field of ['type', 'name', 'visible', 'text', 'main'] as const) {
+ const normalize = (value: unknown) =>
+ field === 'type' && value === 'ROUNDED_RECTANGLE' ? 'RECTANGLE' : value
+ if (normalize(a[field]) !== normalize(b[field])) push(field, 'semantic', a[field], b[field])
+ }
+}
+
+function comparePaint(a: SceneOracleNode, b: SceneOracleNode, isHidden: boolean, push: Push): void {
+ for (const field of ['fills', 'strokes'] as const) {
+ if (a[field].join(' | ') !== b[field].join(' | '))
+ push(field, isHidden ? 'hidden-paint' : 'visible-paint', a[field], b[field])
+ }
+}
+
+function compareGeometry(
+ a: SceneOracleNode,
+ b: SceneOracleNode,
+ isHidden: boolean,
+ tolerance: number,
+ push: Push
+): void {
+ const category = isHidden ? 'hidden-geometry' : 'visible-geometry'
+ for (const field of ['x', 'y', 'width', 'height'] as const) {
+ if (
+ !Number.isFinite(a[field]) ||
+ !Number.isFinite(b[field]) ||
+ Math.abs(a[field] - b[field]) > tolerance
+ ) {
+ push(field, category, a[field], b[field])
+ }
+ }
+}
+
+/** Compare complete ordered trees. */
+export function compareSceneOracle(
+ expected: readonly SceneOracleNode[],
+ actual: readonly SceneOracleNode[],
+ tolerance = 0.01
+): SceneOracleDifference[] {
+ const index = (nodes: readonly SceneOracleNode[]) => {
+ const result = new Map<string, SceneOracleNode>()
+ for (const node of nodes) {
+ const key = JSON.stringify(node.path)
+ if (result.has(key)) throw new Error(`Duplicate occurrence path ${key}`)
+ result.set(key, node)
+ }
+ return result
+ }
+ const left = index(expected)
+ const right = index(actual)
+ const differences: SceneOracleDifference[] = []
+ for (const key of new Set([...left.keys(), ...right.keys()])) {
+ const a = left.get(key)
+ const b = right.get(key)
+ if (!a || !b) {
+ differences.push({
+ path: (a ?? b)?.path ?? [],
+ category: 'structure',
+ field: 'node',
+ expected: a ?? null,
+ actual: b ?? null
+ })
+ continue
+ }
+ const push: Push = (field, category, expected, actual) => {
+ differences.push({ path: a.path, field, category, expected, actual })
+ }
+ const isHidden = hidden(a, left) && hidden(b, right)
+ compareIdentity(a, b, push)
+ comparePaint(a, b, isHidden, push)
+ compareGeometry(a, b, isHidden, tolerance, push)
+ }
+ return differences
+}
diff --git a/tools/generate/visual-oracles/src/operations/activate-tab.ts b/tools/generate/visual-oracles/src/operations/activate-tab.ts
new file mode 100644
index 000000000..a3b48207d
--- /dev/null
+++ b/tools/generate/visual-oracles/src/operations/activate-tab.ts
@@ -0,0 +1,54 @@
+import { parseArgs } from 'node:util'
+
+/**
+ * Bring a Figma desktop tab to the front by its title. `figma-use` and the oracle captures
+ * target the active document, so a reopened export must be the visible tab first. The tab
+ * strip lives in the desktop shell page, reachable over the same DevTools port figma-use uses.
+ */
+const { values } = parseArgs({
+ options: { title: { type: 'string' }, port: { type: 'string', default: '9222' } }
+})
+if (!values.title) throw new Error('Required: --title <tab title> [--port 9222]')
+
+interface Target {
+ type: string
+ url: string
+ webSocketDebuggerUrl: string
+}
+const targets = (await (
+ await fetch(`http://localhost:${values.port}/json/list`)
+).json()) as Target[]
+const shell = targets.find((t) => t.type === 'page' && t.url.endsWith('shell.html'))
+if (!shell)
+ throw new Error('Figma desktop shell page not found; is Figma running with remote debugging?')
+
+const socket = new WebSocket(shell.webSocketDebuggerUrl)
+await new Promise<void>((resolve, reject) => {
+ socket.onopen = () => resolve()
+ socket.onerror = () => reject(new Error('Could not connect to the Figma shell'))
+})
+const expression = `(() => {
+ const tabs = [...document.querySelectorAll('[role="tab"]')]
+ const tab = tabs.find((t) => (t.getAttribute('aria-label') || '') === ${JSON.stringify(values.title)})
+ if (!tab) return tabs.map((t) => t.getAttribute('aria-label'))
+ tab.click()
+ return true
+})()`
+socket.send(
+ JSON.stringify({ id: 1, method: 'Runtime.evaluate', params: { expression, returnByValue: true } })
+)
+const result = await new Promise<unknown>((resolve) => {
+ socket.onmessage = (message) => {
+ const payload = JSON.parse(String(message.data)) as {
+ result?: { result?: { value?: unknown } }
+ }
+ resolve(payload.result?.result?.value)
+ }
+})
+socket.close()
+if (result !== true)
+ throw new Error(`No tab titled ${values.title}; open tabs: ${JSON.stringify(result)}`)
+await new Promise<void>((resolve) => {
+ setTimeout(resolve, 1500)
+})
+console.log(`activated ${values.title}`)
diff --git a/tools/generate/visual-oracles/src/operations/compare/digest.ts b/tools/generate/visual-oracles/src/operations/compare/digest.ts
new file mode 100644
index 000000000..1df0bdd64
--- /dev/null
+++ b/tools/generate/visual-oracles/src/operations/compare/digest.ts
@@ -0,0 +1,55 @@
+#!/usr/bin/env bun
+import { parseArgs } from 'node:util'
+
+import { captureDocumentOracle } from '#visual/document-capture'
+import { compareSceneOracle, type SceneOracleNode } from '#visual/scene-oracle'
+
+import { materializeFigArchive } from '@open-pencil/fig'
+
+const { values } = parseArgs({
+ options: {
+ file: { type: 'string' },
+ out: { type: 'string' },
+ baseline: { type: 'string' },
+ show: { type: 'string', default: '20' }
+ }
+})
+if (!values.file) throw new Error('Required: --file FILE [--out FILE] [--baseline FILE]')
+
+// A reader change often moves these counts too, so report them beside the node capture.
+const unresolved = { assignment: 0, property: 0, binding: 0, component: 0 }
+const { graph, sources } = materializeFigArchive(await Bun.file(values.file).arrayBuffer(), {
+ derivedBounds: true,
+ onUnresolvedAssignment: () => unresolved.assignment++,
+ onUnresolvedProperty: () => unresolved.property++,
+ onUnresolvedBinding: () => unresolved.binding++,
+ onMissingComponent: () => unresolved.component++
+})
+const nodes = captureDocumentOracle(graph, sources)
+if (values.out) await Bun.write(values.out, JSON.stringify(nodes))
+
+if (!values.baseline) {
+ console.log(
+ JSON.stringify({ nodes: nodes.length, pages: graph.getPages().length, unresolved }, null, 2)
+ )
+} else {
+ const baseline = (await Bun.file(values.baseline).json()) as SceneOracleNode[]
+ const differences = compareSceneOracle(baseline, nodes)
+ const counts: Record<string, number> = {}
+ for (const difference of differences)
+ counts[difference.category] = (counts[difference.category] ?? 0) + 1
+ console.log(
+ JSON.stringify(
+ { baselineNodes: baseline.length, nodes: nodes.length, differences: counts, unresolved },
+ null,
+ 2
+ )
+ )
+ for (const difference of differences.slice(0, Number(values.show))) {
+ const { path, field, category, expected, actual } = difference
+ console.log(
+ ` ${category} ${path.join(',')} ${field}: ${JSON.stringify(expected)} -> ${JSON.stringify(actual)}`
+ )
+ }
+ if (differences.length) process.exitCode = 1
+}
diff --git a/tools/generate/visual-oracles/src/operations/compare-document.ts b/tools/generate/visual-oracles/src/operations/compare/document.ts
similarity index 99%
rename from tools/generate/visual-oracles/src/operations/compare-document.ts
rename to tools/generate/visual-oracles/src/operations/compare/document.ts
index 7929ec023..7753ba926 100644
--- a/tools/generate/visual-oracles/src/operations/compare-document.ts
+++ b/tools/generate/visual-oracles/src/operations/compare/document.ts
@@ -4,11 +4,10 @@ import { mkdirSync } from 'node:fs'
import { basename, resolve } from 'node:path'
import { parseArgs } from 'node:util'
+import { readVisualOracleManifest, type VisualOracleTarget } from '#visual/manifest'
import { chromium, type Page } from '@playwright/test'
import { $ } from 'bun'
-import { readVisualOracleManifest, type VisualOracleTarget } from '../document/manifest'
-
const { values, positionals } = parseArgs({
allowPositionals: true,
options: {
diff --git a/tools/generate/visual-oracles/src/operations/compare/interpreted-document.ts b/tools/generate/visual-oracles/src/operations/compare/interpreted-document.ts
new file mode 100644
index 000000000..e305e7c66
--- /dev/null
+++ b/tools/generate/visual-oracles/src/operations/compare/interpreted-document.ts
@@ -0,0 +1,80 @@
+#!/usr/bin/env bun
+import { mkdir } from 'node:fs/promises'
+import { join } from 'node:path'
+import { parseArgs } from 'node:util'
+
+import { captureGraphOracle, figmaOracleScript } from '#visual/capture-scene'
+import { summarizePathDiagnostics } from '#visual/path-diagnostics'
+import { compareSceneOracle, type SceneOracleNode } from '#visual/scene-oracle'
+import { $ } from 'bun'
+
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { InstancePathDiagnostic } from '@open-pencil/fig/instance-overrides'
+
+const { values } = parseArgs({
+ options: {
+ file: { type: 'string' },
+ node: { type: 'string' },
+ 'figma-key': { type: 'string' },
+ 'allow-partial-assignments': { type: 'boolean', default: false },
+ output: { type: 'string' }
+ }
+})
+if (!values.file || !values.node || !values['figma-key'] || !values.output) {
+ throw new Error('Required: --file FILE --node ID --figma-key KEY --output DIR')
+}
+await mkdir(values.output, { recursive: true })
+const script = figmaOracleScript(values['figma-key'], values.node)
+const capture = await $`figma-use eval ${script} --json`.quiet().text()
+const oracle = JSON.parse(capture) as { fileKey: string; rootId: string; nodes: SceneOracleNode[] }
+if (
+ oracle.fileKey !== values['figma-key'] ||
+ oracle.rootId !== values.node ||
+ !Array.isArray(oracle.nodes)
+) {
+ throw new Error('Invalid oracle capture identity')
+}
+const { nodeChanges, blobs, images } = parseFigBuffer(await Bun.file(values.file).arrayBuffer())
+const diagnostics: InstancePathDiagnostic[] = []
+const assignmentDiagnostics: unknown[] = []
+const { graph, sources } = materializeDocument(nodeChanges, blobs, {
+ images: new Map(images),
+ derivedBounds: true,
+ onUnresolvedAssignment: values['allow-partial-assignments']
+ ? (diagnostic) => assignmentDiagnostics.push(diagnostic)
+ : undefined,
+ onUnresolvedProperty: (diagnostic) => diagnostics.push(diagnostic)
+})
+const root = sources.get(values.node)
+if (!root) throw new Error('Missing assembled root')
+const actual = captureGraphOracle(graph, root, sources)
+const differences = compareSceneOracle(oracle.nodes, actual)
+const groupedDiagnostics = summarizePathDiagnostics(diagnostics)
+for (const [name, value] of Object.entries({
+ oracle,
+ actual,
+ differences,
+ diagnostics,
+ assignmentDiagnostics,
+ groupedDiagnostics
+})) {
+ await Bun.write(join(values.output, `${name}.json`), JSON.stringify(value, null, 2))
+}
+const counts: Record<string, number> = {}
+for (const difference of differences)
+ counts[difference.category] = (counts[difference.category] ?? 0) + 1
+console.log(
+ JSON.stringify(
+ {
+ partialAssignmentCallbacks: assignmentDiagnostics.length,
+ expectedNodes: oracle.nodes.length,
+ actualNodes: actual.length,
+ differences: counts,
+ uniqueUnresolvedPaths: groupedDiagnostics.length,
+ unresolvedCallbacks: diagnostics.length
+ },
+ null,
+ 2
+ )
+)
+if (differences.length || assignmentDiagnostics.length) process.exitCode = 1
diff --git a/tools/generate/visual-oracles/src/operations/compare-node.ts b/tools/generate/visual-oracles/src/operations/compare/node.ts
similarity index 100%
rename from tools/generate/visual-oracles/src/operations/compare-node.ts
rename to tools/generate/visual-oracles/src/operations/compare/node.ts
diff --git a/tools/generate/visual-oracles/src/operations/interpret-instance.ts b/tools/generate/visual-oracles/src/operations/interpret-instance.ts
new file mode 100644
index 000000000..4b52074de
--- /dev/null
+++ b/tools/generate/visual-oracles/src/operations/interpret-instance.ts
@@ -0,0 +1,105 @@
+import { mkdir } from 'node:fs/promises'
+import { join } from 'node:path'
+import { parseArgs } from 'node:util'
+
+import { $ } from 'bun'
+import { toUint8Array } from 'js-base64'
+
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit, renderNodesToImage } from '@open-pencil/core/io'
+import { prepareGraphFonts } from '@open-pencil/core/text'
+import { parseFigBuffer } from '@open-pencil/fig'
+import {
+ interpretInstance,
+ materializeInstance,
+ type InstanceOccurrence,
+ type InstancePathDiagnostic
+} from '@open-pencil/fig/instance-overrides'
+import { nodeChangeToProps } from '@open-pencil/fig/node-change'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Render the interpreter output directly. No legacy import, export/reimport, or layout pass.
+const { values } = parseArgs({
+ options: {
+ file: { type: 'string' },
+ node: { type: 'string' },
+ output: { type: 'string' },
+ scale: { type: 'string', default: '2' },
+ 'figma-key': { type: 'string' }
+ }
+})
+if (!values.file || !values.node || !values.output)
+ throw new Error('Required: --file --node --output')
+const scale = Number(values.scale)
+if (!Number.isFinite(scale) || scale <= 0 || scale > 8)
+ throw new Error('Scale must be > 0 and <= 8')
+await mkdir(values.output, { recursive: true })
+const { nodeChanges, blobs, images } = parseFigBuffer(await Bun.file(values.file).arrayBuffer())
+const diagnostics: InstancePathDiagnostic[] = []
+const occurrence = interpretInstance(nodeChanges, values.node, {
+ derivedBounds: true,
+ onUnresolvedProperty: (d) => diagnostics.push(d)
+})
+const graph = new SceneGraph()
+const page = graph.getPages()[0]
+for (const [hash, bytes] of images) graph.images.set(hash, bytes)
+const sources = new Map(
+ nodeChanges.flatMap((node) => (node.guid ? [[guidToString(node.guid), node] as const] : []))
+)
+const components = new Map<string, string>()
+function prepare(node: InstanceOccurrence): void {
+ if (node.mainComponentId && !components.has(node.mainComponentId)) {
+ const source = sources.get(node.mainComponentId)
+ if (!source) throw new Error('Missing source component')
+ const { nodeType, ...props } = nodeChangeToProps(source, blobs)
+ if (nodeType !== 'COMPONENT') throw new Error('Expected terminal component')
+ components.set(node.mainComponentId, graph.createNode('COMPONENT', page.id, props).id)
+ }
+ node.children.forEach(prepare)
+}
+prepare(occurrence)
+const result = materializeInstance(graph, page.id, occurrence, components, { blobs })
+const bounds = () => [...result.nodes.values()].map((n) => [n.id, n.x, n.y, n.width, n.height])
+const before = JSON.stringify(bounds())
+const ck = await initCanvasKit()
+const surface = ck.MakeSurface(1, 1)
+if (!surface) throw new Error('No Skia surface')
+const renderer = new SkiaRenderer(ck, surface)
+try {
+ await renderer.loadFonts()
+ const fonts = await prepareGraphFonts(graph, [result.root.id])
+ if (!fonts.faithful) throw new Error(`Missing fonts: ${JSON.stringify(fonts)}`)
+ const png = renderNodesToImage(ck, renderer, graph, page.id, [result.root.id], {
+ scale,
+ format: 'PNG',
+ trimTransparent: false
+ })
+ if (!png) throw new Error('No rendered image')
+ if (before !== JSON.stringify(bounds()))
+ throw new Error('Render preparation changed occurrence bounds')
+ await Bun.write(join(values.output, 'interpreted.png'), png)
+ await Bun.write(
+ join(values.output, 'report.json'),
+ JSON.stringify(
+ { file: values.file, node: values.node, scale, fonts, diagnostics, bounds: bounds() },
+ null,
+ 2
+ )
+ )
+} finally {
+ renderer.destroy()
+}
+if (values['figma-key']) {
+ const code = `if(figma.fileKey!==${JSON.stringify(values['figma-key'])})throw Error("Wrong Figma document");const n=await figma.getNodeByIdAsync(${JSON.stringify(values.node)});if(!n||!("exportAsync"in n))throw Error("Missing export node");return {png:figma.base64Encode(await n.exportAsync({format:"PNG",constraint:{type:"SCALE",value:${scale}}})),bounds:n.absoluteRenderBounds}`
+ const exported = (await $`figma-use eval --json --timeout 60 ${code}`.json()) as {
+ png: string
+ bounds: unknown
+ }
+ await Bun.write(join(values.output, 'figma.png'), toUint8Array(exported.png))
+ await Bun.write(
+ join(values.output, 'figma-bounds.json'),
+ JSON.stringify(exported.bounds, null, 2)
+ )
+}
+console.log(`Wrote direct-render artifacts to ${values.output}`)
diff --git a/tools/generate/visual-oracles/tests/cli.test.ts b/tools/generate/visual-oracles/tests/cli.test.ts
index 9071487fb..1a5a33699 100644
--- a/tools/generate/visual-oracles/tests/cli.test.ts
+++ b/tools/generate/visual-oracles/tests/cli.test.ts
@@ -10,5 +10,6 @@ describe('visual oracle CLI', () => {
expect(usage).toContain('node')
expect(usage).toContain('document')
+ expect(usage).toContain('digest')
})
})
diff --git a/tools/generate/visual-oracles/tests/document/document-capture.test.ts b/tools/generate/visual-oracles/tests/document/document-capture.test.ts
new file mode 100644
index 000000000..8a3228b1c
--- /dev/null
+++ b/tools/generate/visual-oracles/tests/document/document-capture.test.ts
@@ -0,0 +1,26 @@
+import { expect, test } from 'bun:test'
+
+import { captureDocumentOracle } from '#visual/document-capture'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+/** Two captures only line up if every node is addressed by page as well as position. */
+test('each page keeps its own node paths under a page prefix', () => {
+ const graph = new SceneGraph()
+ const first = graph.getPages()[0]
+ graph.createNode('FRAME', first.id, { name: 'Only' })
+ const second = graph.addPage('Second')
+ const frame = graph.createNode('FRAME', second.id, { name: 'Outer' })
+ graph.createNode('TEXT', frame.id, { name: 'Inner', text: 'Hello' })
+
+ const nodes = captureDocumentOracle(graph, new Map())
+ const paths = nodes.map((node) => node.path.join(','))
+ expect(paths).toEqual(['0', '0,0', '1', '1,0', '1,0,0'])
+ expect(nodes.find((node) => node.path.join(',') === '1,0,0')?.text).toBe('Hello')
+})
+
+test('an unchanged document captures identically', () => {
+ const graph = new SceneGraph()
+ graph.createNode('FRAME', graph.getPages()[0].id, { name: 'Frame' })
+ expect(captureDocumentOracle(graph, new Map())).toEqual(captureDocumentOracle(graph, new Map()))
+})
diff --git a/tools/generate/visual-oracles/tests/document/path-diagnostics.test.ts b/tools/generate/visual-oracles/tests/document/path-diagnostics.test.ts
new file mode 100644
index 000000000..aa06ffe61
--- /dev/null
+++ b/tools/generate/visual-oracles/tests/document/path-diagnostics.test.ts
@@ -0,0 +1,33 @@
+import { expect, test } from 'bun:test'
+
+import { summarizePathDiagnostics } from '#visual/path-diagnostics'
+
+test('keeps different effective replacement components in separate groups', () => {
+ const diagnostic = {
+ ownerId: '1:1',
+ path: [{ sessionID: 1, localID: 2 }],
+ reason: 'missing-target' as const
+ }
+ expect(
+ summarizePathDiagnostics([
+ { ...diagnostic, mainComponentId: '1:3' },
+ { ...diagnostic, mainComponentId: '1:4' }
+ ])
+ ).toHaveLength(2)
+})
+
+test('groups repeated evaluations without collapsing owner or complete path', () => {
+ const first = {
+ ownerId: '1:1',
+ path: [{ sessionID: 1, localID: 2 }],
+ reason: 'missing-target' as const
+ }
+ const result = summarizePathDiagnostics([
+ first,
+ first,
+ { ...first, ownerId: '1:3' },
+ { ...first, path: [{ sessionID: 1, localID: 4 }, ...first.path] }
+ ])
+ expect(result.map((entry) => entry.occurrences)).toEqual([2, 1, 1])
+ expect(first).not.toHaveProperty('occurrences')
+})
diff --git a/tools/generate/visual-oracles/tests/document/scene-oracle.test.ts b/tools/generate/visual-oracles/tests/document/scene-oracle.test.ts
new file mode 100644
index 000000000..3895c5c90
--- /dev/null
+++ b/tools/generate/visual-oracles/tests/document/scene-oracle.test.ts
@@ -0,0 +1,56 @@
+import { expect, test } from 'bun:test'
+
+import { compareSceneOracle, type SceneOracleNode } from '#visual/scene-oracle'
+
+const node = (path: number[], visible = true): SceneOracleNode => ({
+ path,
+ visible,
+ type: 'RECTANGLE',
+ name: 'Node',
+ x: 0,
+ y: 0,
+ width: 10,
+ height: 10,
+ text: null,
+ main: null,
+ fills: [],
+ strokes: []
+})
+
+test('separates hidden descendant geometry and detects extra nodes', () => {
+ const expected = [node([]), node([0], false), node([0, 0])]
+ const actual = structuredClone(expected)
+ actual[2].width = 20
+ actual.push(node([1]))
+ expect(compareSceneOracle(expected, actual).map((d) => d.category)).toEqual([
+ 'hidden-geometry',
+ 'structure'
+ ])
+})
+
+test('reports a paint difference, and hides it with the layer that carries it', () => {
+ const expected = [node([]), node([0], false), node([0, 0])]
+ const actual = structuredClone(expected)
+ actual[0].fills = ['SOLID 255,255,255 50%']
+ actual[2].fills = ['SOLID 255,255,255 50%']
+ expect(compareSceneOracle(expected, actual).map((d) => d.category)).toEqual([
+ 'visible-paint',
+ 'hidden-paint'
+ ])
+})
+
+test('normalizes rectangle representation but never hides visibility mismatches', () => {
+ const expected = [node([])]
+ const actual = [{ ...node([]), type: 'ROUNDED_RECTANGLE' }]
+ expect(compareSceneOracle(expected, actual)).toEqual([])
+ actual[0].visible = false
+ actual[0].width = 11
+ expect(compareSceneOracle(expected, actual).map((d) => d.category)).toEqual([
+ 'semantic',
+ 'visible-geometry'
+ ])
+})
+
+test('rejects duplicate addresses', () => {
+ expect(() => compareSceneOracle([node([]), node([])], [])).toThrow('Duplicate occurrence path')
+})
diff --git a/tsconfig.json b/tsconfig.json
index 1997b05fe..ee7460b05 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -32,6 +32,9 @@
"#core/*": [
"./packages/core/src/*"
],
+ "#fig/*": [
+ "./packages/fig/src/*"
+ ],
"#cli/*": [
"./packages/cli/src/*"
],