AI-native design editor. Open-source Figma alternative.
refactor(editor): centralize mutation layout reconciliation
Danila Poyarkovedb608e99243
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5162e64ee..20cbef094 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -60,6 +60,8 @@### Performance+- Scope automation and Figma API layout reconciliation to graph nodes and parent containers actually changed by each mutation.+- Keep rapid trackpad zoom reversals responsive on complex documents by cancelling obsolete high-resolution scene reconstruction and settling only after navigation becomes idle.- Keep zooming responsive on effect-heavy documents by reusing bounded, invalidation-aware raster snapshots for supported shadow effects while retaining vector-picture fallbacks for backdrop-dependent and oversized effects.- Show the FIG page list from a lightweight Kiwi scan before materializing the full document, making large files feel responsive sooner.diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex 0f1fb462a..909562ed7 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -159,7 +159,7 @@ export function createEditor(options?: EditorOptions) {}const graphReads = createGraphReadActions(() => _graph)- const { runLayoutForNode } = createLayoutRunner(() => _graph)+ const { runLayoutForNode, runMutationWithLayout } = createLayoutRunner(() => _graph)const { scheduleComponentSync } = createComponentSyncScheduler(() => _graph, requestRender)const { subscribeToGraph, unsubscribeFromGraph } = createGraphEventSubscription({@@ -197,6 +197,7 @@ export function createEditor(options?: EditorOptions) {setActiveTool,setNavigationPhase,runLayoutForNode,+ runMutationWithLayout,subscribeToGraph}@@ -289,6 +290,8 @@ export function createEditor(options?: EditorOptions) {state,// Graph reads+ runLayoutForNode,+ runMutationWithLayout,...graphReads,// Lifecyclediff --git a/packages/core/src/editor/graph-events.ts b/packages/core/src/editor/graph-events.tsindex ade2d627d..56460989d 100644--- a/packages/core/src/editor/graph-events.ts+++ b/packages/core/src/editor/graph-events.ts@@ -112,8 +112,8 @@ export function createGraphEventSubscription(options: GraphEventOptions) {options.emitEditorEvent('node:created', node)onNodeStructureChanged(node.id)},- deleted: (id) => {- options.emitEditorEvent('node:deleted', id)+ deleted: (id, _parentId) => {+ options.emitEditorEvent('node:deleted', id, _parentId)onNodeStructureChanged(id)},reparented: (nodeId, oldParentId, newParentId) => {diff --git a/packages/core/src/editor/layout-runner.ts b/packages/core/src/editor/layout-runner.tsindex e4582ac17..347f136c7 100644--- a/packages/core/src/editor/layout-runner.ts+++ b/packages/core/src/editor/layout-runner.ts@@ -1,4 +1,9 @@-import type { SceneGraph } from '@open-pencil/scene-graph'+import {+ collectSceneMutation,+ mutationLayoutScopeIds,+ type SceneGraph,+ type SceneMutationImpact+} from '@open-pencil/scene-graph'import { computeAllLayouts, computeLayout } from '#core/layout'@@ -19,5 +24,33 @@ export function createLayoutRunner(getGraph: () => SceneGraph) {}}- return { runLayoutForNode }+ function compactLayoutScope(impact: SceneMutationImpact): string[] {+ const graph = getGraph()+ const candidates = new Set(mutationLayoutScopeIds(impact).filter((id) => graph.getNode(id)))+ return [...candidates].filter((id) => {+ let parentId = graph.getNode(id)?.parentId ?? null+ while (parentId) {+ if (candidates.has(parentId)) return false+ parentId = graph.getNode(parentId)?.parentId ?? null+ }+ return true+ })+ }++ async function runMutationWithLayout<T>(+ operation: () => T | Promise<T>,+ fallbackId?: string+ ): Promise<T> {+ const graph = getGraph()+ const { result, impact } = await collectSceneMutation(graph, operation)+ const scopeIds = compactLayoutScope(impact)+ if (scopeIds.length > 0) {+ for (const id of scopeIds) runLayoutForNode(id)+ } else if (fallbackId) {+ computeAllLayouts(graph, fallbackId)+ }+ return result+ }++ return { runLayoutForNode, runMutationWithLayout }}diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex f224ba221..b3bd664d8 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -177,5 +177,6 @@ export interface EditorContext {setActiveTool: (tool: Tool) => voidsetNavigationPhase: (phase: NavigationPhase, inputAt?: number) => voidrunLayoutForNode: (id: string) => void+ runMutationWithLayout: <T>(operation: () => T | Promise<T>, fallbackId?: string) => Promise<T>subscribeToGraph: () => void}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 04095beec..0afcf3693 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -1,4 +1,5 @@/* eslint-disable max-lines -- SceneGraph exposes a stable facade over domain modules */+export * from './mutation-impact'export * from './instance-overrides'export * from './images'export * from './components/properties'@@ -553,7 +554,7 @@ export class SceneGraph {this.instanceIndex.get(node.componentId)?.delete(id)}this.nodes.delete(id)- this.emitter.emit('node:deleted', id)+ this.emitter.emit('node:deleted', id, node.parentId)}hitTest(px: number, py: number, scopeId?: string): SceneNode | null {diff --git a/packages/scene-graph/src/mutation-impact.test.ts b/packages/scene-graph/src/mutation-impact.test.tsnew file mode 100644index 000000000..6c720b82b--- /dev/null+++ b/packages/scene-graph/src/mutation-impact.test.ts@@ -0,0 +1,64 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from './index'+import { collectSceneMutation, mutationLayoutScopeIds } from './mutation-impact'++function pageId(graph: SceneGraph): string {+ return graph.getPages()[0].id+}++describe('scene mutation impact', () => {+ test('collects created and updated nodes with current parents', async () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const { result, impact } = await collectSceneMutation(graph, () => {+ const frame = graph.createNode('FRAME', page)+ graph.updateNode(frame.id, { width: 240 })+ return frame.id+ })++ expect(impact.createdNodeIds).toContain(result)+ expect(impact.changedNodeIds).toContain(result)+ expect(impact.currentParentIds).toContain(page)+ expect(mutationLayoutScopeIds(impact)).toContain(result)+ })++ test('retains the old parent when deleting', async () => {+ const graph = new SceneGraph()+ const parent = graph.createNode('FRAME', pageId(graph))+ const child = graph.createNode('RECTANGLE', parent.id)++ const { impact } = await collectSceneMutation(graph, () => graph.deleteNode(child.id))++ expect(impact.deletedNodeIds).toContain(child.id)+ expect(impact.previousParentIds).toContain(parent.id)+ })++ test('retains old and new parents when reparenting', async () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const left = graph.createNode('FRAME', page)+ const right = graph.createNode('FRAME', page)+ const child = graph.createNode('RECTANGLE', left.id)++ const { impact } = await collectSceneMutation(graph, () =>+ graph.reparentNode(child.id, right.id)+ )++ expect(impact.previousParentIds).toContain(left.id)+ expect(impact.currentParentIds).toContain(right.id)+ })++ test('unsubscribes when an operation throws', async () => {+ const graph = new SceneGraph()+ expect(() =>+ collectSceneMutation(graph, () => {+ throw new Error('failed')+ })+ ).toThrow('failed')++ graph.createNode('RECTANGLE', pageId(graph))+ const { impact } = await collectSceneMutation(graph, () => undefined)+ expect(impact.changedNodeIds.size).toBe(0)+ })+})diff --git a/packages/scene-graph/src/mutation-impact.ts b/packages/scene-graph/src/mutation-impact.tsnew file mode 100644index 000000000..ccb28bfb8--- /dev/null+++ b/packages/scene-graph/src/mutation-impact.ts@@ -0,0 +1,67 @@+import type { SceneGraph } from './index'++export interface SceneMutationImpact {+ changedNodeIds: Set<string>+ previousParentIds: Set<string>+ currentParentIds: Set<string>+ createdNodeIds: Set<string>+ deletedNodeIds: Set<string>+}++export function createSceneMutationImpact(): SceneMutationImpact {+ return {+ changedNodeIds: new Set(),+ previousParentIds: new Set(),+ currentParentIds: new Set(),+ createdNodeIds: new Set(),+ deletedNodeIds: new Set()+ }+}++export type MutationImpactListener = (impact: SceneMutationImpact) => void++export interface CollectedSceneMutation<T> {+ result: T+ impact: SceneMutationImpact+}++/** Collects the actual graph nodes and parent containers touched by an operation. */+export async function collectSceneMutation<T>(+ graph: SceneGraph,+ operation: () => T | Promise<T>+): Promise<CollectedSceneMutation<T>> {+ const impact = createSceneMutationImpact()+ const unbind = graph.onNodeEvents({+ created: (node) => {+ impact.createdNodeIds.add(node.id)+ impact.changedNodeIds.add(node.id)+ if (node.parentId) impact.currentParentIds.add(node.parentId)+ },+ updated: (id) => impact.changedNodeIds.add(id),+ deleted: (id, parentId) => {+ if (parentId) impact.previousParentIds.add(parentId)+ impact.deletedNodeIds.add(id)+ impact.changedNodeIds.add(id)+ },+ reparented: (nodeId, oldParentId, newParentId) => {+ impact.changedNodeIds.add(nodeId)+ if (oldParentId) impact.previousParentIds.add(oldParentId)+ impact.currentParentIds.add(newParentId)+ },+ reordered: (nodeId, parentId) => {+ impact.changedNodeIds.add(nodeId)+ impact.currentParentIds.add(parentId)+ }+ })+ try {+ return { result: await operation(), impact }+ } finally {+ unbind()+ }+}++export function mutationLayoutScopeIds(impact: SceneMutationImpact): string[] {+ return [+ ...new Set([...impact.changedNodeIds, ...impact.previousParentIds, ...impact.currentParentIds])+ ]+}diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex f6d10c1bd..158324f70 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -6,7 +6,7 @@ export interface SceneGraphEvents {'node:created': (node: SceneNode) => void'node:updated': (id: string, changes: Partial<SceneNode>) => void'node:previewUpdated': (id: string, changes: Partial<SceneNode>) => void- 'node:deleted': (id: string) => void+ 'node:deleted': (id: string, parentId: string | null) => void'node:reparented': (nodeId: string, oldParentId: string | null, newParentId: string) => void'node:reordered': (nodeId: string, parentId: string, index: number) => void}@@ -15,7 +15,7 @@ export type SceneGraphEventHandlers = Partial<{created: (node: SceneNode) => voidupdated: (id: string, changes: Partial<SceneNode>) => voidpreviewUpdated: (id: string, changes: Partial<SceneNode>) => void- deleted: (id: string) => void+ deleted: (id: string, parentId: string | null) => voidreparented: (nodeId: string, oldParentId: string | null, newParentId: string) => voidreordered: (nodeId: string, parentId: string, index: number) => void}>diff --git a/src/app/automation/bridge/eval-handler.ts b/src/app/automation/bridge/eval-handler.tsindex bf579e905..97536820c 100644--- a/src/app/automation/bridge/eval-handler.ts+++ b/src/app/automation/bridge/eval-handler.ts@@ -14,7 +14,7 @@ export function createAutomationEvalHandler(makeFigma: FigmaFactory) {/* noop */}).constructorconst fn = new AsyncFunction('figma', wrapEvalCode(code))- const result = await fn(figma)+ const result = await target.store.runMutationWithLayout(() => fn(figma), target.pageId)target.store.requestRender()return { ok: true, result: result ?? null }}diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.tsindex 8043f170d..7dce37bae 100644--- a/src/app/automation/bridge/tool-handlers.ts+++ b/src/app/automation/bridge/tool-handlers.ts@@ -1,6 +1,5 @@import { renderTreeNode } from '@open-pencil/core/design-jsx'import type { FigmaAPI } from '@open-pencil/core/figma-api'-import { computeAllLayouts } from '@open-pencil/core/layout'import { ALL_TOOLS, registerComponentCatalog } from '@open-pencil/core/tools'import type { JSONObject } from '@open-pencil/scene-graph/primitives'@@ -17,13 +16,16 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {): Promise<unknown> {const store = target.storeconst tree = toolArgs.tree as Parameters<typeof renderTreeNode>[1]- const result = await renderTreeNode(store.graph, tree, {- parentId: (toolArgs.parent_id as string | undefined) ?? target.pageId,- x: toolArgs.x as number | undefined,- y: toolArgs.y as number | undefined- })+ const result = await store.runMutationWithLayout(+ () =>+ renderTreeNode(store.graph, tree, {+ parentId: (toolArgs.parent_id as string | undefined) ?? target.pageId,+ x: toolArgs.x as number | undefined,+ y: toolArgs.y as number | undefined+ }),+ target.pageId+ )await ensureGraphFonts(store.graph, [result.id], store.renderer)- computeAllLayouts(store.graph, target.pageId)store.requestRender()store.flashNodes([result.id])return {@@ -48,12 +50,13 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {libraryService.bindEditor(store)registerComponentCatalog(store.graph, libraryService)const figma = makeFigma(store, target.pageId)- const result = await def.execute(figma, toolArgs)+ const result = def.mutates+ ? await store.runMutationWithLayout(() => def.execute(figma, toolArgs), figma.currentPageId)+ : await def.execute(figma, toolArgs)if (def.mutates) {const pageNode = store.graph.getNode(figma.currentPageId)if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)- computeAllLayouts(store.graph, figma.currentPageId)store.requestRender()store.flashNodes(extractNodeIds(result))}diff --git a/tests/engine/editor/layout/mutation-impact.test.ts b/tests/engine/editor/layout/mutation-impact.test.tsnew file mode 100644index 000000000..1e121b081--- /dev/null+++ b/tests/engine/editor/layout/mutation-impact.test.ts@@ -0,0 +1,53 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { createLayoutRunner } from '#core/editor/layout-runner'++function pageId(graph: SceneGraph): string {+ return graph.getPages()[0].id+}++describe('mutation layout reconciliation', () => {+ test('reflows the previous parent after deletion', async () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const parent = graph.createNode('FRAME', page, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG'+ })+ const first = graph.createNode('RECTANGLE', parent.id, { width: 40, height: 20 })+ graph.createNode('RECTANGLE', parent.id, { width: 60, height: 20 })+ const { runLayoutForNode, runMutationWithLayout } = createLayoutRunner(() => graph)+ runLayoutForNode(parent.id)+ expect(parent.width).toBe(100)++ await runMutationWithLayout(() => graph.deleteNode(first.id), page)++ expect(parent.width).toBe(60)+ })++ test('reflows old and new parents after reparenting', async () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const left = graph.createNode('FRAME', page, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG'+ })+ const right = graph.createNode('FRAME', page, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG'+ })+ const child = graph.createNode('RECTANGLE', left.id, { width: 40, height: 20 })+ const { runLayoutForNode, runMutationWithLayout } = createLayoutRunner(() => graph)+ runLayoutForNode(left.id)++ await runMutationWithLayout(() => graph.reparentNode(child.id, right.id), page)++ expect(left.width).toBe(0)+ expect(right.width).toBe(40)+ })+})