AI-native design editor. Open-source Figma alternative.
fix(pen): detach instances whose overrides replace their layers (#1465)
Marcos Velásquez260ed98f1175
diff --git a/changes/1465/fixed.md b/changes/1465/fixed.mdnew file mode 100644index 000000000..ccbbf8673--- /dev/null+++ b/changes/1465/fixed.md@@ -0,0 +1 @@+- `.pen` documents whose instance overrides replace layers save as `.fig`: a nested instance replaced by another component is swapped, as in Figma, and an instance whose layers an override replaces otherwise opens detached.diff --git a/packages/core/tests/io/formats/pen/instances.test.ts b/packages/core/tests/io/formats/pen/instances.test.tsnew file mode 100644index 000000000..6f83cfd8f--- /dev/null+++ b/packages/core/tests/io/formats/pen/instances.test.ts@@ -0,0 +1,74 @@+import { describe, expect, test } from 'bun:test'++import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'+import { layoutAuthoredNodes } from '@open-pencil/core/layout'+import { initCodec } from '@open-pencil/kiwi/fig/codec'+import { parsePenFile, type PenDocument, type PenNode } from '@open-pencil/pen'++const button: PenNode = {+ id: 'button',+ type: 'frame',+ name: 'Button',+ reusable: true,+ children: [{ id: 'dot', type: 'ellipse', width: 8, height: 8 }]+}+const card: PenNode = {+ id: 'card',+ type: 'frame',+ name: 'Card',+ reusable: true,+ layout: 'vertical',+ children: [+ { id: 'title', type: 'text', content: 'Card title' },+ { id: 'cardButton', type: 'ref', ref: 'button' }+ ]+}+const badge: PenNode = {+ id: 'badge',+ type: 'frame',+ name: 'Badge',+ reusable: true,+ children: [{ id: 'badgeLabel', type: 'text', content: 'New' }]+}++describe('.pen instances saved as .fig', () => {+ test('keep a nested instance an override swaps for another component', async () => {+ await initCodec()+ const document: PenDocument = {+ version: '2.21',+ children: [+ button,+ card,+ badge,+ {+ id: 'withBadge',+ type: 'ref',+ ref: 'card',+ name: 'Promo',+ descendants: {+ cardButton: {+ type: 'ref',+ ref: 'badge',+ descendants: { badgeLabel: { content: 'Sale' } }+ }+ }+ }+ ]+ }+ const graph = parsePenFile(JSON.stringify(document), {+ layout: (target) =>+ layoutAuthoredNodes(+ target,+ target.getPages().map((page) => page.id)+ )+ })+ const reopened = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)+ const promo = [...reopened.getAllNodes()].find((node) => node.name === 'Promo')+ const nested = promo ? reopened.getChildren(promo.id)[1] : undefined++ expect(promo?.type).toBe('INSTANCE')+ expect(nested?.type).toBe('INSTANCE')+ expect(reopened.getNode(nested?.componentId ?? '')?.name).toBe('Badge')+ expect(reopened.getChildren(nested?.id ?? '').map((node) => node.text)).toEqual(['Sale'])+ })+})diff --git a/packages/pen/src/instances.ts b/packages/pen/src/instances.tsindex 5fdd22f68..a8f726558 100644--- a/packages/pen/src/instances.ts+++ b/packages/pen/src/instances.ts@@ -3,14 +3,19 @@ import { isEqual } from 'es-toolkit/predicate'import { generateId, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import {+ detachInstance,INSTANCE_OVERRIDE_FIELDS,populateInstanceChildren,- recordInstanceOverride+ recordInstanceOverride,+ swapInstanceComponent} from '@open-pencil/scene-graph/instances'import { applyPenProperties, createSceneNode, type Build } from './nodes'import type { PenNode, PenOverride } from './schema'+/** Fills an instance read from `.pen`, after the instances inside its component. */+type Populate = (id: string) => void+/** The layers a copy was made from, nearest first, through copies of copies. */function sources(graph: SceneGraph, node: SceneNode): Set<string> {const found = new Set<string>()@@ -61,10 +66,16 @@ function inAncestorThemes<T>(build: Build, node: SceneNode, apply: () => T): T {}}-function replaceLayer(build: Build, target: SceneNode, replacement: PenOverride): void {+function replaceLayer(+ build: Build,+ target: SceneNode,+ replacement: PenOverride,+ populate: Populate+): void {const { graph } = buildconst parentId = target.parentIdif (!parentId) return+ if (swapLayer(build, target, replacement, populate)) returnconst index = graph.getNode(parentId)?.childIds.indexOf(target.id) ?? -1const pen: PenNode = {...replacement,@@ -75,9 +86,47 @@ function replaceLayer(build: Build, target: SceneNode, replacement: PenOverride)graph.deleteNode(target.id)const id = createSceneNode(pen, parentId, build)if (id && index >= 0) graph.insertChildAt(id, parentId, index)+ // The parent's layers changed; a replacement that is itself an instance stays one.+ if (id) build.replaced.add(parentId)})}+/**+ * Swaps a nested instance an override replaces with an instance of another component for that+ * component, as Figma's instance swap does, so the instances holding it stay instances. The+ * replacement's own fields and overrides then apply to the swapped layer. Returns whether it+ * swapped; any other replacement changes the layers of the instance holding it.+ */+function swapLayer(+ build: Build,+ target: SceneNode,+ replacement: PenOverride,+ populate: Populate+): boolean {+ const { graph, effective, instances } = build+ const component =+ typeof replacement.ref === 'string' ? build.components.get(replacement.ref) : undefined+ if (target.type !== 'INSTANCE' || replacement.type !== 'ref' || component?.type !== 'frame')+ return false+ for (const nested of instances.keys()) {+ if (graph.isDescendant(nested, component.id)) populate(nested)+ }+ swapInstanceComponent(graph, target.id, component.id)+ if (graph.getNode(target.id)?.componentId !== component.id) return false+ const {+ children: _children,+ reusable: _reusable,+ descendants: _descendants,+ ...fields+ } = component+ effective.set(target.id, { ...fields, id: target.id })+ inheritCopyFields(build, target)+ const { ref: _ref, type: _type, id: _id, descendants, ...own } = replacement+ overrideLayer(build, target, own)+ applyDescendants(build, target, descendants, populate)+ return true+}+/*** Records as the instance's overrides the fields an override changed on a copy, so they survive* the instance's next sync and a save, as an edit made in the editor would.@@ -106,6 +155,7 @@ function overrideLayer(build: Build, target: SceneNode, override: PenOverride):const replaced = target.childIdsfor (const childId of replaced) graph.deleteNode(childId)for (const child of children) createSceneNode(child, target.id, build)+ build.replaced.add(target.id)}} finally {leave?.()@@ -113,23 +163,60 @@ function overrideLayer(build: Build, target: SceneNode, override: PenOverride):})}+/**+ * Detaches the instances holding a layer whose children an override replaced. An instance keeps+ * its component's layers, overriding their fields but never replacing them, so such an instance+ * becomes a frame that keeps what it shows, as detaching it in Figma does.+ */+function detachReplacingInstances(build: Build): void {+ const { graph } = build+ for (const id of build.replaced) {+ for (let node = graph.getNode(id); node;) {+ if (node.type === 'INSTANCE') detachInstance(graph, node.id)+ node = node.parentId ? graph.getNode(node.parentId) : undefined+ }+ }+ build.replaced.clear()+}+/** Gives an instance's copies their overrides; a key with a `type` replaces the layer. */-function applyDescendants(build: Build, instance: SceneNode, ref: PenNode): void {- for (const [path, override] of Object.entries(ref.descendants ?? {})) {+function applyDescendants(+ build: Build,+ instance: SceneNode,+ descendants: PenNode['descendants'],+ populate: Populate+): void {+ for (const [path, override] of Object.entries(descendants ?? {})) {const target = resolvePath(build.graph, instance, path)if (!target) continue- if (override.type) replaceLayer(build, target, override)+ if (override.type) replaceLayer(build, target, override, populate)else overrideLayer(build, target, override)}}+/** Gives each copy inside `root` the pen.dev fields and placement of the layer it copies. */+function inheritCopyFields(build: Build, root: SceneNode): void {+ const { graph, effective, placements } = build+ const copies = graph.getChildren(root.id)+ for (const copy of copies) {+ const source = copy.componentId+ const fields = source ? effective.get(source) : undefined+ if (fields) effective.set(copy.id, fields)+ const placement = source ? placements.get(source) : undefined+ if (placement) placements.set(copy.id, placement)+ if (source && build.groupIds.has(source)) build.groupIds.add(copy.id)+ if (source && build.aroundIds.has(source)) build.aroundIds.add(copy.id)+ copies.push(...graph.getChildren(copy.id))+ }+}+/*** Fills each instance with copies of its component's layers, then applies its overrides. An* instance inside a component is filled first, so the copies made of it carry its layers and* overrides; a copy keeps its source's pen.dev fields and placement.*/export function populateInstances(build: Build): void {- const { graph, effective, placements, instances } = build+ const { graph, instances } = buildconst done = new Set<string>()function populate(id: string): void {@@ -144,18 +231,10 @@ export function populateInstances(build: Build): void {if (graph.isDescendant(nested, component.id)) populate(nested)}populateInstanceChildren(graph, instance.id, component.id)- const copies = graph.getChildren(instance.id)- for (const copy of copies) {- const source = copy.componentId- const fields = source ? effective.get(source) : undefined- if (fields) effective.set(copy.id, fields)- const placement = source ? placements.get(source) : undefined- if (placement) placements.set(copy.id, placement)- if (source && build.groupIds.has(source)) build.groupIds.add(copy.id)- if (source && build.aroundIds.has(source)) build.aroundIds.add(copy.id)- copies.push(...graph.getChildren(copy.id))- }- applyDescendants(build, instance, ref)+ inheritCopyFields(build, instance)+ applyDescendants(build, instance, ref.descendants, populate)+ // Before anything copies this instance, so the copies are of what it became.+ detachReplacingInstances(build)}// A replacement may hold instances of its own, which join the map as they are read.diff --git a/packages/pen/src/nodes.ts b/packages/pen/src/nodes.tsindex 61ae7e151..8977d923d 100644--- a/packages/pen/src/nodes.ts+++ b/packages/pen/src/nodes.ts@@ -66,6 +66,8 @@ export interface Build {iconComponents: Map<string, string>/** The page those components are on, added with the first one. */iconPageId: string | null+ /** Layers whose children an override replaced, whose instances are detached. */+ replaced: Set<string>}function penPlacement(pen: PenOverride, ctx: VarContext): PenPlacement {diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.tsindex 17af64f97..c8e305a1c 100644--- a/packages/pen/src/read.ts+++ b/packages/pen/src/read.ts@@ -69,7 +69,8 @@ export function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): SgroupIds: new Set(),aroundIds: new Set(),iconComponents: new Map(),- iconPageId: null+ iconPageId: null,+ replaced: new Set()}collectComponents(doc.children, build.components)diff --git a/packages/pen/tests/instances.test.ts b/packages/pen/tests/instances.test.tsindex 5c1efa563..b7b9b3e63 100644--- a/packages/pen/tests/instances.test.ts+++ b/packages/pen/tests/instances.test.ts@@ -141,6 +141,104 @@ describe('parsePenFile — instances', () => {expect(getNodeOrThrow(graph, 'square').fills[0]?.color).toMatchObject({ r: 1, g: 1, b: 0 })})+ test('detaches an instance whose override replaces a layer or its children', () => {+ const graph = parseDocument([+ button,+ card,+ {+ id: 'replacedLayer',+ type: 'ref',+ ref: 'button',+ descendants: { dot: { type: 'rectangle', id: 'square', width: 10, height: 10 } }+ },+ {+ id: 'replacedChildren',+ type: 'ref',+ ref: 'card',+ descendants: {+ cardButton: { children: [{ id: 'note', type: 'text', content: 'Note' }] }+ }+ },+ { id: 'kept', type: 'ref', ref: 'card' }+ ])+ // Instances keep their component's layers, so these become frames showing the same layers.+ expect(getNodeOrThrow(graph, 'replacedLayer')).toMatchObject({+ type: 'FRAME',+ componentId: null+ })+ expect(graph.getChildren('replacedLayer').map((node) => node.type)).toEqual([+ 'RECTANGLE',+ 'TEXT'+ ])+ expect(getNodeOrThrow(graph, 'replacedChildren').type).toBe('FRAME')+ // The card's second layer is its button.+ const nested = expectDefined(graph.getChildren('replacedChildren')[1], 'nested button')+ expect(nested.type).toBe('FRAME')+ expect(graph.getChildren(nested.id).map((node) => node.text)).toEqual(['Note'])+ expect(getNodeOrThrow(graph, 'kept').type).toBe('INSTANCE')+ expect(graph.getChildren('kept')[1]?.type).toBe('INSTANCE')+ })++ test('keeps a replacement that is an instance of another component', () => {+ const badge: PenNode = {+ id: 'badge',+ type: 'frame',+ reusable: true,+ children: [{ id: 'badgeLabel', type: 'text', content: 'New' }]+ }+ const graph = parseDocument([+ button,+ badge,+ {+ id: 'withBadge',+ type: 'ref',+ ref: 'button',+ descendants: { dot: { type: 'ref', id: 'swappedBadge', ref: 'badge' } }+ }+ ])+ expect(getNodeOrThrow(graph, 'withBadge').type).toBe('FRAME')+ expect(getNodeOrThrow(graph, 'swappedBadge')).toMatchObject({+ type: 'INSTANCE',+ componentId: 'badge'+ })+ expect(graph.getChildren('swappedBadge').map((node) => node.text)).toEqual(['New'])+ })++ test('swaps a nested instance a replacement makes an instance of another component', () => {+ const badge: PenNode = {+ id: 'badge',+ type: 'frame',+ reusable: true,+ children: [{ id: 'badgeLabel', type: 'text', content: 'New' }]+ }+ const graph = parseDocument([+ button,+ card,+ badge,+ {+ id: 'withBadge',+ type: 'ref',+ ref: 'card',+ descendants: {+ cardButton: {+ type: 'ref',+ ref: 'badge',+ name: 'Status',+ descendants: { badgeLabel: { content: 'Sale' } }+ }+ }+ }+ ])+ // As Figma's instance swap: the card stays an instance and its button shows the badge.+ expect(getNodeOrThrow(graph, 'withBadge').type).toBe('INSTANCE')+ const swapped = expectDefined(graph.getChildren('withBadge')[1], 'swapped button')+ expect(swapped).toMatchObject({ type: 'INSTANCE', componentId: 'badge', name: 'Status' })+ expect(graph.getChildren(swapped.id).map((node) => node.text)).toEqual(['Sale'])+ // Its overrides are recorded, so a sync keeps them.+ syncInstance(graph, 'withBadge')+ expect(graph.getChildren(swapped.id).map((node) => node.text)).toEqual(['Sale'])+ })+test('hides a descendant through its enabled field', () => {const graph = parseDocument([button,