Skip to content

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

fix(scene-graph): save the positions and sizes layout writes after an edit (#1525)

Marco Salomoned6d78bc13a99
diff --git a/changes/1525/fixed.md b/changes/1525/fixed.md
new file mode 100644
index 000000000..9f8b6c8c4
--- /dev/null
+++ b/changes/1525/fixed.md
@@ -0,0 +1 @@
+- Saving an opened `.fig` after an edit that re-lays out auto layout, such as changing a gap or adding a layer, keeps where layout moved the other layers and the new size of the hugging frames around them.
diff --git a/packages/core/src/io/formats/pdf/prepare.ts b/packages/core/src/io/formats/pdf/prepare.ts
index 0e380cdd6..838b65cbc 100644
--- a/packages/core/src/io/formats/pdf/prepare.ts
+++ b/packages/core/src/io/formats/pdf/prepare.ts
@@ -49,7 +49,9 @@ export async function preparePagesForPDF(
specs: readonly PDFPageSpec[]
): Promise<DocumentFontStatus> {
const status = await preparePDFFonts(graph, specs)
- for (const spec of specs) computeAllLayouts(graph, spec.pageId)
+ graph.applyDerivedLayoutDuring(() => {
+ for (const spec of specs) computeAllLayouts(graph, spec.pageId)
+ })
return status
}
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
index 31c562c05..b13a25833 100644
--- a/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
+++ b/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
@@ -42,9 +42,8 @@ test('Gold document exposes effective Boolean assignments and supports editor un
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 liveInput = graph.getNode(inputId)
+ if (!liveInput) throw new Error('Missing input')
const editor = createEditor({ graph })
editor.setInstanceComponentProperty(first.id, '4270:0', 'false')
expect(avatar.visible).toBe(false)
@@ -95,9 +94,9 @@ test('Gold document exposes effective Boolean assignments and supports editor un
return avatar?.componentId ? restored.getNode(avatar.componentId)?.name : undefined
})
).toEqual(originalComponents)
- // Setting the property lays the instance out again, which may move the size by float error.
- expect(input.width).toBeCloseTo(originalInputSize.width, 3)
- expect(input.height).toBeCloseTo(originalInputSize.height, 3)
+ // Hiding the avatar lays the hugging input out again, and the file keeps that size.
+ expect(input.width).toBeCloseTo(liveInput.width, 3)
+ expect(input.height).toBeCloseTo(liveInput.height, 3)
expect(
restoredContents.map((node) => {
const avatar = restored
diff --git a/packages/core/tests/io/formats/fig/session/archive-changes.test.ts b/packages/core/tests/io/formats/fig/session/archive-changes.test.ts
index 5ccfa98bb..32f069e1a 100644
--- a/packages/core/tests/io/formats/fig/session/archive-changes.test.ts
+++ b/packages/core/tests/io/formats/fig/session/archive-changes.test.ts
@@ -1,15 +1,30 @@
import { expect, test } from 'bun:test'
+import { createEditor } from '@open-pencil/core'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
import { computeAllLayouts } from '@open-pencil/core/layout'
-import { initCodec } from '@open-pencil/kiwi/fig/codec'
+import { parseFigBuffer } from '@open-pencil/fig'
+import { derivedSymbolDataOf, symbolOverridesOf } from '@open-pencil/fig/instance-overrides'
+import { initCodec, type NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
import { archiveChanges } from '#core/kiwi/fig/session/archive/changes'
+async function reopen(source: SceneGraph) {
+ await initCodec()
+ const graph = await parseFigFile((await exportFigFile(source)).slice().buffer as ArrayBuffer)
+ const page = graph.getPages()[0]
+ const layer = (name: string) => {
+ const found = [...graph.nodes.values()].find((node) => node.name === name)
+ if (!found) throw new Error(`Missing ${name}`)
+ return found
+ }
+ graph.applyDerivedLayoutDuring(() => computeAllLayouts(graph, page.id))
+ return { graph, page, layer }
+}
+
/** A row whose saved child positions are not where auto layout puts them. */
async function openRow() {
- await initCodec()
const source = new SceneGraph()
const row = source.createNode('FRAME', source.getPages()[0].id, {
name: 'Row',
@@ -20,26 +35,56 @@ async function openRow() {
})
for (const name of ['First', 'Second', 'Third'])
source.createNode('RECTANGLE', row.id, { name, x: 0, width: 50, height: 20 })
- const graph = await parseFigFile((await exportFigFile(source)).slice().buffer as ArrayBuffer)
- const page = graph.getPages()[0]
- const layer = (name: string) => {
- const found = [...graph.nodes.values()].find((node) => node.name === name)
- if (!found) throw new Error(`Missing ${name}`)
+ return reopen(source)
+}
+
+/** A hugging column inside a hugging frame, saved with its children at `ys`. */
+async function openColumn(itemSpacing: number, ys: [number, number]) {
+ const source = new SceneGraph()
+ const outer = source.createNode('FRAME', source.getPages()[0].id, {
+ name: 'Outer',
+ layoutMode: 'VERTICAL',
+ primaryAxisSizing: 'HUG',
+ width: 50,
+ height: 20 + 20 + itemSpacing
+ })
+ const column = source.createNode('FRAME', outer.id, {
+ name: 'Column',
+ layoutMode: 'VERTICAL',
+ primaryAxisSizing: 'HUG',
+ itemSpacing,
+ width: 50,
+ height: 20 + 20 + itemSpacing
+ })
+ source.createNode('RECTANGLE', column.id, { name: 'A', y: ys[0], width: 50, height: 20 })
+ source.createNode('RECTANGLE', column.id, { name: 'B', y: ys[1], width: 50, height: 20 })
+ return reopen(source)
+}
+
+async function savedRecords(graph: SceneGraph) {
+ const bytes = await exportFigFile(graph)
+ const records = parseFigBuffer(bytes.slice().buffer as ArrayBuffer).nodeChanges
+ return (name: string): NodeChange => {
+ const found = records.find((record) => record.name === name)
+ if (!found) throw new Error(`Missing saved ${name}`)
return found
}
- return { graph, page, layer }
}
test('the layout a page gets as it loads is no change to its archive', async () => {
- const { graph, page, layer } = await openRow()
- graph.applyDerivedLayoutDuring(() => computeAllLayouts(graph, page.id))
+ const { graph, layer } = await openRow()
expect(layer('Second').x).toBe(60)
expect([...(archiveChanges(graph)?.touched ?? [])]).toEqual([])
})
+test('the layout a page gets as it loads keeps the positions the file saved', async () => {
+ const { graph } = await openRow()
+ const saved = await savedRecords(graph)
+ expect(['First', 'Second', 'Third'].map((name) => saved(name).transform?.m02)).toEqual([0, 0, 0])
+})
+
test('the layout an edit causes changes the layers it moves', async () => {
const { graph, page, layer } = await openRow()
- graph.applyDerivedLayoutDuring(() => computeAllLayouts(graph, page.id))
graph.updateNode(layer('First').id, { width: 80 })
computeAllLayouts(graph, page.id)
const touched = new Set(archiveChanges(graph)?.touched)
@@ -49,3 +94,92 @@ test('the layout an edit causes changes the layers it moves', async () => {
'Third'
])
})
+
+test('a gap edit saves where layout moved the layers after it', async () => {
+ const { graph, page, layer } = await openColumn(12, [0, 32])
+ graph.updateNode(layer('Column').id, { itemSpacing: 40 })
+ computeAllLayouts(graph, page.id)
+ expect(layer('B').y).toBe(60)
+ const saved = await savedRecords(graph)
+ expect(saved('A').transform?.m12).toBe(0)
+ expect(saved('B').transform?.m12).toBe(60)
+ expect(saved('Column').size?.y).toBe(80)
+})
+
+test('a gap edit saves the position layout gives a layer the file saved elsewhere', async () => {
+ const { graph, page, layer } = await openColumn(13, [0, 0])
+ expect(layer('B').y).toBe(33)
+ graph.updateNode(layer('Column').id, { itemSpacing: 12 })
+ computeAllLayouts(graph, page.id)
+ const saved = await savedRecords(graph)
+ expect(saved('B').transform?.m12).toBe(32)
+})
+
+test('a gap edit saves the size of the hugging frames around it', async () => {
+ const { graph, page, layer } = await openColumn(12, [0, 32])
+ graph.updateNode(layer('Column').id, { itemSpacing: 40 })
+ computeAllLayouts(graph, page.id)
+ expect(layer('Outer').height).toBe(80)
+ const saved = await savedRecords(graph)
+ expect(saved('Outer').size?.y).toBe(80)
+ expect(saved('Column').transform?.m12).toBe(0)
+})
+
+test('a gap edit committed from a preview saves the layers its layout moved', async () => {
+ const { graph, layer } = await openColumn(12, [0, 32])
+ const editor = createEditor({ graph })
+ const preview = editor.beginNodePreview('Gap')
+ preview.update(layer('Column').id, { itemSpacing: 40 })
+ preview.commit()
+ expect(layer('B').y).toBe(60)
+ const saved = await savedRecords(graph)
+ expect(saved('B').transform?.m12).toBe(60)
+ expect(saved('Column').size?.y).toBe(80)
+ expect(saved('Outer').size?.y).toBe(80)
+})
+
+/** A component in a set and an instance of it, its layers saved where layout puts them. */
+async function openComponent() {
+ const source = new SceneGraph()
+ const pageId = source.getPages()[0].id
+ const set = source.createNode('COMPONENT_SET', pageId, { name: 'Cards', width: 50, height: 52 })
+ const card = source.createNode('COMPONENT', set.id, {
+ name: 'Size=Small',
+ layoutMode: 'VERTICAL',
+ primaryAxisSizing: 'HUG',
+ itemSpacing: 12,
+ width: 50,
+ height: 52
+ })
+ source.createNode('RECTANGLE', card.id, { name: 'A', width: 50, height: 20 })
+ source.createNode('RECTANGLE', card.id, { name: 'B', y: 32, width: 50, height: 20 })
+ source.createInstance(card.id, pageId, { name: 'Card', x: 100 })
+ return reopen(source)
+}
+
+function geometryOverrides(record: NodeChange) {
+ return symbolOverridesOf(record).filter(
+ (entry) => entry.transform !== undefined || entry.size !== undefined
+ )
+}
+
+test('a component gap edit saves its instances as layout places them, not as overrides', async () => {
+ const { graph, layer } = await openComponent()
+ const editor = createEditor({ graph })
+ editor.updateNodeWithUndo(layer('Size=Small').id, { itemSpacing: 40 })
+ // Component edits reach their instances in a microtask.
+ await Promise.resolve()
+ const instance = layer('Card')
+ expect(instance.height).toBe(80)
+ expect(graph.getChildren(instance.id).map((child) => child.y)).toEqual([0, 60])
+ const saved = await savedRecords(graph)
+ expect(saved('B').transform?.m12).toBe(60)
+ const card = saved('Card')
+ expect(card.size?.y).toBe(80)
+ expect(geometryOverrides(card)).toEqual([])
+ expect(
+ derivedSymbolDataOf(card)
+ .map((entry) => entry.transform?.m12 ?? 0)
+ .toSorted((a, b) => a - b)
+ ).toEqual([0, 60])
+})
diff --git a/packages/scene-graph/src/graph.ts b/packages/scene-graph/src/graph.ts
index 1cedb5444..267c085b1 100644
--- a/packages/scene-graph/src/graph.ts
+++ b/packages/scene-graph/src/graph.ts
@@ -477,7 +477,8 @@ export class SceneGraph {
/**
* Runs `fn` as layout. Its updates are published once the outermost layout ends, still as
- * layout, and without values a pass changed and a later pass put back (`LayoutWrites`).
+ * layout, and without values a pass changed and a later pass put back (`LayoutWrites`). Outside
+ * derived layout, the positions and sizes it publishes count as edited, so formats save them.
*/
withLayoutMutations(fn: () => void): void {
const outermost = this.scopeDepths.layout === 0
@@ -498,8 +499,9 @@ export class SceneGraph {
const writes = this.layoutWrites
this.layoutWrites = null
if (!writes) return
- for (const [id, changes] of writes.updates((nodeId) => this.nodes.get(nodeId))) {
- this.emitter.emit('node:updated', id, changes)
+ for (const [node, changes, edited] of writes.updates((nodeId) => this.nodes.get(nodeId))) {
+ markSourceFieldsEdited(node, edited)
+ this.emitter.emit('node:updated', node.id, changes)
}
}
get isApplyingLayout(): boolean {
@@ -577,7 +579,11 @@ export class SceneGraph {
if (changes.vectorNetwork) {
changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }
}
- this.layoutWrites?.record(node, changes)
+ this.layoutWrites?.record(
+ node,
+ changes,
+ this.scopeDepths.sourceMetadata === 0 && !this.isApplyingDerivedLayout
+ )
Object.assign(node, changes)
if (changes.fills) removeStaleBindings(node, 'fills', changes)
if (changes.strokes) removeStaleBindings(node, 'strokes', changes)
diff --git a/packages/scene-graph/src/layout/writes.ts b/packages/scene-graph/src/layout/writes.ts
index 45839fd90..1664ab021 100644
--- a/packages/scene-graph/src/layout/writes.ts
+++ b/packages/scene-graph/src/layout/writes.ts
@@ -1,8 +1,17 @@
+import { SIZE_FIELDS, TRANSFORM_FIELDS } from '../fields/geometry'
import type { SceneNode } from '../types'
+/** The layout results a format keeps apart from what it saved once an edit moves or sizes. */
+const EDITED_GEOMETRY_FIELDS: ReadonlySet<keyof SceneNode> = new Set([
+ ...TRANSFORM_FIELDS,
+ ...SIZE_FIELDS
+])
+
interface LayerWrites {
before: Partial<SceneNode>
changed: Set<keyof SceneNode>
+ /** Geometry an edit's layout wrote, rather than layout of what the document already holds. */
+ edited: Set<keyof SceneNode>
}
/**
@@ -13,27 +22,29 @@ interface LayerWrites {
export class LayoutWrites {
private readonly layers = new Map<string, LayerWrites>()
- /** Call before `changes` are applied to `node`. */
- record(node: SceneNode, changes: Partial<SceneNode>): void {
+ /** Call before `changes` are applied to `node`; `edit` when an edit's layout writes them. */
+ record(node: SceneNode, changes: Partial<SceneNode>, edit: boolean): void {
let layer = this.layers.get(node.id)
if (!layer) {
- layer = { before: {}, changed: new Set() }
+ layer = { before: {}, changed: new Set(), edited: new Set() }
this.layers.set(node.id, layer)
}
for (const key of Object.keys(changes) as (keyof SceneNode)[]) {
if (!Object.hasOwn(layer.before, key)) Object.assign(layer.before, { [key]: node[key] })
if (!Object.is(node[key], changes[key])) layer.changed.add(key)
+ if (edit && EDITED_GEOMETRY_FIELDS.has(key)) layer.edited.add(key)
}
}
/**
* Each written layer's update: the values layout changed and kept, and values it wrote as they
- * already were, which a preview's commit writes to publish what it showed.
+ * already were, which a preview's commit writes to publish what it showed. With it come the
+ * geometry fields of that update an edit's layout wrote, which count as edited.
*/
*updates(
getNode: (id: string) => SceneNode | undefined
- ): Generator<[string, Partial<SceneNode>]> {
- for (const [id, { before, changed }] of this.layers) {
+ ): Generator<[SceneNode, Partial<SceneNode>, (keyof SceneNode)[]]> {
+ for (const [id, { before, changed, edited }] of this.layers) {
const node = getNode(id)
if (!node) continue
const changes: Partial<SceneNode> = {}
@@ -41,7 +52,8 @@ export class LayoutWrites {
if (changed.has(key) && Object.is(node[key], before[key])) continue
Object.assign(changes, { [key]: node[key] })
}
- if (Object.keys(changes).length > 0) yield [id, changes]
+ const keys = Object.keys(changes) as (keyof SceneNode)[]
+ if (keys.length > 0) yield [node, changes, keys.filter((key) => edited.has(key))]
}
}
}
diff --git a/packages/scene-graph/tests/basic/layout-updates.test.ts b/packages/scene-graph/tests/basic/layout-updates.test.ts
index 649e776cd..70b90f08f 100644
--- a/packages/scene-graph/tests/basic/layout-updates.test.ts
+++ b/packages/scene-graph/tests/basic/layout-updates.test.ts
@@ -96,3 +96,51 @@ describe('updates made by layout', () => {
expect(updates.map(({ changes }) => changes)).toEqual([{ x: 5 }, { x: 0 }])
})
})
+
+describe('geometry layout writes after an edit', () => {
+ const edited = (graph: SceneGraph, id: string) => graph.getNode(id)?.source.editedFields
+
+ test('count as edited, so formats save them', () => {
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Card', 0, 0)
+
+ graph.withLayoutMutations(() => graph.updateNode(id, { y: 12, primaryAxisSizing: 'FIXED' }))
+
+ expect(edited(graph, id)).toEqual(['y'])
+ })
+
+ test('do not count when layout lays out what the document already holds', () => {
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Card', 0, 0)
+
+ graph.applyDerivedLayoutDuring(() =>
+ graph.withLayoutMutations(() => graph.updateNode(id, { y: 12 }))
+ )
+ graph.preserveSourceMetadataDuring(() =>
+ graph.withLayoutMutations(() => graph.updateNode(id, { x: 4 }))
+ )
+
+ expect(edited(graph, id)).toEqual([])
+ })
+
+ test('do not count for values layout changed and then put back', () => {
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Card', 8, 0)
+
+ graph.withLayoutMutations(() => {
+ graph.updateNode(id, { x: -1 })
+ graph.updateNode(id, { x: 8 })
+ })
+
+ expect(edited(graph, id)).toEqual([])
+ })
+
+ test('count for a value written as it already was, as a preview commits what it showed', () => {
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Card', 0, 0)
+
+ graph.withLayoutMutations(() => graph.updateNode(id, { x: 0 }))
+
+ expect(edited(graph, id)).toEqual(['x'])
+ })
+})