Skip to content

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

perf(scene-graph): publish layout updates once, without values that came back (#1279)

Danila Poyarkov80fe7a9ce775
diff --git a/changes/1279/performance.md b/changes/1279/performance.md
new file mode 100644
index 000000000..722576842
--- /dev/null
+++ b/changes/1279/performance.md
@@ -0,0 +1 @@
+- Laying out a page no longer reports layers it leaves where they were, so revisiting a large page skips rebuilding the layers list, font status and Lint results.
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index b3c358d23..6be61edd7 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -106,6 +106,7 @@ import { bindNodeEvents } from './events'
import * as HitTest from './hit-test'
export type { DropTargetOptions } from './hit-test'
import * as Instances from './instances'
+import { LayoutWrites } from './layout/writes'
import Matrix, { type Mat3 } from './matrix'
import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'
import { updateNodePreview, type NodePreviewObserver } from './preview'
@@ -218,6 +219,7 @@ export class SceneGraph {
private importedStateApplicationDepth = 0
private importedIdGenerator: (() => string) | undefined
private layoutMutationDepth = 0
+ private layoutWrites: LayoutWrites | null = null
private derivedLayoutDepth = 0
positionPreviewVersion = 0
instanceIndex = new Map<string, Set<string>>()
@@ -635,12 +637,31 @@ export class SceneGraph {
return this.derivedLayoutDepth > 0
}
+ /**
+ * 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`).
+ */
withLayoutMutations(fn: () => void): void {
+ const outermost = this.layoutMutationDepth === 0
this.layoutMutationDepth++
+ if (outermost) this.layoutWrites = new LayoutWrites()
try {
fn()
} finally {
- this.layoutMutationDepth--
+ try {
+ if (outermost) this.publishLayoutUpdates()
+ } finally {
+ this.layoutMutationDepth--
+ }
+ }
+ }
+
+ private publishLayoutUpdates(): void {
+ 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)
}
}
get isApplyingLayout(): boolean {
@@ -717,11 +738,17 @@ export class SceneGraph {
if (changes.vectorNetwork) {
changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }
}
+ this.layoutWrites?.record(node, changes)
Object.assign(node, changes)
if (changes.fills) removeStaleBindings(node, 'fills', changes)
if (changes.strokes) removeStaleBindings(node, 'strokes', changes)
for (const key of absent) Reflect.deleteProperty(node, key)
- this.emitter.emit('node:updated', id, changes)
+ this.publishNodeUpdate(id, changes)
+ }
+
+ /** Publishes an update now, or leaves it to the running layout, which publishes once it ends. */
+ private publishNodeUpdate(id: string, changes: Partial<SceneNode>): void {
+ if (!this.layoutWrites) this.emitter.emit('node:updated', id, changes)
}
reparentNode(nodeId: string, newParentId: string): void {
diff --git a/packages/scene-graph/src/layout/writes.ts b/packages/scene-graph/src/layout/writes.ts
new file mode 100644
index 000000000..45839fd90
--- /dev/null
+++ b/packages/scene-graph/src/layout/writes.ts
@@ -0,0 +1,47 @@
+import type { SceneNode } from '../types'
+
+interface LayerWrites {
+ before: Partial<SceneNode>
+ changed: Set<keyof SceneNode>
+}
+
+/**
+ * What one layout run writes to each layer: the values before its first write, and the keys it
+ * actually changed. Layout passes can size a layer and size it back, such as a frame laid out on
+ * its own and then by its parent, so a key that changed and came back is left out of the update.
+ */
+export class LayoutWrites {
+ private readonly layers = new Map<string, LayerWrites>()
+
+ /** Call before `changes` are applied to `node`. */
+ record(node: SceneNode, changes: Partial<SceneNode>): void {
+ let layer = this.layers.get(node.id)
+ if (!layer) {
+ layer = { before: {}, changed: 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)
+ }
+ }
+
+ /**
+ * 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.
+ */
+ *updates(
+ getNode: (id: string) => SceneNode | undefined
+ ): Generator<[string, Partial<SceneNode>]> {
+ for (const [id, { before, changed }] of this.layers) {
+ const node = getNode(id)
+ if (!node) continue
+ const changes: Partial<SceneNode> = {}
+ for (const key of Object.keys(before) as (keyof SceneNode)[]) {
+ 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]
+ }
+ }
+}
diff --git a/packages/scene-graph/tests/basic/layout-updates.test.ts b/packages/scene-graph/tests/basic/layout-updates.test.ts
new file mode 100644
index 000000000..649e776cd
--- /dev/null
+++ b/packages/scene-graph/tests/basic/layout-updates.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+import { rect } from './helpers'
+
+/** Records each published update with whether it arrived while layout was still applying. */
+function recordUpdates(graph: SceneGraph) {
+ const updates: { id: string; changes: Partial<SceneNode>; duringLayout: boolean }[] = []
+ graph.onNodeEvents({
+ updated: (id, changes) =>
+ updates.push({ id, changes: { ...changes }, duringLayout: graph.isApplyingLayout })
+ })
+ return updates
+}
+
+describe('updates made by layout', () => {
+ test('are published once, with the values the layout ended on', () => {
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Card', 0, 0)
+ const updates = recordUpdates(graph)
+
+ graph.withLayoutMutations(() => {
+ graph.updateNode(id, { width: 40 })
+ graph.updateNode(id, { width: 60, height: 30 })
+ expect(updates).toEqual([])
+ })
+
+ expect(updates).toEqual([{ id, changes: { width: 60, height: 30 }, duringLayout: true }])
+ })
+
+ test('are not published for values layout changed and then put back', () => {
+ // Bottom-up layout sizes a frame on its own, then its parent's pass sizes it back.
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Content', 8, 0)
+ const { height } = graph.getNode(id) ?? { height: 0 }
+ const updates = recordUpdates(graph)
+
+ graph.withLayoutMutations(() => {
+ graph.updateNode(id, { x: -1, height: 36 })
+ graph.updateNode(id, { x: 8, height })
+ })
+
+ expect(updates).toEqual([])
+ expect(graph.getNode(id)?.x).toBe(8)
+ })
+
+ test('still publish a value written as it already was', () => {
+ // A preview shows its layout in place, then commits by writing those values again.
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Card', 0, 0)
+ const updates = recordUpdates(graph)
+
+ graph.withLayoutMutations(() => graph.updateNode(id, { x: 0 }))
+
+ expect(updates).toEqual([{ id, changes: { x: 0 }, duringLayout: true }])
+ })
+
+ test('are published when the outermost layout ends', () => {
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Card', 0, 0)
+ const updates = recordUpdates(graph)
+
+ graph.withLayoutMutations(() => {
+ graph.withLayoutMutations(() => graph.updateNode(id, { x: 20 }))
+ expect(updates).toEqual([])
+ })
+
+ expect(updates).toEqual([{ id, changes: { x: 20 }, duringLayout: true }])
+ })
+
+ test('are still published when layout throws, since the layers already changed', () => {
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Card', 0, 0)
+ const updates = recordUpdates(graph)
+
+ expect(() =>
+ graph.withLayoutMutations(() => {
+ graph.updateNode(id, { y: 12 })
+ throw new Error('Layout failed')
+ })
+ ).toThrow('Layout failed')
+
+ expect(updates).toEqual([{ id, changes: { y: 12 }, duringLayout: true }])
+ expect(graph.isApplyingLayout).toBe(false)
+ })
+
+ test('leave edits outside layout published as they happen', () => {
+ const graph = new SceneGraph()
+ const id = rect(graph, 'Card', 0, 0)
+ const updates = recordUpdates(graph)
+
+ graph.updateNode(id, { x: 5 })
+ graph.updateNode(id, { x: 0 })
+
+ expect(updates.map(({ changes }) => changes)).toEqual([{ x: 5 }, { x: 0 }])
+ })
+})