AI-native design editor. Open-source Figma alternative.
fix(pen): record an instance's own fields and a swapped icon's name as overrides (#1502)
Marcos Velásquez6da1bf51caec
diff --git a/changes/1502/fixed.md b/changes/1502/fixed.mdnew file mode 100644index 000000000..b79a474cd--- /dev/null+++ b/changes/1502/fixed.md@@ -0,0 +1 @@+- `.pen` instances keep the fields their `ref` sets, and a swapped icon keeps its layer name, after a sync or saving as `.fig`.diff --git a/packages/pen/src/icons.ts b/packages/pen/src/icons.tsindex 783b48f18..a725f8f57 100644--- a/packages/pen/src/icons.ts+++ b/packages/pen/src/icons.ts@@ -138,6 +138,8 @@ export function useIconComponent(node: SceneNode, pen: PenNode, build: Build): vpopulateInstanceChildren(graph, node.id, componentId)} else if (instanceMainComponent(graph, node)?.id !== componentId) {swapInstanceComponent(graph, node.id, componentId, { keepName: true })+ // The layer keeps its own name rather than the icon's, which a saved file keeps as an override.+ recordInstanceOverride(graph, node.id, ['name'])}keepOwnFields(graph, node.id, own, componentId)recolorGlyph(graph, node.id, color)diff --git a/packages/pen/src/instances.ts b/packages/pen/src/instances.tsindex a8f726558..1b6cdf219 100644--- a/packages/pen/src/instances.ts+++ b/packages/pen/src/instances.ts@@ -10,7 +10,7 @@ import {swapInstanceComponent} from '@open-pencil/scene-graph/instances'-import { applyPenProperties, createSceneNode, type Build } from './nodes'+import { applyPenProperties, createSceneNode, fieldsSetBy, type Build } from './nodes'import type { PenNode, PenOverride } from './schema'/** Fills an instance read from `.pen`, after the instances inside its component. */@@ -128,16 +128,34 @@ function swapLayer(}/**- * 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.+ * Records as the instance's overrides the fields an override set or changed on a copy, so they+ * survive the instance's next sync and a save, as an edit made in the editor would.*/function recordChangedFields(graph: SceneGraph,target: SceneNode,- before: Partial<SceneNode>+ before: Partial<SceneNode>,+ override: PenOverride): void {const changed = INSTANCE_OVERRIDE_FIELDS.filter((field) => !isEqual(before[field], target[field]))- recordInstanceOverride(graph, target.id, changed)+ recordInstanceOverride(graph, target.id, [...changed, ...fieldsSetBy(override)])+}++/**+ * Records as the instance's own overrides the fields its `ref` sets or makes differ from its+ * component's. A size counts only when the `ref` sets it: otherwise it is the layout's, which+ * follows the component's.+ */+function recordOwnFields(graph: SceneGraph, instance: SceneNode, ref: PenNode): void {+ const component = instance.componentId ? graph.getNode(instance.componentId) : undefined+ if (!component) return+ const changed = INSTANCE_OVERRIDE_FIELDS.filter(+ (field) =>+ (field !== 'width' || 'width' in ref) &&+ (field !== 'height' || 'height' in ref) &&+ !isEqual(instance[field], component[field])+ )+ recordInstanceOverride(graph, instance.id, [...changed, ...fieldsSetBy(ref)])}function overrideLayer(build: Build, target: SceneNode, override: PenOverride): void {@@ -150,7 +168,7 @@ function overrideLayer(build: Build, target: SceneNode, override: PenOverride):const leave = merged.theme ? ctx.enterTheme(merged.theme) : undefinedtry {applyPenProperties(target, merged, build)- recordChangedFields(graph, target, before)+ recordChangedFields(graph, target, before, fields)if (children) {const replaced = target.childIdsfor (const childId of replaced) graph.deleteNode(childId)@@ -231,6 +249,7 @@ export function populateInstances(build: Build): void {if (graph.isDescendant(nested, component.id)) populate(nested)}populateInstanceChildren(graph, instance.id, component.id)+ recordOwnFields(graph, instance, ref)inheritCopyFields(build, instance)applyDescendants(build, instance, ref.descendants, populate)// Before anything copies this instance, so the copies are of what it became.diff --git a/packages/pen/src/nodes.ts b/packages/pen/src/nodes.tsindex 8977d923d..96c70d9e4 100644--- a/packages/pen/src/nodes.ts+++ b/packages/pen/src/nodes.ts@@ -6,6 +6,7 @@ import type {SceneGraph,SceneNode} from '@open-pencil/scene-graph'+import { CORNER_FIELDS } from '@open-pencil/scene-graph/fields'import { fillSizingFields } from '@open-pencil/scene-graph/layout'import type { Color } from '@open-pencil/scene-graph/primitives'@@ -23,7 +24,7 @@ import {} from './layout'import { applyStroke, convertPaints, strokeFields } from './paints'import { isPlain, type PenPlacement } from './placement'-import type { PenNode, PenOverride } from './schema'+import type { NodeFields, PenNode, PenOverride } from './schema'import { applyTextProps } from './text'import { bindIfVar, resolveBoolean, resolveNumber, type VarContext } from './variables'@@ -131,6 +132,96 @@ function applyAutoLayout(}}+const PLACEMENT_FIELDS = ['x', 'y', 'rotation', 'flipX', 'flipY'] as const++/** What `applyStroke` writes: a stroke's weight and alignment are its paints'. */+const STROKE_WRITES = [+ 'strokes',+ 'independentStrokeWeights',+ 'borderTopWeight',+ 'borderRightWeight',+ 'borderBottomWeight',+ 'borderLeftWeight',+ 'strokeCap',+ 'strokeJoin'+] as const++/**+ * The layer fields each property `applyPenProperties` reads writes. A property that writes none of+ * the layer's own fields maps to none: bookkeeping, the decorations pen.dev does not draw, and an+ * icon's glyph, which is the layer's children or the component it shows.+ */+const PROPERTY_FIELDS = {+ name: ['name'],+ context: [],+ x: PLACEMENT_FIELDS,+ y: PLACEMENT_FIELDS,+ width: ['width'],+ height: ['height'],+ reusable: [],+ theme: ['variableModes'],+ enabled: ['visible'],+ opacity: ['opacity'],+ flipX: PLACEMENT_FIELDS,+ flipY: PLACEMENT_FIELDS,+ layoutPosition: ['layoutPositioning'],+ rotation: PLACEMENT_FIELDS,+ fill: ['fills'],+ stroke: STROKE_WRITES,+ strokeWidth: STROKE_WRITES,+ strokeLinecap: ['strokes', 'strokeCap'],+ strokeLinejoin: ['strokes', 'strokeJoin'],+ strokeAlignment: ['strokes'],+ effect: ['effects'],+ cornerRadius: CORNER_FIELDS,+ layout: ['layoutMode'],+ gap: ['itemSpacing'],+ layoutIncludeStroke: ['strokesIncludedInLayout'],+ padding: ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'],+ justifyContent: ['primaryAxisAlign'],+ alignItems: ['counterAxisAlign'],+ clip: ['clipsContent'],+ placeholder: [],+ slot: [],+ innerRadius: ['arcData'],+ startAngle: ['arcData'],+ sweepAngle: ['arcData'],+ polygonCount: ['pointCount'],+ geometry: ['vectorNetwork'],+ fillRule: ['vectorNetwork'],+ viewBox: ['vectorNetwork'],+ content: ['text'],+ textGrowth: ['textAutoResize'],+ fontFamily: ['fontFamily'],+ fontSize: ['fontSize'],+ fontWeight: ['fontWeight'],+ fontStyle: ['italic'],+ letterSpacing: ['letterSpacing'],+ lineHeight: ['lineHeight'],+ textAlign: ['textAlignHorizontal'],+ textAlignVertical: ['textAlignVertical'],+ underline: [],+ strikethrough: [],+ href: [],+ library: [],+ icon: [],+ weight: [],+ iconFontName: [],+ iconFontFamily: [],+ ref: []+} satisfies Record<keyof NodeFields, readonly (keyof SceneNode)[]>++const isProperty = (key: string): key is keyof typeof PROPERTY_FIELDS => key in PROPERTY_FIELDS++/**+ * The fields the properties `pen` carries write, whatever their values: pen.dev keeps a property+ * an instance sets even when it equals its component's, so a later change to the component does+ * not reach it.+ */+export function fieldsSetBy(pen: PenOverride): (keyof SceneNode)[] {+ return Object.keys(pen).flatMap((key) => (isProperty(key) ? PROPERTY_FIELDS[key] : []))+}+/*** Sets every field a layer takes from its pen.dev fields, so a layer copied from a component can be* given its overrides by applying its merged fields again. Turned and mirrored layers are builtdiff --git a/packages/pen/src/schema.ts b/packages/pen/src/schema.tsindex c282d77c7..6034cab85 100644--- a/packages/pen/src/schema.ts+++ b/packages/pen/src/schema.ts@@ -159,7 +159,7 @@ const nodeFields = {ref: v.optional(strSchema)}-type NodeFields = v.InferOutput<v.ObjectSchema<typeof nodeFields, undefined>>+export type NodeFields = v.InferOutput<v.ObjectSchema<typeof nodeFields, undefined>>/** Properties an instance sets on one of its component's descendants, or a node replacing it. */export interface PenOverride extends NodeFields {diff --git a/packages/pen/tests/icons.test.ts b/packages/pen/tests/icons.test.tsindex eb07d9cc8..4ae3990ec 100644--- a/packages/pen/tests/icons.test.ts+++ b/packages/pen/tests/icons.test.ts@@ -80,6 +80,9 @@ describe('parsePenFile — icons in components', () => {})const glyph = glyphOf(graph, 'swapped')expect(instanceMainComponent(graph, glyph)?.name).toBe('lucide/star/16x16')+ // The layer keeps its name, as an override a saved file keeps.+ expect(glyph.name).toBe(getNodeOrThrow(graph, 'glyph').name)+ expect(hasInstanceOverride(graph, glyph.id, 'name')).toBe(true)// Every layer the instance holds is a copy of a component's layer, as a .fig file needs.const queue = [...graph.getChildren('swapped')]for (const node of queue) {diff --git a/packages/pen/tests/instances.test.ts b/packages/pen/tests/instances.test.tsindex b7b9b3e63..29a869a06 100644--- a/packages/pen/tests/instances.test.ts+++ b/packages/pen/tests/instances.test.ts@@ -86,6 +86,59 @@ describe('parsePenFile — instances', () => {expect(getNodeOrThrow(graph, 'label').text).toBe('Button')})+ test("records the instance's own fields as overrides, its size only when it sets one", () => {+ const graph = parseDocument([+ button,+ { id: 'tinted', type: 'ref', ref: 'button', fill: '#119944' },+ { id: 'sized', type: 'ref', ref: 'button', width: 200 }+ ])+ expect(hasInstanceOverride(graph, 'tinted', 'fills')).toBe(true)+ expect(hasInstanceOverride(graph, 'tinted', 'width')).toBe(false)+ expect(hasInstanceOverride(graph, 'sized', 'width')).toBe(true)++ syncInstance(graph, 'tinted')++ expect(getNodeOrThrow(graph, 'tinted').fills[0]?.color).toMatchObject({ r: 0x11 / 255 })+ })++ test('records the fields a stroke writes, not the ones it leaves to its paints', () => {+ const graph = parseDocument([+ button,+ { id: 'outlined', type: 'ref', ref: 'button', stroke: { fill: '#111111', thickness: 2 } }+ ])+ const recorded = (field: string) => hasInstanceOverride(graph, 'outlined', field)+ expect(['strokes', 'strokeCap', 'strokeJoin'].map(recorded)).toEqual([true, true, true])+ expect(['strokeWeight', 'strokeAlign', 'dashPattern'].map(recorded)).toEqual([+ false,+ false,+ false+ ])+ })++ test("keeps a field the ref sets to its component's value when the component changes", () => {+ const graph = parseDocument([+ button,+ {+ id: 'same',+ type: 'ref',+ ref: 'button',+ fill: '#2255CC',+ descendants: { label: { content: 'Button' } }+ }+ ])+ expect(hasInstanceOverride(graph, 'same', 'fills')).toBe(true)+ expect(hasInstanceOverride(graph, copyOf(graph, 'same', 'label').id, 'text')).toBe(true)++ graph.updateNode('button', {+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]+ })+ graph.updateNode('label', { text: 'Renamed' })+ syncInstance(graph, 'same')++ expect(getNodeOrThrow(graph, 'same').fills[0]?.color).toMatchObject({ r: 0x22 / 255 })+ expect(copyOf(graph, 'same', 'label').text).toBe('Button')+ })+test('records a descendant override so a sync keeps it', () => {const graph = parseDocument([button,