Skip to content

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

fix(components): record, save, and sync every field an instance can override (#1080)

Danila Poyarkov3bcf43905f65
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9aba55b28..20ea032e7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -130,6 +130,7 @@
- Customize the toolbar in **Settings → Toolbar**, also opened from **Customize toolbar…** when you right-click it: hide tools, reorder them, and choose which share a flyout, on desktop and mobile alike. Hidden tools keep their shortcuts, **Move** always stays, and tools added in later versions join their default flyout in a customized toolbar.
### Changed
+- The plugin API refuses to move, rotate, constrain, or mask a layer an instance takes from its component, with Figma's errors, such as `in set_x: This property cannot be overridden in an instance: relative-transform`. Those fields always follow the component. Slot content stays editable, and editing a slot's default content makes the instance own it, as in Figma.
- A layer dragged out of an auto layout frame leaves it as in Figma, once its edge is 5 px past the frame across the flow or about 15 px along it, instead of after the cursor travels 96 px beyond it.
- Bound variables show as a neutral chip in the properties panel instead of purple text, so they no longer read as components.
- Import SVG as editable layers, as pasting it into Figma does, from `import_svg`, dropped files, and pasted markup ([#734](https://github.com/open-pencil/open-pencil/issues/734)). Each `<g>` becomes a group, each shape its own vector, and each `<text>` a text layer with its fonts, `<tspan>` styles, alignment, and rotation, named after its `id`, element opacity is kept, and clipped content sits in a clip path group whose mask is drawn from the clip's shapes. The imported frame is white, clips its content, and is named after the root `<svg>` `id`; an SVG without a size imports as a group. Shapes are no longer merged into one multi-color vector.
@@ -182,6 +183,8 @@
### Fixed
+- Instances opened from a `.fig` file keep the style overrides Figma gives them, such as corner radius, stroke weight and alignment, line height, letter spacing, font, effects, and fill, stroke, and effect styles. Editing their component used to overwrite them on the canvas while the saved file kept them, and a later edit to one of these fields in the instance was not saved. Text edited in an instance is saved with its styled ranges and list lines, as Figma writes it; saving kept only its characters.
+- A component edit reaches every field its instances do not override, as in Figma: stroke weight, alignment, caps, joins, and dashes, corner smoothing, blend mode, layout grids, letter spacing, line height, text case, decoration, alignment, truncation, styled ranges, and the position, rotation, and flips of layers outside auto layout. Such a layer is placed by its constraints when the instance has another size than its component.
- Crash recovery, chat history, diagnostics, local files, libraries, saved credentials, and the sync outbox keep saving after Safari suspends the tab. Safari closes their IndexedDB connections without telling the page, and every later write failed with "The database connection is closing" until the page was reloaded.
- HTML, Tailwind JSX, and Vue and React exports keep a text's character styles as spans, its lists as nested lists with Figma's markers, its paragraph spacing and first-line indent, and its decoration style, colour, thickness, offset, and skip ink, where they wrote the whole text in one style. Importing HTML reads them back: inline formatting and box-less paragraphs, headings, and lists join into one text layer.
- Underlines and strikethroughs are drawn where and as Figma draws them, from the font's own metrics: underlines break around descenders, dotted ones are round dots, and a set offset or thickness is kept, in reopened `.fig` files too, which drew no strikethroughs and misplaced the other styles. Text saved to `.fig` or copied to Figma keeps its decorations there, where Figma showed underlined text without them and underlined text over several lines not at all.
diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.ts
index ce98063f1..79784c6a6 100644
--- a/packages/core/src/figma-api/accessor-utils.ts
+++ b/packages/core/src/figma-api/accessor-utils.ts
@@ -1,7 +1,9 @@
import {
fitEnclosingGroups,
FITTED_CONTAINER_TYPES,
- recordInstanceOverride
+ claimSlotContent,
+ recordInstanceOverride,
+ slotScope
} from '@open-pencil/scene-graph'
import type { GroupFitOptions, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
@@ -36,6 +38,27 @@ export function assertProxyEditable(target: ProxyThis, internals: NodeProxyInter
assertNodeEditable(graph(target, internals), nodeId(target, internals))
}
+/**
+ * Readies an edit to a field a layer inside an instance always takes from its component. Figma
+ * refuses it there, naming the property it would have overridden (Figma desktop 126). Slot
+ * content is the instance's own and keeps the edit: a slot still showing the component's default
+ * content is claimed first, as Figma does on the first edit, so a later sync leaves it alone.
+ */
+export function prepareFollowedFieldEdit(
+ scene: SceneGraph,
+ node: SceneNode,
+ setter: string,
+ property: 'relative-transform' | 'vertical-constraint' | 'is-mask' | 'mask-type'
+): void {
+ if (!node.parentId) return
+ const scope = slotScope(scene, node.parentId)
+ if (scope.kind === 'locked')
+ throw new Error(
+ `in set_${setter}: This property cannot be overridden in an instance: ${property}`
+ )
+ if (scope.kind === 'slot') claimSlotContent(scene, scope)
+}
+
/** Fields whose change can move a node's bounds, so the groups around it refit. */
const GEOMETRY_FIELDS: ReadonlySet<string> = new Set([
'x',
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index 85b6125b7..28b177f38 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -16,6 +16,7 @@ import type { Rect } from '@open-pencil/scene-graph/primitives'
import { assertNodeEditable } from '#core/editor/capabilities'
import {
+ prepareFollowedFieldEdit,
fitGroupsAround,
graph,
hostFitOptions,
@@ -122,6 +123,12 @@ export function installBasicNodeProxyAccessors(
return containerTransform(raw(this, internals), graph(this, internals))[2]
},
set(this: ProxyThis, value: number) {
+ prepareFollowedFieldEdit(
+ graph(this, internals),
+ raw(this, internals),
+ 'x',
+ 'relative-transform'
+ )
setTransform(this, internals, (matrix) => withOrigin(matrix, value, matrix[5]))
}
},
@@ -131,6 +138,12 @@ export function installBasicNodeProxyAccessors(
return containerTransform(raw(this, internals), graph(this, internals))[5]
},
set(this: ProxyThis, value: number) {
+ prepareFollowedFieldEdit(
+ graph(this, internals),
+ raw(this, internals),
+ 'y',
+ 'relative-transform'
+ )
setTransform(this, internals, (matrix) => withOrigin(matrix, matrix[2], value))
}
},
@@ -157,6 +170,12 @@ export function installBasicNodeProxyAccessors(
},
// Figma turns a node counterclockwise about its top-left corner.
set(this: ProxyThis, value: number) {
+ prepareFollowedFieldEdit(
+ graph(this, internals),
+ raw(this, internals),
+ 'rotation',
+ 'relative-transform'
+ )
setTransform(this, internals, (matrix) => withFigmaRotation(matrix, value))
}
},
@@ -181,6 +200,12 @@ export function installBasicNodeProxyAccessors(
return figmaTransform(containerTransform(node, scene))
},
set(this: ProxyThis, value: FigmaTransform) {
+ prepareFollowedFieldEdit(
+ graph(this, internals),
+ raw(this, internals),
+ 'relativeTransform',
+ 'relative-transform'
+ )
const [[a, b, x], [c, d, y]] = value
setTransform(this, internals, () => [a, b, x, c, d, y, 0, 0, 1])
}
diff --git a/packages/core/src/figma-api/accessors/layout.ts b/packages/core/src/figma-api/accessors/layout.ts
index 40048e2a7..466e0fd2e 100644
--- a/packages/core/src/figma-api/accessors/layout.ts
+++ b/packages/core/src/figma-api/accessors/layout.ts
@@ -12,6 +12,7 @@ import {
} from '@open-pencil/scene-graph'
import {
+ prepareFollowedFieldEdit,
assertProxyEditable,
graph,
raw,
@@ -69,6 +70,12 @@ export function installLayoutNodeProxyAccessors(
return { horizontal: node.horizontalConstraint, vertical: node.verticalConstraint }
},
set(this: ProxyThis, value: { horizontal: string; vertical: string }) {
+ prepareFollowedFieldEdit(
+ graph(this, internals),
+ raw(this, internals),
+ 'constraints',
+ 'vertical-constraint'
+ )
updateNode(this, internals, {
horizontalConstraint: value.horizontal as SceneNode['horizontalConstraint'],
verticalConstraint: value.vertical as SceneNode['verticalConstraint']
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 49b11a82b..de6e3368b 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -24,7 +24,7 @@ import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import { assertNodeEditable } from '#core/editor/capabilities'
import type { FigmaEffect } from '#core/figma-api/effects'
-import { fitGroupsAround } from './accessor-utils'
+import { prepareFollowedFieldEdit, fitGroupsAround } from './accessor-utils'
import { installBasicNodeProxyAccessors } from './accessors/basic'
import { installLayoutNodeProxyAccessors } from './accessors/layout'
import { installStrokeNodeProxyAccessors } from './accessors/strokes'
@@ -267,6 +267,7 @@ export class FigmaNodeProxy {
}
set isMask(v: boolean) {
+ prepareFollowedFieldEdit(this[INTERNAL_GRAPH], this._raw(), 'isMask', 'is-mask')
this._update({ isMask: v })
}
@@ -275,6 +276,7 @@ export class FigmaNodeProxy {
}
set maskType(v: string) {
+ prepareFollowedFieldEdit(this[INTERNAL_GRAPH], this._raw(), 'maskType', 'mask-type')
this._update({ maskType: v as SceneNode['maskType'] })
}
diff --git a/packages/core/tests/figma-api/instance-overrides.test.ts b/packages/core/tests/figma-api/instance-overrides.test.ts
new file mode 100644
index 000000000..541fb4ae8
--- /dev/null
+++ b/packages/core/tests/figma-api/instance-overrides.test.ts
@@ -0,0 +1,86 @@
+import { expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
+import { createComponentPropertyId, hasInstanceOverride, SceneGraph } from '@open-pencil/scene-graph'
+
+// Recorded with the same script in Figma desktop 126.
+
+function setup() {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const component = figma.createComponent()
+ component.resize(100, 100)
+ component.appendChild(figma.createRectangle())
+ const instance = component.createInstance()
+ const [layer] = instance.children as FigmaNodeProxy[]
+ return { graph, instance, layer }
+}
+
+test('a layer inside an instance refuses the fields it always takes from its component', () => {
+ const { layer } = setup()
+ const refused = (setter: string, property: string) =>
+ `in set_${setter}: This property cannot be overridden in an instance: ${property}`
+ expect(() => (layer.x = 5)).toThrow(refused('x', 'relative-transform'))
+ expect(() => (layer.y = 5)).toThrow(refused('y', 'relative-transform'))
+ expect(() => (layer.rotation = 10)).toThrow(refused('rotation', 'relative-transform'))
+ expect(() => (layer.relativeTransform = [[1, 0, 3], [0, 1, 3]])).toThrow(
+ refused('relativeTransform', 'relative-transform')
+ )
+ expect(() => (layer.constraints = { horizontal: 'MAX', vertical: 'MIN' })).toThrow(
+ refused('constraints', 'vertical-constraint')
+ )
+ expect(() => (layer.isMask = true)).toThrow(refused('isMask', 'is-mask'))
+ expect(() => (layer.maskType = 'LUMINANCE')).toThrow(refused('maskType', 'mask-type'))
+})
+
+test('a layer inside an instance can be locked and restyled, each recorded as an override', () => {
+ const { graph, instance, layer } = setup()
+ layer.locked = true
+ layer.strokeWeight = 4
+ expect(hasInstanceOverride(graph, layer.id, 'locked')).toBe(true)
+ expect(hasInstanceOverride(graph, layer.id, 'strokeWeight')).toBe(true)
+ // The instance itself still moves.
+ instance.x = 40
+ expect(instance.x).toBe(40)
+})
+
+/** A Card component whose Body slot shows a default Note layer, and an instance of it. */
+function slotSetup() {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const page = graph.getPages()[0].id
+ const body = createComponentPropertyId()
+ const card = graph.createNode('COMPONENT', page, {
+ componentPropertyDefinitions: [{ id: body, name: 'Body', type: 'SLOT', defaultValue: '' }]
+ })
+ const frame = graph.createNode('FRAME', card.id, {
+ name: 'Body',
+ width: 200,
+ height: 100,
+ componentPropertyReferences: [{ propertyId: body, field: 'SLOT_CONTENT' }]
+ })
+ const note = graph.createNode('RECTANGLE', frame.id, { name: 'Note', x: 10, y: 10 })
+ const instance = expectDefined(graph.createInstance(card.id, page))
+ const slot = expectDefined(figma.getNodeById(graph.getChildren(instance.id)[0].id))
+ return { graph, figma, card, note, slot }
+}
+
+test('slot content is the instance’s own and keeps its position and constraints', () => {
+ const { figma, slot } = slotSetup()
+ const added = figma.createRectangle()
+ slot.appendChild(added)
+ added.x = 12
+ added.constraints = { horizontal: 'MAX', vertical: 'MIN' }
+ expect([added.x, added.constraints.horizontal]).toEqual([12, 'MAX'])
+})
+
+test('moving default slot content claims the slot, so the component no longer moves it', () => {
+ const { graph, card, note, slot } = slotSetup()
+ const [copy] = slot.children as FigmaNodeProxy[]
+ copy.x = 40
+ graph.updateNode(note.id, { x: 90 })
+ graph.syncInstances(card.id)
+ expect(copy.x).toBe(40)
+})
diff --git a/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts b/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts
new file mode 100644
index 000000000..4fd47a059
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts
@@ -0,0 +1,55 @@
+import { beforeAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { hasInstanceOverride, recordInstanceOverride } from '@open-pencil/scene-graph'
+
+beforeAll(async () => {
+ await initCodec()
+})
+
+test('instance style overrides come back as overrides after saving and reopening', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const card = graph.createNode('COMPONENT', page, { name: 'Card', width: 200, height: 100 })
+ graph.createNode('RECTANGLE', card.id, { name: 'Bar', width: 100, height: 10, strokeWeight: 1 })
+ graph.createNode('TEXT', card.id, { name: 'Label', text: 'Hello world', fontSize: 12 })
+ const instance = expectDefined(graph.createInstance(card.id, page))
+ const [bar, label] = graph.getChildren(instance.id)
+ graph.updateNode(bar.id, { strokeWeight: 6, cornerSmoothing: 0.6 })
+ recordInstanceOverride(graph, bar.id, ['strokeWeight', 'cornerSmoothing'])
+ graph.updateNode(label.id, {
+ letterSpacing: 2,
+ styleRuns: [{ start: 0, length: 5, style: { fontSize: 30 } }]
+ })
+ recordInstanceOverride(graph, label.id, ['letterSpacing', 'styleRuns'])
+
+ const reopened = await parseFigFile((await exportFigFile(graph)).slice().buffer)
+ const nodes = [...reopened.getAllNodes()]
+ const copy = expectDefined(nodes.find((node) => node.type === 'INSTANCE'), 'reopened instance')
+ const component = expectDefined(nodes.find((node) => node.type === 'COMPONENT'))
+ const [reopenedBar, reopenedLabel] = reopened.getChildren(copy.id)
+ expect(reopenedBar.strokeWeight).toBe(6)
+ // Kiwi stores it as a 32-bit float, as Figma does.
+ expect(reopenedBar.cornerSmoothing).toBeCloseTo(0.6)
+ expect(reopenedLabel.letterSpacing).toBe(2)
+ expect(reopenedLabel.styleRuns).toEqual([
+ expect.objectContaining({ start: 0, length: 5, style: expect.objectContaining({ fontSize: 30 }) })
+ ])
+ for (const [layer, field] of [
+ [reopenedBar, 'strokeWeight'],
+ [reopenedBar, 'cornerSmoothing'],
+ [reopenedLabel, 'letterSpacing'],
+ [reopenedLabel, 'styleRuns']
+ ] as const)
+ expect(hasInstanceOverride(reopened, layer.id, field)).toBe(true)
+
+ // The reopened overrides hold through an edit to the component; the rest follows it.
+ const [componentBar, componentLabel] = reopened.getChildren(component.id)
+ reopened.updateNode(componentBar.id, { strokeWeight: 3, strokeAlign: 'OUTSIDE' })
+ reopened.updateNode(componentLabel.id, { letterSpacing: 5, textCase: 'UPPER' })
+ reopened.syncInstances(component.id)
+ expect([reopenedBar.strokeWeight, reopenedBar.strokeAlign]).toEqual([6, 'OUTSIDE'])
+ expect([reopenedLabel.letterSpacing, reopenedLabel.textCase]).toEqual([2, 'UPPER'])
+})
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 531a512d7..3c50a81f3 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -209,6 +209,7 @@ Common node properties are readable/writable through the proxy, including:
- `figma.getNodeByIdAsync(id)` and `instance.getMainComponentAsync()` resolve to the same nodes as `figma.getNodeById(id)` and `instance.mainComponent`, for scripts written for Figma's dynamic-page mode
- `figma.notify(message)` logs a warning in headless mode
- `instance.swapComponent(component)` points an instance at another component
+- A layer inside an instance refuses `x`, `y`, `rotation`, `relativeTransform`, `constraints`, `isMask`, and `maskType` with Figma's error, such as `in set_x: This property cannot be overridden in an instance: relative-transform`; those always follow the component. Slot content keeps them, and setting one on a slot's default content makes the instance own the slot
- `component.createSlot()` adds a slot frame and its `SLOT` property; slot frames read `type: 'SLOT'`, `resetSlot()` brings back an instance slot's component content, and `limitViolations` lists the limits an instance slot breaks. `addComponentProperty` and `editComponentProperty` take a `description` and, for slots, `slotSettings`
- `figma.viewport`
diff --git a/packages/docs/ru/user-guide/components.md b/packages/docs/ru/user-guide/components.md
index b3b3ff11c..2be90f99f 100644
--- a/packages/docs/ru/user-guide/components.md
+++ b/packages/docs/ru/user-guide/components.md
@@ -100,13 +100,9 @@ OpenPencil сохраняет совместимые назначения тек
## Синхронизация
-После изменения компонента связанные экземпляры обновляются автоматически. Синхронизируются:
+После изменения компонента связанные экземпляры обновляются автоматически, как в Figma: каждое свойство, которое экземпляр не переопределил, следует за компонентом. Это размер, заливки, обводки с их толщиной, положением, окончаниями, соединениями и пунктиром, эффекты, прозрачность, режим наложения, радиусы и сглаживание углов, параметры компоновки и сетки, обрезка содержимого, общие стили и текст — от шрифта и размера до межбуквенного интервала, высоты строки, регистра, оформления, выравнивания и стилей фрагментов.
-- ширина и высота;
-- заливки, обводки и эффекты;
-- прозрачность и радиусы углов;
-- параметры компоновки;
-- обрезка содержимого.
+Дочерний объект экземпляра также берёт у компонента положение, поворот, отражение, привязки и маску. Если сдвинуть или повернуть объект в компоненте, он сдвинется во всех экземплярах. Если размер экземпляра отличается от размера компонента, объект размещается по своим привязкам: объект, привязанный к правому краю, сохраняет расстояние до него. Внутри автокомпоновки объект размещает компоновка.
Синхронизация выполняется после изменения, перемещения или изменения размера дочерних объектов компонента.
@@ -114,7 +110,9 @@ OpenPencil сохраняет совместимые назначения тек
Экземпляр может переопределять отдельные свойства, не разрывая связь с компонентом. При следующей синхронизации переопределённое свойство сохраняется, а остальные продолжают обновляться из основного компонента.
-Для дочерних объектов можно переопределить имя, текст, размер, начертание и семейство шрифта, а также визуальные свойства и параметры компоновки: заливки, обводки, эффекты, прозрачность, радиусы углов и размеры.
+Для дочерних объектов можно переопределить имя, текст, стили фрагментов и шрифт, все визуальные и текстовые свойства из списка выше, размер, видимость и блокировку. Положение, поворот, отражение, привязки и маску переопределить нельзя: они всегда берутся из компонента. Скрипты, которые меняют положение, поворот, привязки или маску, получают ошибку Figma. Содержимое слота принадлежит экземпляру и остаётся редактируемым.
+
+Переопределения из файла `.fig` при открытии остаются переопределениями и сохраняются так, как их записывает Figma.
Если добавить дочерний объект в компонент, его копия автоматически появится во всех существующих экземплярах. Порядок дочерних объектов соответствует основному компоненту.
diff --git a/packages/docs/user-guide/components.md b/packages/docs/user-guide/components.md
index e32d1de35..8228e9686 100644
--- a/packages/docs/user-guide/components.md
+++ b/packages/docs/user-guide/components.md
@@ -118,13 +118,9 @@ Right-click an instance and select **Go to main component**. The editor navigate
## Live Sync
-When you edit a component, all its instances update automatically. Synced properties include:
+When you edit a component, all its instances update automatically, as in Figma: every property an instance does not override follows the component. That covers size, fills, strokes and their weight, alignment, caps, joins, and dashes, effects, opacity, blend mode, corner radii and smoothing, layout settings and grids, clipping, shared styles, and text, from its font and size to letter spacing, line height, case, decoration, alignment, and styled ranges.
-- Width and height
-- Fills, strokes, and effects
-- Opacity and corner radii
-- Layout properties (auto layout settings)
-- Clips content setting
+A layer inside an instance also takes its position, rotation, flips, constraints, and mask from the component. Move or rotate a layer in the component and it moves in every instance. When an instance has a different size than its component, the layer is placed by its constraints, so a layer pinned to the right keeps its distance from the right edge. Inside auto layout, the layout places it.
Sync triggers automatically after node updates, moves, and resizes within a component.
@@ -134,7 +130,9 @@ Instances can override specific properties without breaking the sync link. When
### Overridable Properties
-Child-level overrides support: name, text, font size, font weight, font family, plus all visual and layout properties (fills, strokes, effects, opacity, corner radii, size).
+A layer inside an instance can override its name, text, styled ranges, and font, every visual and text property listed above, its size, and whether it is visible or locked. Its position, rotation, flips, constraints, and mask cannot be overridden: they always come from the component. Scripts that set its position, rotation, constraints, or mask get Figma's error. Slot content is the instance's own and stays editable.
+
+Overrides in a `.fig` file come back as overrides when you open it, and are saved the way Figma writes them.
### New Children
diff --git a/packages/fig/src/instance-overrides/fields.ts b/packages/fig/src/instance-overrides/fields.ts
index f01092314..a136c6967 100644
--- a/packages/fig/src/instance-overrides/fields.ts
+++ b/packages/fig/src/instance-overrides/fields.ts
@@ -1,3 +1,5 @@
+import { groupBy } from 'es-toolkit'
+
import type { SceneNode } from '@open-pencil/scene-graph'
/**
@@ -16,8 +18,14 @@ export interface OverrideField {
| 'size'
| 'layout-distance'
| 'layout-mode'
+ | 'node'
/** A placed-space distance that an instance's uniform scale multiplies. */
readonly length?: true
+ /**
+ * For `node` claims: the value Figma reads when the record leaves the field out, written
+ * explicitly so a claim of the default still overrides the component.
+ */
+ readonly absent?: unknown
}
/** Raw override fields an instance owner may claim, keyed by their Kiwi name. */
@@ -26,7 +34,8 @@ export const OVERRIDE_FIELDS = {
opacity: { scene: ['opacity'], kind: 'scalar' },
fontSize: { scene: ['fontSize'], kind: 'scalar', length: true },
visible: { scene: ['visible'], kind: 'visible' },
- textData: { scene: ['text'], kind: 'text' },
+ // Figma claims styled ranges and list lines with the characters (desktop 126).
+ textData: { scene: ['text', 'styleRuns', 'textParagraphs'], kind: 'text' },
styleIdForText: { scene: ['textStyleId'], kind: 'text-style' },
fillPaints: { scene: ['fills'], kind: 'paint' },
strokePaints: { scene: ['strokes'], kind: 'paint' },
@@ -41,7 +50,66 @@ export const OVERRIDE_FIELDS = {
stackChildPrimaryGrow: { scene: ['layoutGrow'], kind: 'layout-mode' },
stackPrimarySizing: { scene: ['primaryAxisSizing'], kind: 'layout-mode' },
stackCounterSizing: { scene: ['counterAxisSizing'], kind: 'layout-mode' },
- stackChildAlignSelf: { scene: ['layoutAlignSelf'], kind: 'layout-mode' }
+ stackChildAlignSelf: { scene: ['layoutAlignSelf'], kind: 'layout-mode' },
+ // Claimed as the layer's own record writes them (Figma desktop 126 claim encoding).
+ cornerRadius: { scene: ['cornerRadius'], kind: 'node', length: true, absent: 0 },
+ rectangleTopLeftCornerRadius: { scene: ['topLeftRadius'], kind: 'node', length: true, absent: 0 },
+ rectangleTopRightCornerRadius: {
+ scene: ['topRightRadius'],
+ kind: 'node',
+ length: true,
+ absent: 0
+ },
+ rectangleBottomRightCornerRadius: {
+ scene: ['bottomRightRadius'],
+ kind: 'node',
+ length: true,
+ absent: 0
+ },
+ rectangleBottomLeftCornerRadius: {
+ scene: ['bottomLeftRadius'],
+ kind: 'node',
+ length: true,
+ absent: 0
+ },
+ rectangleCornerRadiiIndependent: { scene: ['independentCorners'], kind: 'node', absent: false },
+ cornerSmoothing: { scene: ['cornerSmoothing'], kind: 'node', absent: 0 },
+ strokeWeight: { scene: ['strokeWeight'], kind: 'node', length: true },
+ strokeAlign: { scene: ['strokeAlign'], kind: 'node', absent: 'CENTER' },
+ borderTopWeight: { scene: ['borderTopWeight'], kind: 'node', length: true },
+ borderRightWeight: { scene: ['borderRightWeight'], kind: 'node', length: true },
+ borderBottomWeight: { scene: ['borderBottomWeight'], kind: 'node', length: true },
+ borderLeftWeight: { scene: ['borderLeftWeight'], kind: 'node', length: true },
+ borderStrokeWeightsIndependent: {
+ scene: ['independentStrokeWeights'],
+ kind: 'node',
+ absent: false
+ },
+ strokeCap: { scene: ['strokeCap'], kind: 'node', absent: 'NONE' },
+ strokeJoin: { scene: ['strokeJoin'], kind: 'node', absent: 'MITER' },
+ miterLimit: { scene: ['strokeMiterLimit'], kind: 'node' },
+ dashPattern: { scene: ['dashPattern'], kind: 'node', length: true, absent: [] },
+ blendMode: { scene: ['blendMode'], kind: 'node', absent: 'PASS_THROUGH' },
+ effects: { scene: ['effects'], kind: 'node', absent: [] },
+ locked: { scene: ['locked'], kind: 'node', absent: false },
+ layoutGrids: { scene: ['layoutGrids'], kind: 'node', absent: [] },
+ styleIdForFill: { scene: ['fillStyleId'], kind: 'node' },
+ styleIdForStrokeFill: { scene: ['strokeStyleId'], kind: 'node' },
+ styleIdForEffect: { scene: ['effectStyleId'], kind: 'node' },
+ stackPrimaryAlignItems: { scene: ['primaryAxisAlign'], kind: 'node' },
+ stackCounterAlignItems: { scene: ['counterAxisAlign'], kind: 'node' },
+ stackPositioning: { scene: ['layoutPositioning'], kind: 'node' },
+ fontName: { scene: ['fontFamily', 'fontWeight', 'italic'], kind: 'node' },
+ fontVariations: { scene: ['fontVariations'], kind: 'node', absent: [] },
+ lineHeight: { scene: ['lineHeight'], kind: 'node', absent: { value: 100, units: 'PERCENT' } },
+ letterSpacing: { scene: ['letterSpacing'], kind: 'node' },
+ paragraphSpacing: { scene: ['paragraphSpacing'], kind: 'node', length: true, absent: 0 },
+ textCase: { scene: ['textCase'], kind: 'node', absent: 'ORIGINAL' },
+ textDecoration: { scene: ['textDecoration'], kind: 'node', absent: 'NONE' },
+ textAlignHorizontal: { scene: ['textAlignHorizontal'], kind: 'node' },
+ textAlignVertical: { scene: ['textAlignVertical'], kind: 'node' },
+ textTruncation: { scene: ['textTruncation'], kind: 'node', absent: 'DISABLED' },
+ maxLines: { scene: ['maxLines'], kind: 'node' }
} as const satisfies Record<string, OverrideField>
export type RawOverrideField = keyof typeof OVERRIDE_FIELDS
@@ -52,12 +120,20 @@ type RawFieldOfKind<K extends OverrideField['kind']> = {
const entries = Object.entries(OVERRIDE_FIELDS) as [RawOverrideField, OverrideField][]
-/** Scene fields that carry an instance override, with the raw field each serializes to. */
+/** Scene fields that carry an instance override, with the raw fields each serializes to. */
export const SCENE_OVERRIDE_FIELDS: ReadonlyMap<
keyof SceneNode,
- { raw: RawOverrideField; field: OverrideField }
+ readonly { raw: RawOverrideField; field: OverrideField }[]
> = new Map(
- entries.flatMap(([raw, field]) => field.scene.map((scene) => [scene, { raw, field }] as const))
+ Object.entries(
+ groupBy(
+ entries.flatMap(([raw, field]) => field.scene.map((scene) => ({ scene, raw, field }))),
+ (entry) => entry.scene
+ )
+ ).map(([scene, claims]) => [
+ scene as keyof SceneNode,
+ claims.map(({ raw, field }) => ({ raw, field }))
+ ])
)
function rawFieldsOfKind<K extends OverrideField['kind']>(kind: K): RawFieldOfKind<K>[] {
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index 8ffd49775..5dca240ea 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -493,7 +493,9 @@ function applyInstancePayload(
}
mergeOverrides(
symbolOverrides,
- serializeRuntimePropertyOverrides(context, node, localIdCounter)
+ serializeRuntimePropertyOverrides(context, node, localIdCounter, (target) =>
+ overridableNodeFields(context, target)
+ )
)
if (symbolOverrides.length > 0) symbolData.symbolOverrides = symbolOverrides
if (!Number.isFinite(node.componentScale) || node.componentScale <= 0)
@@ -913,6 +915,43 @@ function exportedChildren(node: SceneNode, context: SceneNodeToKiwiContext): Sce
.filter((child) => !child.internalOnly && child.sharedStyleType === null)
}
+/** Stroke geometry and lock state, which a layer's record and its instance claims both write. */
+function applyNodeStateProps(node: SceneNode, nc: KiwiNodeChange): void {
+ // With strokes, their geometry is the node's. Without, the node keeps its own weight and
+ // alignment, written when set or when the source file carried them.
+ if (node.strokes.length > 0) {
+ nc.strokeWeight = node.strokes[0].weight
+ nc.strokeAlign = node.strokes[0].align
+ } else {
+ const rawNodeFields = effectiveFigmaRawNodeFields(node)
+ if (node.strokeWeight !== DEFAULT_STROKE_WEIGHT || 'strokeWeight' in rawNodeFields) {
+ nc.strokeWeight = node.strokeWeight
+ }
+ // Kiwi reads a missing alignment as centered.
+ if (node.strokeAlign !== 'CENTER' || 'strokeAlign' in rawNodeFields) {
+ nc.strokeAlign = node.strokeAlign
+ }
+ }
+ if (node.locked) nc.locked = true
+}
+
+/**
+ * The style fields of a layer as its own record writes them, for the instance override claims
+ * that carry them. Text is written without derived glyphs: a claim never carries them.
+ */
+export function overridableNodeFields(
+ context: SceneNodeToKiwiContext,
+ source: SceneNode
+): KiwiNodeChange {
+ const node = nodeToSerialize(context, source)
+ const nc: KiwiNodeChange = {}
+ if (node.blendMode !== 'PASS_THROUGH') nc.blendMode = node.blendMode
+ applyNodeStateProps(node, nc)
+ applyNodeVisualProps({ ...context, fontDigestMap: undefined }, node, nc)
+ context.serializeLayoutProps(node, nc)
+ return nc
+}
+
export function sceneNodeToKiwiWithContext(
source: SceneNode,
parentGuid: GUID,
@@ -950,23 +989,7 @@ export function sceneNodeToKiwiWithContext(
if (node.type === 'GROUP') {
nc.resizeToFit = true
}
- // With strokes, their geometry is the node's. Without, the node keeps its own weight and
- // alignment, written when set or when the source file carried them.
- if (node.strokes.length > 0) {
- nc.strokeWeight = node.strokes[0].weight
- nc.strokeAlign = node.strokes[0].align
- } else {
- const rawNodeFields = effectiveFigmaRawNodeFields(node)
- if (node.strokeWeight !== DEFAULT_STROKE_WEIGHT || 'strokeWeight' in rawNodeFields) {
- nc.strokeWeight = node.strokeWeight
- }
- // Kiwi reads a missing alignment as centered.
- if (node.strokeAlign !== 'CENTER' || 'strokeAlign' in rawNodeFields) {
- nc.strokeAlign = node.strokeAlign
- }
- }
- if (node.locked) nc.locked = true
-
+ applyNodeStateProps(node, nc)
applyNodeVisualProps(context, node, nc)
applyComponentMetadata(context, node, nc, localIdCounter)
applyInstancePayload(context, node, nc, localIdCounter)
diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.ts
index 92148ce92..19606059a 100644
--- a/packages/fig/src/node-change/export/override-claims.ts
+++ b/packages/fig/src/node-change/export/override-claims.ts
@@ -1,9 +1,11 @@
-import { SCENE_OVERRIDE_FIELDS } from '#fig/instance-overrides/fields'
+import { type OverrideField, SCENE_OVERRIDE_FIELDS } from '#fig/instance-overrides/fields'
+import { compact } from 'es-toolkit'
import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
import {
forEachInstanceOverride,
ownsSlotContent,
+ scaleNodeChanges,
type SceneGraph,
type SceneNode
} from '@open-pencil/scene-graph'
@@ -18,6 +20,7 @@ import {
getOrCreateNodeGuid,
instanceGuidResolver,
isDescendantOf,
+ type KiwiNodeChange,
type KiwiSymbolOverridePayload,
type SceneNodeToKiwiContext,
type StyleReference
@@ -85,6 +88,8 @@ interface ClaimInput {
target: SceneNode
/** The recorded override value, when the override stored one. */
value: unknown
+ /** The target's own record, written once however many of its fields are claimed. */
+ nodeFields: () => KiwiNodeChange
}
/**
@@ -93,18 +98,54 @@ interface ClaimInput {
*/
function registryClaim(
field: keyof SceneNode,
- { context, instance, target, value }: ClaimInput
+ input: ClaimInput
+): Omit<KiwiSymbolOverridePayload, 'guidPath'> | undefined {
+ const entries = SCENE_OVERRIDE_FIELDS.get(field)
+ if (!entries) return undefined
+ const claims = compact(
+ entries.map(({ raw, field: definition }) => rawClaim(raw, definition, field, input))
+ )
+ return claims.length > 0 ? Object.assign({}, ...claims) : undefined
+}
+
+/** Writes the style fields of a layer as its own record does. */
+export type NodeFieldsWriter = (node: SceneNode) => KiwiNodeChange
+
+/** A layer's record in its component's coordinates, which instance claims are written in. */
+function unscaledNodeFields(
+ writeNodeFields: NodeFieldsWriter,
+ instance: SceneNode,
+ target: SceneNode
+): KiwiNodeChange {
+ const scale = instance.componentScale
+ if (!Number.isFinite(scale) || scale <= 0) throw new Error('Invalid instance uniform scale')
+ const unscaled =
+ scale === 1 ? target : { ...target, ...scaleNodeChanges(target, 1 / scale, false) }
+ return writeNodeFields(unscaled)
+}
+
+/** One raw field of a claim, serialized by the kind of its scene field. */
+function rawClaim(
+ raw: string,
+ definition: OverrideField,
+ field: keyof SceneNode,
+ { context, instance, target, value, nodeFields }: 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 'node': {
+ const record = nodeFields()
+ const claimed = raw in record ? record[raw] : definition.absent
+ return claimed === undefined ? undefined : { [raw]: claimed }
+ }
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': {
+ // The characters with their styled ranges and lines, as the layer's own record writes them.
+ const characters = field === 'text' && typeof value === 'string' ? value : target.text
+ return { textData: { ...nodeFields().textData, characters } }
+ }
case 'text-style':
return target.textStyleId
? { styleIdForText: exportedTextStyleReference(context, target.textStyleId) }
@@ -155,15 +196,24 @@ function bindingClaim(
}
function overrideClaim(
- claimed: ClaimInput,
+ claimed: Omit<ClaimInput, 'nodeFields'> & {
+ records: Map<string, KiwiNodeChange>
+ writeNodeFields: NodeFieldsWriter
+ },
field: string,
path: GUID[],
counter: { value: number }
): KiwiSymbolOverridePayload | undefined {
- const input = {
- ...claimed,
- target: exportedNode(claimed.context, claimed.target)
+ const target = exportedNode(claimed.context, claimed.target)
+ const nodeFields = () => {
+ let record = claimed.records.get(target.id)
+ if (!record) {
+ record = unscaledNodeFields(claimed.writeNodeFields, claimed.instance, target)
+ claimed.records.set(target.id, record)
+ }
+ return record
}
+ const input: ClaimInput = { ...claimed, target, nodeFields }
if (field === 'componentId')
return exportedSwapOverride(input.context, input.target, path, counter)
const claim = field.startsWith('boundVariables/')
@@ -176,12 +226,14 @@ function overrideClaim(
export function serializeRuntimePropertyOverrides(
context: SceneNodeToKiwiContext,
instance: SceneNode,
- localIdCounter: { value: number }
+ localIdCounter: { value: number },
+ writeNodeFields: NodeFieldsWriter
): KiwiSymbolOverridePayload[] {
const result: KiwiSymbolOverridePayload[] = []
const resolveGuid = instanceGuidResolver(context, localIdCounter)
// A layer with several overridden fields is addressed once; the resolver keeps the GUIDs it makes.
const targets = new Map<string, { target: SceneNode; path: GUID[] } | undefined>()
+ const records = new Map<string, KiwiNodeChange>()
const findTarget = (targetId: string) => {
const target = context.graph.getNode(targetId)
if (!target || (target.id !== instance.id && !isDescendantOf(context, targetId, instance.id)))
@@ -201,7 +253,7 @@ export function serializeRuntimePropertyOverrides(
const resolved = resolveTarget(node, nodeId)
if (!resolved) return
const claim = overrideClaim(
- { context, instance, target: resolved.target, value },
+ { context, instance, target: resolved.target, value, records, writeNodeFields },
field,
resolved.path,
localIdCounter
diff --git a/packages/fig/tests/instance-overrides/style-claims.test.ts b/packages/fig/tests/instance-overrides/style-claims.test.ts
new file mode 100644
index 000000000..1a004a864
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/style-claims.test.ts
@@ -0,0 +1,118 @@
+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 { 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 } from '@open-pencil/scene-graph'
+import { copyStyleRuns } from '@open-pencil/scene-graph/copy'
+
+test('style claims read from a file survive edits to the component, as in Figma', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(1, 4), type: 'SYMBOL' },
+ {
+ guid: guid(2, 4),
+ type: 'RECTANGLE',
+ parentIndex: { guid: guid(1, 4), position: '!' },
+ cornerRadius: 2,
+ strokeWeight: 1
+ },
+ {
+ guid: guid(3, 4),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1, 4), position: '"' },
+ textData: { characters: 'Label' },
+ fontName: { family: 'Inter', style: 'Regular', postscript: '' },
+ lineHeight: { value: 20, units: 'PIXELS' }
+ },
+ {
+ guid: guid(4, 4),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1, 4),
+ symbolOverrides: [
+ { guidPath: { guids: [guid(2, 4)] }, cornerRadius: 12, strokeWeight: 3 },
+ {
+ guidPath: { guids: [guid(3, 4)] },
+ fontName: { family: 'Inter', style: 'Bold', postscript: '' },
+ lineHeight: { value: 32, units: 'PIXELS' }
+ }
+ ]
+ }
+ } as NodeChange
+ ]
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const occurrence = interpretInstance(changes, '4:4')
+ 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('4:1')
+ if (!component) throw new Error('Missing component')
+ const [rect, text] = graph.getChildren(component.materialized.root.id)
+ graph.updateNode(rect.id, { cornerRadius: 4, strokeWeight: 2, strokeAlign: 'OUTSIDE' })
+ graph.updateNode(text.id, { fontWeight: 300, lineHeight: 24, letterSpacing: 1 })
+ graph.syncInstances(component.materialized.root.id)
+
+ const [copyRect, copyText] = graph.getChildren(result.root.id)
+ expect([copyRect.cornerRadius, copyRect.strokeWeight, copyRect.strokeAlign]).toEqual([
+ 12,
+ 3,
+ 'OUTSIDE'
+ ])
+ expect([copyText.fontWeight, copyText.lineHeight, copyText.letterSpacing]).toEqual([700, 32, 1])
+})
+
+test('styled ranges claimed with the characters stay when the component restyles its text', () => {
+ // The claim Figma desktop 126 writes when a script restyles the first word of a copy.
+ const changes: NodeChange[] = [
+ { guid: guid(1, 5), type: 'SYMBOL' },
+ {
+ guid: guid(2, 5),
+ type: 'TEXT',
+ parentIndex: { guid: guid(1, 5), position: '!' },
+ fontSize: 12,
+ textData: { characters: 'Hello world' }
+ },
+ {
+ guid: guid(3, 5),
+ type: 'INSTANCE',
+ symbolData: {
+ symbolID: guid(1, 5),
+ symbolOverrides: [
+ {
+ guidPath: { guids: [guid(2, 5)] },
+ textData: {
+ characters: 'Hello world',
+ characterStyleIDs: [1, 1, 1, 1, 1],
+ styleOverrideTable: [{ styleID: 1, fontSize: 30 }]
+ }
+ }
+ ]
+ }
+ } as NodeChange
+ ]
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const occurrence = interpretInstance(changes, '5: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('5:1')
+ if (!component) throw new Error('Missing component')
+ const [copy] = graph.getChildren(result.root.id)
+ const claimed = copyStyleRuns(copy.styleRuns)
+ expect(claimed).toEqual([expect.objectContaining({ start: 0, length: 5 })])
+
+ const [text] = graph.getChildren(component.materialized.root.id)
+ graph.updateNode(text.id, { styleRuns: [{ start: 6, length: 5, style: { fontSize: 8 } }] })
+ graph.syncInstances(component.materialized.root.id)
+ expect(copy.styleRuns).toEqual(claimed)
+})
diff --git a/packages/fig/tests/node-change/export.test.ts b/packages/fig/tests/node-change/export.test.ts
index a3bba6484..47bfc9777 100644
--- a/packages/fig/tests/node-change/export.test.ts
+++ b/packages/fig/tests/node-change/export.test.ts
@@ -94,10 +94,131 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
)
expect(sourceText.overrideKey).toBe('2:20')
+ // Figma writes a text claim with its lines, as the layer's own record has them.
expect(symbolDataOf(change)?.symbolOverrides).toEqual([
{
...originalOverride,
- textData: { characters: 'Edited' }
+ textData: {
+ characters: 'Edited',
+ lines: [
+ {
+ indentationLevel: 0,
+ isFirstLineOfList: false,
+ lineType: 'PLAIN',
+ listStartOffset: 0,
+ sourceDirectionality: 'AUTO',
+ styleId: 0
+ }
+ ]
+ }
+ }
+ ])
+ })
+
+ test('writes styled ranges with the characters of a text claim, as Figma does', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id)
+ graph.createNode('TEXT', component.id, {
+ overrideKey: '2:20',
+ text: 'Hello world',
+ fontSize: 12
+ })
+ const instance = expectDefined(graph.createInstance(component.id, page.id), 'instance')
+ const [text] = graph.getChildren(instance.id)
+ // Recorded by a script that restyles the first word only; the characters are unchanged.
+ graph.updateNode(text.id, { styleRuns: [{ start: 0, length: 5, style: { fontSize: 30 } }] })
+ graph.updateNode(instance.id, {
+ instanceOverrides: {
+ self: new Map(),
+ descendants: new Map([[text.id, new Map<string, unknown>([['styleRuns', text.styleRuns]])]])
+ }
+ })
+
+ const [change] = sceneNodeToKiwi(
+ instance,
+ { sessionID: 1, localID: 1 },
+ 0,
+ { value: 2 },
+ graph,
+ []
+ )
+
+ const [claim] = symbolDataOf(change)?.symbolOverrides ?? []
+ // The first word takes style 1; the rest keep the layer's own style, 0.
+ expect(claim.textData).toMatchObject({
+ characters: 'Hello world',
+ characterStyleIDs: [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
+ styleOverrideTable: [expect.objectContaining({ styleID: 1, fontSize: 30 })]
+ })
+ })
+
+ test('writes style overrides as the layer’s own record claims them, in the component’s scale', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id)
+ graph.createNode('RECTANGLE', component.id, { overrideKey: '2:20', strokeWeight: 2 })
+ graph.createNode('TEXT', component.id, { overrideKey: '2:21', text: 'A', lineHeight: 30 })
+ const instance = expectDefined(graph.createInstance(component.id, page.id), 'instance')
+ const [rect, text] = graph.getChildren(instance.id)
+ // Placed at twice the component's size, as a scaled instance is.
+ graph.updateNode(instance.id, { componentScale: 2 })
+ graph.updateNode(rect.id, { strokeWeight: 8, strokeAlign: 'CENTER', cornerSmoothing: 0.6 })
+ graph.updateNode(text.id, { lineHeight: null, letterSpacing: 4 })
+ graph.updateNode(instance.id, {
+ instanceOverrides: {
+ self: new Map(),
+ descendants: new Map([
+ [
+ rect.id,
+ new Map<string, unknown>([
+ ['strokeWeight', 8],
+ ['strokeAlign', 'CENTER'],
+ ['cornerSmoothing', 0.6]
+ ])
+ ],
+ [
+ text.id,
+ new Map<string, unknown>([
+ ['lineHeight', null],
+ ['letterSpacing', 4]
+ ])
+ ]
+ ])
+ },
+ source: {
+ ...instance.source,
+ fig: {
+ ...instance.source.fig,
+ // A stale claim read from the file, replaced by the edit.
+ symbolOverrides: [
+ { guidPath: { guids: [{ sessionID: 2, localID: 20 }] }, strokeWeight: 1 }
+ ]
+ }
+ }
+ })
+
+ const [change] = sceneNodeToKiwi(
+ graph.getNode(instance.id) ?? instance,
+ { sessionID: 1, localID: 1 },
+ 0,
+ { value: 2 },
+ graph,
+ []
+ )
+
+ expect(symbolDataOf(change)?.symbolOverrides).toEqual([
+ {
+ guidPath: { guids: [{ sessionID: 2, localID: 20 }] },
+ strokeWeight: 4,
+ // Figma reads a missing alignment as centred, so the claim spells it out.
+ strokeAlign: 'CENTER',
+ cornerSmoothing: 0.6
+ },
+ {
+ guidPath: { guids: [{ sessionID: 2, localID: 21 }] },
+ lineHeight: { value: 100, units: 'PERCENT' },
+ letterSpacing: { value: 2, units: 'PIXELS' }
}
])
})
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 7e1ebfe43..99922204a 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -51,6 +51,8 @@ export {
copyInstanceComponentProps,
findInstanceAncestor,
hasInstanceOverride,
+ INSTANCE_FOLLOWED_FIELDS,
+ INSTANCE_OVERRIDE_FIELDS,
INSTANCE_SYNC_FIELDS,
INSTANCE_SYNC_PROPS,
INSTANCE_SYNC_TEXT_PROPS,
diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.ts
index 8c0a602ef..88372a8c7 100644
--- a/packages/scene-graph/src/instances.ts
+++ b/packages/scene-graph/src/instances.ts
@@ -12,7 +12,7 @@ import {
removeLeftoverCopies
} from './instances/copies'
import { canCreateInstance } from './instances/cycles'
-import { INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS } from './instances/fields'
+import { INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_PROPS } from './instances/fields'
import {
bindingProtection,
cloneChildrenWithMapping,
@@ -28,6 +28,8 @@ import { detachOwnedSlotContent, restoreOwnedSlotContent } from './slots/frames'
export type { NodeCloneMode } from './copy'
export {
+ INSTANCE_FOLLOWED_FIELDS,
+ INSTANCE_OVERRIDE_FIELDS,
INSTANCE_SYNC_FIELDS,
INSTANCE_SYNC_PROPS,
INSTANCE_SYNC_TEXT_PROPS
@@ -259,7 +261,7 @@ export function recordInstanceOverride(
if (!instance) return
const relevant = [...fields].filter((field) =>
- (INSTANCE_SYNC_FIELDS as readonly string[]).includes(field)
+ (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field)
)
if (relevant.length === 0) return
diff --git a/packages/scene-graph/src/instances/fields.ts b/packages/scene-graph/src/instances/fields.ts
index 0e05a7c10..6215618eb 100644
--- a/packages/scene-graph/src/instances/fields.ts
+++ b/packages/scene-graph/src/instances/fields.ts
@@ -6,9 +6,40 @@ export const INSTANCE_SYNC_TEXT_PROPS = [
'fontSize',
'fontWeight',
'fontFamily',
- 'textDirection'
+ 'italic',
+ 'textDirection',
+ 'letterSpacing',
+ 'lineHeight',
+ 'textCase',
+ 'textDecoration',
+ 'textDecorationStyle',
+ 'textDecorationThickness',
+ 'textUnderlineOffset',
+ 'textDecorationFills',
+ 'textDecorationSkipInk',
+ 'textAlignHorizontal',
+ 'textAlignVertical',
+ 'textAutoResize',
+ 'textTruncation',
+ 'maxLines',
+ 'leadingTrim',
+ 'paragraphSpacing',
+ 'paragraphIndent',
+ 'listSpacing',
+ 'hangingList',
+ 'fontVariations',
+ 'fontFeatures',
+ // Styled ranges belong to the characters: an instance that overrides its text keeps them.
+ 'styleRuns',
+ 'textParagraphs'
] as const
+/** Fields that belong to another one: overriding the owner keeps them too. */
+export const INSTANCE_SYNC_FIELD_OWNERS: Readonly<Partial<Record<string, string>>> = {
+ styleRuns: 'text',
+ textParagraphs: 'text'
+}
+
export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [
'width',
'height',
@@ -46,6 +77,18 @@ export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [
'gridRowGap',
'gridPosition',
'clipsContent',
+ 'counterAxisAlignContent',
+ 'itemReverseZIndex',
+ 'strokesIncludedInLayout',
+ 'layoutGrids',
+ 'blendMode',
+ 'cornerSmoothing',
+ 'strokeWeight',
+ 'strokeAlign',
+ 'strokeCap',
+ 'strokeJoin',
+ 'strokeMiterLimit',
+ 'dashPattern',
'independentStrokeWeights',
'borderTopWeight',
'borderRightWeight',
@@ -61,8 +104,40 @@ export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [
'gridStyleId'
]
-export const INSTANCE_SYNC_FIELDS = [
+/** How a layer inside an instance sits in its parent and whether it is locked, which its overrides may change. */
+export const INSTANCE_SYNC_CHILD_PROPS = ['layoutGrow', 'layoutAlignSelf', 'locked'] as const
+
+/**
+ * Where a component's layer sits and how it is shaped, which Figma refuses to override in an
+ * instance ("This property cannot be overridden in an instance"), so its copies always follow.
+ * A layer in an auto layout flow takes its position from the layout instead.
+ */
+export const INSTANCE_FOLLOWED_FIELDS = [
+ 'x',
+ 'y',
+ 'rotation',
+ 'flipX',
+ 'flipY',
+ 'horizontalConstraint',
+ 'verticalConstraint',
+ 'layoutPositioning',
+ 'isMask',
+ 'maskType',
+ 'arcData',
+ 'pointCount',
+ 'starInnerRadius'
+] as const
+
+/** Fields an edit to a layer inside an instance records as that instance's override. */
+export const INSTANCE_OVERRIDE_FIELDS = [
...INSTANCE_SYNC_PROPS,
...INSTANCE_SYNC_TEXT_PROPS,
+ ...INSTANCE_SYNC_CHILD_PROPS,
'visible'
] as const
+
+/** Fields a component's layer gives the copies of it in every instance. */
+export const INSTANCE_SYNC_FIELDS = [
+ ...INSTANCE_OVERRIDE_FIELDS,
+ ...INSTANCE_FOLLOWED_FIELDS
+] as const
diff --git a/packages/scene-graph/src/instances/placement.ts b/packages/scene-graph/src/instances/placement.ts
new file mode 100644
index 000000000..cb8bbcfd8
--- /dev/null
+++ b/packages/scene-graph/src/instances/placement.ts
@@ -0,0 +1,29 @@
+import type { SceneNode } from '../'
+import { enforcedAspectRatio } from '../layout/aspect-ratio'
+import { layoutConstrainedChildRect } from '../resize'
+
+/** The fields that say where a copy sits in its parent. */
+export const PLACEMENT_FIELDS: ReadonlySet<string> = new Set(['x', 'y', 'width', 'height'])
+
+/**
+ * The component's layer placed in the copy's parent: where its constraints put it when the
+ * instance's frame has another size than the component's, as Figma resizes an instance.
+ */
+export function placedByConstraints(
+ source: SceneNode,
+ compParent: SceneNode,
+ instParent: SceneNode,
+ factor: number
+): SceneNode {
+ const before = { width: compParent.width * factor, height: compParent.height * factor }
+ if (before.width === instParent.width && before.height === instParent.height) return source
+ const rect = layoutConstrainedChildRect(
+ source,
+ before,
+ instParent,
+ source.horizontalConstraint,
+ source.verticalConstraint,
+ enforcedAspectRatio(source)
+ )
+ return { ...source, ...rect }
+}
diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.ts
index ca60ea8bb..b56b788f7 100644
--- a/packages/scene-graph/src/instances/sync.ts
+++ b/packages/scene-graph/src/instances/sync.ts
@@ -20,7 +20,8 @@ import {
unplacedCopy,
type InstanceSyncContext
} from './copies'
-import { INSTANCE_SYNC_FIELDS } from './fields'
+import { INSTANCE_SYNC_FIELD_OWNERS, INSTANCE_SYNC_FIELDS } from './fields'
+import { PLACEMENT_FIELDS, placedByConstraints } from './placement'
function setSceneProp<K extends keyof SceneNode>(
target: Partial<SceneNode>,
@@ -118,6 +119,40 @@ export function sourceInTargetCoordinates(source: SceneNode, targetScale: number
}
}
+interface SyncedFieldsInput {
+ compParent: SceneNode
+ instParent: SceneNode
+ /** The component's coordinates in the copy's. */
+ factor: number
+ /** Fields the copy keeps: overridden, bound, or driven by a property. */
+ skip: (key: string) => boolean
+}
+
+/** The fields a copy takes from its component's layer, placed in the copy's parent. */
+function copySyncedFields(
+ updates: Partial<SceneNode>,
+ copy: SceneNode,
+ source: SceneNode,
+ { compParent, instParent, factor, skip }: SyncedFieldsInput
+): void {
+ // In an auto layout flow the layout places the copy, as it placed the component's layer.
+ const placedByLayout = instParent.layoutMode !== 'NONE' && source.layoutPositioning !== 'ABSOLUTE'
+ const placed = placedByLayout
+ ? source
+ : placedByConstraints(source, compParent, instParent, factor)
+ for (const key of INSTANCE_SYNC_FIELDS) {
+ if (key === 'boundVariables') continue
+ if (placedByLayout && (key === 'x' || key === 'y')) continue
+ if (skip(key)) continue
+ const owner = INSTANCE_SYNC_FIELD_OWNERS[key]
+ if (owner && skip(owner)) continue
+ const from = PLACEMENT_FIELDS.has(key) ? placed : source
+ // Most fields already match: comparing first spares cloning them for nothing.
+ if (isEqual(copy[key], from[key])) continue
+ copyProp(updates, from, key)
+ }
+}
+
export function updateSyncedProps(
graph: SceneGraph,
target: SceneNode,
@@ -539,13 +574,12 @@ export function syncChildren(
componentPropertyReferences: structuredClone(compChild.componentPropertyReferences)
}
syncBindingFields(instChild, source, updates, protectedField)
- for (const key of INSTANCE_SYNC_FIELDS) {
- if (key === 'boundVariables') continue
- if (driven.has(key)) continue
- if (isProtectedSyncField(instChild, key, protectedField)) continue
-
- copyProp(updates, source, key)
- }
+ copySyncedFields(updates, instChild, source, {
+ compParent,
+ instParent,
+ factor: componentScale / compChild.componentScale,
+ skip: (key) => driven.has(key) || isProtectedSyncField(instChild, key, protectedField)
+ })
Object.assign(updates, assignedFieldValues(graph, instChild, compChild))
updateSyncedProps(graph, instChild, updates)
diff --git a/packages/scene-graph/src/layout/aspect-ratio.ts b/packages/scene-graph/src/layout/aspect-ratio.ts
index 9c8de1c16..b80f4ed17 100644
--- a/packages/scene-graph/src/layout/aspect-ratio.ts
+++ b/packages/scene-graph/src/layout/aspect-ratio.ts
@@ -1,5 +1,4 @@
import type { SceneGraph } from '../index'
-import { findInstanceAncestor } from '../instances'
import type { Vector } from '../primitives'
import type { SceneNode } from '../types'
@@ -12,7 +11,7 @@ export function lockedAspectRatioTarget(width: number, height: number): Vector {
/** Whether the lock can change: a layer inside an instance keeps its component's, as in Figma. */
export function aspectRatioLockEditable(graph: SceneGraph, node: SceneNode): boolean {
- return !node.parentId || !findInstanceAncestor(graph, node.parentId)
+ return !node.parentId || !graph.closest(node.parentId, (layer) => layer.type === 'INSTANCE')
}
/**
diff --git a/packages/scene-graph/tests/components/sync-field-contract.test.ts b/packages/scene-graph/tests/components/sync-field-contract.test.ts
index 995bdf3e1..164e3da1a 100644
--- a/packages/scene-graph/tests/components/sync-field-contract.test.ts
+++ b/packages/scene-graph/tests/components/sync-field-contract.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from 'bun:test'
-import { SceneGraph, setInstanceOverride } from '@open-pencil/scene-graph'
+import { SceneGraph, setInstanceOverride, type SceneNode } from '@open-pencil/scene-graph'
import { expectDefined } from '../helpers/assert'
@@ -48,3 +48,80 @@ test('component synchronization updates and removes opacity bindings while prese
expect(instance.boundVariables).toEqual({ width: 'width-var' })
expect(instance.opacity).toBe(1)
})
+
+test('a component edit reaches every field its instances do not override, as in Figma', () => {
+ // Repeats a Figma desktop 126 script: move, rotate, and restyle the component's layers.
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const card = graph.createNode('COMPONENT', page, { width: 200, height: 100 })
+ const dot = graph.createNode('RECTANGLE', card.id, {
+ name: 'Dot',
+ x: 170,
+ y: 10,
+ width: 20,
+ height: 20,
+ horizontalConstraint: 'MAX'
+ })
+ const bar = graph.createNode('RECTANGLE', card.id, {
+ name: 'Bar',
+ x: 20,
+ y: 60,
+ width: 100,
+ height: 10,
+ strokeWeight: 1
+ })
+ const plain = expectDefined(graph.createInstance(card.id, page))
+ const wide = expectDefined(graph.createInstance(card.id, page, { width: 300 }))
+ setInstanceOverride(wide.instanceOverrides, wide.id, wide.id, 'width', 300)
+ const overridden = expectDefined(graph.createInstance(card.id, page))
+ const overriddenBar = graph.getChildren(overridden.id)[1]
+ graph.updateNode(overriddenBar.id, { strokeWeight: 6 })
+ setInstanceOverride(overridden.instanceOverrides, overridden.id, overriddenBar.id, 'strokeWeight', 6)
+
+ graph.updateNode(dot.id, { x: 150, y: 30, rotation: 30 })
+ graph.updateNode(bar.id, { x: 40, strokeWeight: 3, strokeAlign: 'OUTSIDE', cornerSmoothing: 0.6 })
+ graph.syncInstances(card.id)
+
+ const read = (instance: SceneNode) => {
+ const [copyDot, copyBar] = graph.getChildren(instance.id)
+ return {
+ dot: [copyDot.x, copyDot.y, copyDot.rotation],
+ bar: [copyBar.x, copyBar.strokeWeight, copyBar.strokeAlign, copyBar.cornerSmoothing]
+ }
+ }
+ expect(read(plain)).toEqual({ dot: [150, 30, 30], bar: [40, 3, 'OUTSIDE', 0.6] })
+ // A wider instance places the right-pinned dot by its constraint.
+ expect(read(wide).dot).toEqual([250, 30, 30])
+ expect(read(overridden).bar).toEqual([40, 6, 'OUTSIDE', 0.6])
+})
+
+test('a layer in an auto layout flow takes its place from the layout, not the component', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const row = graph.createNode('COMPONENT', page, { layoutMode: 'HORIZONTAL', width: 100, height: 20 })
+ const item = graph.createNode('RECTANGLE', row.id, { x: 0, y: 0, width: 20, height: 20 })
+ const instance = expectDefined(graph.createInstance(row.id, page))
+ const copy = graph.getChildren(instance.id)[0]
+ graph.updateNode(copy.id, { x: 12 })
+ graph.updateNode(item.id, { x: 30, cornerSmoothing: 0.6 })
+ graph.syncInstances(row.id)
+ expect([copy.x, copy.cornerSmoothing]).toEqual([12, 0.6])
+})
+
+test('restyled ranges reach instances, except one that overrides its text', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const label = graph.createNode('COMPONENT', page)
+ const text = graph.createNode('TEXT', label.id, { text: 'Hello' })
+ const plain = expectDefined(graph.createInstance(label.id, page))
+ const instance = expectDefined(graph.createInstance(label.id, page))
+ const copy = graph.getChildren(instance.id)[0]
+ const runs = [{ start: 0, length: 2, style: { fontWeight: 700 } }]
+ graph.updateNode(copy.id, { text: 'Hi there', styleRuns: runs })
+ setInstanceOverride(instance.instanceOverrides, instance.id, copy.id, 'text', 'Hi there')
+ const italic = [{ start: 0, length: 5, style: { italic: true } }]
+ graph.updateNode(text.id, { styleRuns: italic })
+ graph.syncInstances(label.id)
+ expect(graph.getChildren(plain.id)[0].styleRuns).toEqual(italic)
+ expect(copy.styleRuns).toEqual(runs)
+})