Skip to content

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

perf(layout): lay out variable changes once per subtree (#1635)

Andrew Avsenin0db79af3add8
diff --git a/changes/1635/fixed.md b/changes/1635/fixed.md
new file mode 100644
index 000000000..fd27b704d
--- /dev/null
+++ b/changes/1635/fixed.md
@@ -0,0 +1 @@
+- A text that sizes itself outside auto layout resizes when a variable bound to its size, such as its font size, changes.
diff --git a/changes/1635/performance.md b/changes/1635/performance.md
new file mode 100644
index 000000000..f96c8c624
--- /dev/null
+++ b/changes/1635/performance.md
@@ -0,0 +1 @@
+- Switching a variable mode or editing a variable's value lays out bound auto layouts once instead of once per bound layer: on a frame of 1,600 bound cards, from about 36 seconds to under 0.1 seconds.
diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts
index 2d2d4ce22..f719dc84c 100644
--- a/packages/core/src/editor/nodes.ts
+++ b/packages/core/src/editor/nodes.ts
@@ -27,6 +27,10 @@ export function opacityFromBuffer(buffer: string): number {
return Math.min(100, Math.max(0, percent)) / 100
}
+function changesMoreThanModes(changes: Partial<SceneNode>): boolean {
+ return Object.keys(changes).some((key) => key !== 'variableModes')
+}
+
export function createNodeActions(ctx: EditorContext) {
// Function declarations below are hoisted, so the preview can wrap updateNode here.
const previewActions = createNodePreviewActions(ctx, updateNode)
@@ -39,7 +43,9 @@ export function createNodeActions(ctx: EditorContext) {
if (changes.variableModes) reconcileVariableLayouts(ctx.graph, { subtrees: [id] })
if (changes.visible !== undefined) refitGroupsAroundLayers(ctx, [id])
if (changes.booleanOperation !== undefined) refitContainers(ctx, [id])
- ctx.runLayoutForNode(id)
+ if (changesMoreThanModes(changes)) {
+ ctx.runLayoutForNode(id)
+ }
}
function updateNode(id: string, changes: Partial<SceneNode>) {
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index c39648df9..9d6e1f8d7 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -86,12 +86,18 @@ function resolveComputedLayoutDirection(
}
export function computeAllLayouts(graph: SceneGraph, scopeId?: string): void {
+ computeSubtreeLayouts(graph, scopeId ?? graph.rootId, new Set())
+}
+
+export function computeSubtreeLayouts(
+ graph: SceneGraph,
+ rootId: string,
+ relaidInstances: ReadonlySet<string>
+): void {
graph.withLayoutMutations(() => {
- const rootId = scopeId ?? graph.rootId
- const visited = new Set<string>()
- computeLayoutsBottomUp(graph, rootId, visited)
+ computeLayoutsBottomUp(graph, rootId, new Set(), relaidInstances)
if (applyEffectiveGeneratedTextLayout(graph, rootId)) {
- computeLayoutsBottomUp(graph, rootId, new Set())
+ computeLayoutsBottomUp(graph, rootId, new Set(), relaidInstances)
}
routeUnroutedConnectors(graph, rootId)
})
@@ -141,16 +147,23 @@ export function layoutAuthoredNodes(graph: SceneGraph, rootIds: Iterable<string>
}
}
-function computeLayoutsBottomUp(graph: SceneGraph, nodeId: string, visited: Set<string>): void {
+function computeLayoutsBottomUp(
+ graph: SceneGraph,
+ nodeId: string,
+ visited: Set<string>,
+ relaidInstances: ReadonlySet<string>
+): void {
const node = graph.getNode(nodeId)
if (!node || visited.has(nodeId)) return
visited.add(nodeId)
for (const childId of node.childIds) {
- computeLayoutsBottomUp(graph, childId, visited)
+ computeLayoutsBottomUp(graph, childId, visited, relaidInstances)
}
- if (node.layoutMode !== 'NONE' && !preservesImportedInstanceLayout(node)) {
+ const keepsSavedInstanceLayout =
+ preservesImportedInstanceLayout(node) && !relaidInstances.has(nodeId)
+ if (node.layoutMode !== 'NONE' && !keepsSavedInstanceLayout) {
computeLayout(graph, nodeId)
}
}
diff --git a/packages/core/src/layout/variables.ts b/packages/core/src/layout/variables.ts
index 677125f6f..452feef34 100644
--- a/packages/core/src/layout/variables.ts
+++ b/packages/core/src/layout/variables.ts
@@ -1,19 +1,98 @@
-import type { SceneGraph } from '@open-pencil/scene-graph'
-import { reconcileVariableBindings, type BindingScope } from '@open-pencil/scene-graph/variables'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ reconcileVariableBindingUpdates,
+ type BindingScope
+} from '@open-pencil/scene-graph/variables'
-import { computeLayout } from '#core/layout'
-
-import { createLayoutRunner } from './mutations'
+import { computeLayout, computeSubtreeLayouts } from '#core/layout'
+import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
/**
* Binding evaluation is derived work, not an additional history entry. The scope names what
* changed, so only the layers that change can reach are resolved and laid out again.
*/
export function reconcileVariableLayouts(graph: SceneGraph, scope: BindingScope): void {
- const { runLayoutForNode } = createLayoutRunner(() => graph)
- for (const id of reconcileVariableBindings(graph, scope)) {
- // A deliberate binding change also invalidates a placed instance's saved Hug size.
+ const updates = reconcileVariableBindingUpdates(graph, scope)
+ if (updates.size === 0) {
+ return
+ }
+ graph.withLayoutMutations(() => {
+ resizeAutoResizingText(graph, updates)
+ layOutChangedLayers(graph, new Set(updates.keys()))
+ })
+}
+
+function resizeAutoResizingText(
+ graph: SceneGraph,
+ updates: ReadonlyMap<string, Partial<SceneNode>>
+): void {
+ for (const [id, changes] of updates) {
+ const resized = textAutoResizeChanges(graph.getNode(id), changes)
+ if (Object.keys(resized).length > 0) {
+ graph.updateNode(id, resized)
+ }
+ }
+}
+
+function layOutChangedLayers(graph: SceneGraph, changed: ReadonlySet<string>): void {
+ const containing = containingLayers(graph, changed)
+ const isInsideChanged = insideAnyOf(graph, changed)
+ const relaidInstances = new Set([...changed, ...containing])
+ for (const id of changed) {
+ if (!isInsideChanged(id)) {
+ computeSubtreeLayouts(graph, id, relaidInstances)
+ }
+ }
+ const depth = depthOf(graph)
+ const surrounding = [...containing]
+ .filter((id) => !changed.has(id) && !isInsideChanged(id))
+ .sort((a, b) => depth(b) - depth(a))
+ for (const id of surrounding) {
computeLayout(graph, id)
- runLayoutForNode(id)
}
}
+
+function containingLayers(graph: SceneGraph, ids: Iterable<string>): Set<string> {
+ const containing = new Set<string>()
+ for (const id of ids) {
+ let parentId = graph.getNode(id)?.parentId
+ while (parentId && !containing.has(parentId)) {
+ containing.add(parentId)
+ parentId = graph.getNode(parentId)?.parentId
+ }
+ }
+ return containing
+}
+
+function insideAnyOf(graph: SceneGraph, ids: ReadonlySet<string>): (id: string) => boolean {
+ const known = new Map<string, boolean>()
+ function isInside(id: string): boolean {
+ const parentId = graph.getNode(id)?.parentId
+ if (!parentId) {
+ return false
+ }
+ const cached = known.get(parentId)
+ if (cached !== undefined) {
+ return cached
+ }
+ const inside = ids.has(parentId) || isInside(parentId)
+ known.set(parentId, inside)
+ return inside
+ }
+ return isInside
+}
+
+function depthOf(graph: SceneGraph): (id: string) => number {
+ const known = new Map<string, number>()
+ function depth(id: string): number {
+ const cached = known.get(id)
+ if (cached !== undefined) {
+ return cached
+ }
+ const parentId = graph.getNode(id)?.parentId
+ const result = parentId ? depth(parentId) + 1 : 0
+ known.set(id, result)
+ return result
+ }
+ return depth
+}
diff --git a/packages/core/tests/editor/variables/mode-layout.test.ts b/packages/core/tests/editor/variables/mode-layout.test.ts
new file mode 100644
index 000000000..6a609614b
--- /dev/null
+++ b/packages/core/tests/editor/variables/mode-layout.test.ts
@@ -0,0 +1,54 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function cardsWithBoundSpacing() {
+ const graph = new SceneGraph()
+ const tokens = graph.createCollection('Tokens')
+ const compact = graph.createMode(tokens.id, 'Compact') ?? ''
+ const gap = graph.createVariable('Gap', 'FLOAT', tokens.id, 12)
+ gap.valuesByMode[compact] = 2
+ const hug = { primaryAxisSizing: 'HUG', counterAxisSizing: 'HUG' } as const
+ const list = graph.createNode('FRAME', graph.getPages()[0].id, {
+ layoutMode: 'VERTICAL',
+ ...hug
+ })
+ const card = graph.createNode('FRAME', list.id, {
+ layoutMode: 'HORIZONTAL',
+ ...hug,
+ boundVariables: { itemSpacing: gap.id }
+ })
+ graph.createNode('RECTANGLE', card.id, { width: 20, height: 10 })
+ graph.createNode('RECTANGLE', card.id, { width: 20, height: 10 })
+ const editor = createEditor({ graph })
+ editor.runLayoutForNode(list.id)
+ return { editor, tokens, compact, list, card }
+}
+
+test('a mode set on a frame reflows the auto layouts it reaches, and undo restores them', () => {
+ const { editor, tokens, compact, list, card } = cardsWithBoundSpacing()
+
+ editor.updateNodeWithUndo(list.id, { variableModes: { [tokens.id]: compact } }, 'Set mode')
+ expect(card.width).toBe(42)
+ expect(list.width).toBe(42)
+
+ editor.undo.undo()
+ expect(card.width).toBe(52)
+ expect(list.width).toBe(52)
+})
+
+test('a mode set together with another change still lays out that change', () => {
+ const { editor, tokens, compact, list } = cardsWithBoundSpacing()
+ const unbound = editor.graph.createNode('FRAME', list.id, {
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG'
+ })
+ editor.graph.createNode('RECTANGLE', unbound.id, { width: 20, height: 10 })
+ editor.runLayoutForNode(unbound.id)
+
+ editor.updateNode(unbound.id, { variableModes: { [tokens.id]: compact }, paddingLeft: 8 })
+
+ expect(unbound.width).toBe(28)
+})
diff --git a/packages/core/tests/layout/variables.test.ts b/packages/core/tests/layout/variables.test.ts
new file mode 100644
index 000000000..fb905f772
--- /dev/null
+++ b/packages/core/tests/layout/variables.test.ts
@@ -0,0 +1,190 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import { reconcileVariableBindings, type BindingScope } from '@open-pencil/scene-graph/variables'
+
+import { computeAllLayouts, computeLayout, setTextMeasurer } from '#core/layout'
+import { reconcileVariableLayouts } from '#core/layout/variables'
+
+function buildDocument() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const tokens = graph.createCollection('Tokens')
+ const compact = 'compact'
+ graph.addMode(tokens.id, compact, 'Compact')
+ const comfortable = tokens.defaultModeId
+ const padding = graph.createVariable('Padding', 'FLOAT', tokens.id, 16)
+ const gap = graph.createVariable('Gap', 'FLOAT', tokens.id, 12)
+ const size = graph.createVariable('Size', 'FLOAT', tokens.id, 40)
+ const inset = graph.createVariable('Inset', 'FLOAT', tokens.id, { aliasId: padding.id })
+ const label = graph.createVariable('Label', 'STRING', tokens.id, 'Save')
+ padding.valuesByMode[compact] = 4
+ gap.valuesByMode[compact] = 2
+ size.valuesByMode[compact] = 24
+ inset.valuesByMode[compact] = 6
+ label.valuesByMode[compact] = 'Save as draft'
+
+ const autoLayout = (direction: 'HORIZONTAL' | 'VERTICAL'): Partial<SceneNode> => ({
+ layoutMode: direction,
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG'
+ })
+ const outer = graph.createNode('FRAME', page.id, {
+ ...autoLayout('VERTICAL'),
+ boundVariables: { itemSpacing: gap.id, paddingTop: padding.id }
+ })
+ for (let row = 0; row < 3; row++) {
+ const rowFrame = graph.createNode('FRAME', outer.id, {
+ ...autoLayout('HORIZONTAL'),
+ boundVariables: { paddingLeft: padding.id, itemSpacing: gap.id }
+ })
+ const card = graph.createNode(row === 1 ? 'INSTANCE' : 'FRAME', rowFrame.id, {
+ ...autoLayout('VERTICAL'),
+ boundVariables: { paddingTop: inset.id, paddingBottom: inset.id }
+ })
+ if (row === 1) {
+ card.source.format = 'fig'
+ }
+ graph.createNode('RECTANGLE', card.id, {
+ width: 10,
+ height: 10,
+ boundVariables: { width: size.id, height: size.id }
+ })
+ graph.createNode('RECTANGLE', rowFrame.id, { width: 20, height: 8 })
+ graph.createNode('TEXT', rowFrame.id, {
+ text: 'Save',
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ boundVariables: { text: label.id }
+ })
+ }
+ computeAllLayouts(graph)
+ return { graph, tokens, compact, comfortable, padding, outer }
+}
+
+type Document = ReturnType<typeof buildDocument>
+
+function layOutEachChangedLayer(graph: SceneGraph, scope: BindingScope): void {
+ for (const id of reconcileVariableBindings(graph, scope)) {
+ computeLayout(graph, id)
+ computeAllLayouts(graph, id)
+ let parentId = graph.getNode(id)?.parentId
+ while (parentId) {
+ const parent = graph.getNode(parentId)
+ if (parent?.layoutMode !== 'NONE') {
+ computeLayout(graph, parentId)
+ }
+ parentId = parent?.parentId
+ }
+ }
+}
+
+function geometry(graph: SceneGraph) {
+ return graph
+ .flattenTree(graph.getPages()[0].id)
+ .map(({ node }) => [node.type, node.x, node.y, node.width, node.height])
+}
+
+function expectSameLayoutAsPerLayer(change: (document: Document) => BindingScope) {
+ const perLayer = buildDocument()
+ const batched = buildDocument()
+ const before = geometry(batched.graph)
+ layOutEachChangedLayer(perLayer.graph, change(perLayer))
+ reconcileVariableLayouts(batched.graph, change(batched))
+ expect(geometry(batched.graph)).toEqual(geometry(perLayer.graph))
+ expect(geometry(batched.graph)).not.toEqual(before)
+}
+
+describe('reconcileVariableLayouts', () => {
+ beforeEach(() => setTextMeasurer((node) => ({ width: node.text.length * 8, height: 16 })))
+ afterEach(() => setTextMeasurer(null))
+
+ test('an explicit mode on a container lays its layers out as one layer at a time would', () => {
+ expectSameLayoutAsPerLayer(({ graph, tokens, compact, outer }) => {
+ graph.updateNode(outer.id, { variableModes: { [tokens.id]: compact } })
+ return { subtrees: [outer.id] }
+ })
+ })
+
+ test('an explicit mode on one nested layer reflows the layouts around it', () => {
+ expectSameLayoutAsPerLayer(({ graph, tokens, compact, outer }) => {
+ const middleRow = outer.childIds[1]
+ graph.updateNode(middleRow, { variableModes: { [tokens.id]: compact } })
+ return { subtrees: [middleRow] }
+ })
+ })
+
+ test('an active mode change lays out every layer it reaches as one layer at a time would', () => {
+ expectSameLayoutAsPerLayer(({ graph, tokens, compact }) => {
+ graph.setActiveMode(tokens.id, compact)
+ return { variables: tokens.variableIds }
+ })
+ })
+
+ test('a value edit through an alias lays out as one layer at a time would', () => {
+ expectSameLayoutAsPerLayer(({ padding, comfortable }) => {
+ padding.valuesByMode[comfortable] = 30
+ return { variables: [padding.id] }
+ })
+ })
+
+ test('a text outside auto layout resizes to a bound font size', () => {
+ setTextMeasurer((node) => ({ width: node.text.length * node.fontSize, height: node.fontSize }))
+ const graph = new SceneGraph()
+ const tokens = graph.createCollection('Tokens')
+ graph.addMode(tokens.id, 'large', 'Large')
+ const size = graph.createVariable('Size', 'FLOAT', tokens.id, 10)
+ size.valuesByMode.large = 20
+ const label = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Save',
+ fontSize: 10,
+ width: 40,
+ height: 10,
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ boundVariables: { fontSize: size.id }
+ })
+
+ graph.setActiveMode(tokens.id, 'large')
+ reconcileVariableLayouts(graph, { variables: [size.id] })
+
+ expect([label.fontSize, label.width, label.height]).toEqual([20, 80, 20])
+ })
+
+ test('a layer scaled by its constraints follows its Hug frame once per change', () => {
+ const graph = new SceneGraph()
+ const tokens = graph.createCollection('Tokens')
+ graph.addMode(tokens.id, 'compact', 'Compact')
+ const width = graph.createVariable('Width', 'FLOAT', tokens.id, 100)
+ width.valuesByMode.compact = 60
+ const hug = { primaryAxisSizing: 'HUG', counterAxisSizing: 'HUG' } as const
+ const outer = graph.createNode('FRAME', graph.getPages()[0].id, {
+ layoutMode: 'VERTICAL',
+ ...hug
+ })
+ const row = graph.createNode('FRAME', outer.id, { layoutMode: 'HORIZONTAL', ...hug })
+ const button = graph.createNode('FRAME', row.id, { layoutMode: 'HORIZONTAL', ...hug })
+ graph.createNode('RECTANGLE', button.id, {
+ width: 100,
+ height: 20,
+ boundVariables: { width: width.id }
+ })
+ graph.createNode('RECTANGLE', row.id, {
+ width: 10,
+ height: 10,
+ boundVariables: { height: width.id }
+ })
+ const badge = graph.createNode('RECTANGLE', button.id, {
+ x: 10,
+ width: 80,
+ height: 20,
+ layoutPositioning: 'ABSOLUTE',
+ horizontalConstraint: 'SCALE'
+ })
+ computeAllLayouts(graph)
+
+ graph.updateNode(outer.id, { variableModes: { [tokens.id]: 'compact' } })
+ reconcileVariableLayouts(graph, { subtrees: [outer.id] })
+
+ expect(button.width).toBe(60)
+ expect(badge.width).toBe(48)
+ })
+})
diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.ts
index 72fc9f594..c0ad41cac 100644
--- a/packages/scene-graph/src/variables/bindings.ts
+++ b/packages/scene-graph/src/variables/bindings.ts
@@ -327,7 +327,18 @@ function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterab
* is written but not returned.
*/
export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {
- const relaid: string[] = []
+ return [...reconcileVariableBindingUpdates(graph, scope).keys()]
+}
+
+/**
+ * As `reconcileVariableBindings`, with the layout fields each relaid layer received. Effects
+ * are written too, but draw without layout, so a layer whose only change is an effect is left out.
+ */
+export function reconcileVariableBindingUpdates(
+ graph: SceneGraph,
+ scope?: BindingScope
+): Map<string, Partial<SceneNode>> {
+ const relaid = new Map<string, Partial<SceneNode>>()
for (const node of scopedNodes(graph, scope)) {
const layoutUpdates = {
...resolvedNumericBindings(graph, node),
@@ -337,7 +348,7 @@ export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScop
const updates = { ...layoutUpdates, ...resolvedEffectBindings(graph, node) }
if (isEmptyObject(updates)) continue
graph.updateNode(node.id, updates)
- if (!isEmptyObject(layoutUpdates)) relaid.push(node.id)
+ if (!isEmptyObject(layoutUpdates)) relaid.set(node.id, layoutUpdates)
}
return relaid
}