AI-native design editor. Open-source Figma alternative.
perf: scope variable changes to what they can reach (#935)
Danila Poyarkove8b5d7533979
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7820ddb52..9c1070eee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@- `SceneNode.booleanOperation` is a required key whose value may be `undefined`, like every other scene node field, so code that builds `SceneNode` objects itself must include it.- `useVariables().collections` from `@open-pencil/vue` returns copies of the document's collections instead of the graph's own objects, so components see modes added or renamed in place; change collections through the editor's actions rather than by mutating the returned objects. `addVariable` returns the new variable's ID.- `useVariablesEditor`, `useVariablesTable`, and `useVariablesDialogState` are removed from `@open-pencil/vue`, together with the `formatModeValue`, `parseVariableValue`, and `shortName` helpers `useVariables()` returned for them, and the package no longer depends on `@tanstack/vue-table`. Build variable editors on `useVariables()` and the editor's variable actions.+- The editor's shared state has a required `canvasVersion`, which the canvas redraws on; `sceneVersion` still counts every document change. Code that creates editor state itself must set it, and code that bumped `sceneVersion` to redraw the canvas calls `requestRender()` instead; `requestRefresh()` records a change the canvas does not draw.- `sceneNodeToDesignDocument` from `@open-pencil/dom-css` takes an options object, `{ includeSourceIds, tokens }`, instead of a boolean third argument; `tokens: false` writes literal values instead of variable references.- `randomHex`, `randomInt`, and `randomIndex` moved from `@open-pencil/core/random` and the `@open-pencil/core` barrel to `@open-pencil/scene-graph/random`.- `Stroke` from `@open-pencil/scene-graph` extends `Fill`, so every stroke states a paint `type` that code constructing one must set to `'SOLID'`, and `copyStroke` deep-copies the paint fields a fill already copied.@@ -199,6 +200,7 @@### Performance+- Edit variables in large documents without stalls: renaming, reordering, or adding a variable, or changing its CSS name, unit, scopes, or conditions, no longer redraws the canvas, and changing a value or mode updates only the layers bound to those variables or to variables aliasing them instead of re-resolving and laying out every bound layer in the document.- Open large `.fig` files with less memory in the macOS desktop app and Safari: imported layers now share one object layout in JavaScriptCore instead of each being stored as a slower, larger dictionary.- Open multi-page `.fig` documents faster: the archive is indexed once rather than once for every page, each page resolves only the layers it adds instead of rescanning the whole document, placing an instance no longer re-synchronises every other instance of its component, and archive records are copied directly rather than through `structuredClone`. A 33-page file loads about a fifth quicker, and a page of repeated components opens three to four times faster once a document is already open.diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.tsindex a92d641ba..369621ae1 100644--- a/packages/core/src/canvas/renderer/pipeline.ts+++ b/packages/core/src/canvas/renderer/pipeline.ts@@ -89,7 +89,8 @@ export function renderFromEditorState(codeFocusNodeId: state.codeFocusNodeId,autoLayoutHover: state.autoLayoutHover},- state.sceneVersion,+ // Recorded pictures follow what the canvas draws, not every document change.+ state.canvasVersion,layer,interactive)diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex 070f194f3..e1359bfc6 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -94,6 +94,7 @@ export function createEditor(options?: EditorOptions) {function requestRender() {state.renderVersion++state.sceneVersion+++ state.canvasVersion++emitNavigationTrace('render:requested', {kind: 'render',renderVersion: state.renderVersion,@@ -105,6 +106,10 @@ export function createEditor(options?: EditorOptions) {})}+ function requestRefresh() {+ state.sceneVersion+++ }+function requestRepaint() {state.renderVersion++emitNavigationTrace('render:requested', {@@ -212,6 +217,7 @@ export function createEditor(options?: EditorOptions) {getRenderer: () => _renderer,getTextEditor: () => _textEditor,requestRender,+ requestRefresh,requestRepaint,beginInteractiveEdit,onEditorEvent,@@ -335,6 +341,7 @@ export function createEditor(options?: EditorOptions) {beginInteractiveEdit,isInteractiveEditing: () => interactiveEdits.size > 0,requestRender,+ requestRefresh,requestRepaint,onEditorEvent,setCanvasKit,diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.tsindex 56e060923..b3afa404c 100644--- a/packages/core/src/editor/nodes.ts+++ b/packages/core/src/editor/nodes.ts@@ -33,7 +33,8 @@ export function createNodeActions(ctx: EditorContext) {const variableBindingActions = createVariableBindingActions(ctx)function runChangedLayout(id: string, changes: Partial<SceneNode>) {- if (changes.variableModes) reconcileVariableLayouts(ctx.graph)+ // A layer's modes reach the layers inside it.+ if (changes.variableModes) reconcileVariableLayouts(ctx.graph, { subtrees: [id] })ctx.runLayoutForNode(id)}diff --git a/packages/core/src/editor/state/shared.ts b/packages/core/src/editor/state/shared.tsindex acf136acc..c256204f8 100644--- a/packages/core/src/editor/state/shared.ts+++ b/packages/core/src/editor/state/shared.ts@@ -10,6 +10,7 @@ export function createDefaultEditorSharedState(): EditorSharedState {designIssues: null,codeFocusNodeId: null,rulerTheme: undefined,- sceneVersion: 0+ sceneVersion: 0,+ canvasVersion: 0}}diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex 0b734c3ee..31543e6e6 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -49,7 +49,13 @@ export interface EditorSharedState {rulerTheme?: RulerTheme/** The interface theme new sections take their fill from; light when unset. */theme?: InterfaceTheme+ /** Bumped by every document change; views, saving, and recovery follow it. */sceneVersion: number+ /**+ * Bumped by document changes the canvas draws. Changes it does not draw, such as a variable's+ * name or CSS name, bump only `sceneVersion`, so the canvas keeps its recorded pictures.+ */+ canvasVersion: number}export interface EditorViewState {@@ -180,6 +186,8 @@ export interface EditorContext {getRenderer: () => SkiaRenderer | nullgetTextEditor: () => TextEditor | nullrequestRender: () => void+ /** A document change the canvas does not draw: views and saving follow, nothing is redrawn. */+ requestRefresh: () => voidrequestRepaint: () => voidbeginInteractiveEdit: () => () => voidonEditorEvent: <K extends EditorEventName>(event: K, handler: EditorEvents[K]) => () => voiddiff --git a/packages/core/src/editor/variable-bindings.ts b/packages/core/src/editor/variable-bindings.tsindex 25c521c43..5a8c610d2 100644--- a/packages/core/src/editor/variable-bindings.ts+++ b/packages/core/src/editor/variable-bindings.ts@@ -11,8 +11,9 @@ import { reconcileVariableLayouts } from '#core/layout/variables'import type { EditorContext } from './types'export function createVariableBindingActions(ctx: EditorContext) {- function refreshBindings() {- reconcileVariableLayouts(ctx.graph)+ /** A binding change reaches only the layer it is on and the layers inside it. */+ function refreshBindings(nodeId: string) {+ reconcileVariableLayouts(ctx.graph, { subtrees: [nodeId] })ctx.requestRender()}@@ -34,7 +35,7 @@ export function createVariableBindingActions(ctx: EditorContext) {const apply = () => {if (variableId === undefined) ctx.graph.unbindVariable(nodeId, path)else ctx.graph.bindVariable(nodeId, path, variableId)- refreshBindings()+ refreshBindings(nodeId)}apply()ctx.undo.push({@@ -63,7 +64,7 @@ export function createVariableBindingActions(ctx: EditorContext) {))ctx.graph.updateNode(nodeId, restored)- refreshBindings()+ refreshBindings(nodeId)}})}diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.tsindex e08cc91c5..fb032ab9f 100644--- a/packages/core/src/editor/variables.ts+++ b/packages/core/src/editor/variables.ts@@ -3,6 +3,7 @@ import { isEmptyObject } from 'es-toolkit/predicate'import {isModeAttributeName,+ type BindingScope,type TokenExpression,type Variable,type VariableCollection,@@ -60,14 +61,21 @@ function setModeEntry(variable: Variable, modeId: string, entry: ModeEntry) {export function createVariableActions(ctx: EditorContext) {/**- * Re-resolves every bound layer, for changes to what variables resolve to. Adding, copying, or- * reordering variables changes no bound value, so those only request a render: re-resolving- * there would resize layers a file saved at a size their binding no longer gives.+ * Re-resolves the layers a change to what variables resolve to can reach: those bound to the+ * changed variables or to variables aliasing them. Every other variable change, such as adding,+ * renaming, reordering, or a token field, changes nothing the canvas draws, so it only refreshes+ * the views and leaves the canvas's recorded pictures in place.*/- function refreshVariables() {- reconcileVariableLayouts(ctx.graph)+ function refreshVariables(scope: BindingScope) {+ reconcileVariableLayouts(ctx.graph, scope)ctx.requestRender()}++ /** Every variable in a collection, the ones a change to its modes can reach. */+ function collectionScope(collectionId: string): BindingScope {+ return { variables: [...(ctx.graph.variableCollections.get(collectionId)?.variableIds ?? [])] }+ }+function getVariablesByType(type: VariableType) {return ctx.graph.getVariablesByType(type)}@@ -114,15 +122,15 @@ export function createVariableActions(ctx: EditorContext) {forward: () => {const c = ctx.graph.variableCollections.get(id)if (c) c.name = newName- ctx.requestRender()+ ctx.requestRefresh()},inverse: () => {const c = ctx.graph.variableCollections.get(id)if (c) c.name = prevName- ctx.requestRender()+ ctx.requestRefresh()}})- ctx.requestRender()+ ctx.requestRefresh()}function addCollection(collection: VariableCollection) {@@ -131,20 +139,21 @@ export function createVariableActions(ctx: EditorContext) {label: 'Add collection',forward: () => {ctx.graph.addCollection(collection)- ctx.requestRender()+ ctx.requestRefresh()},inverse: () => {ctx.graph.removeCollection(collection.id)- ctx.requestRender()+ ctx.requestRefresh()}})- ctx.requestRender()+ ctx.requestRefresh()}function removeCollection(id: string) {const collection = ctx.graph.variableCollections.get(id)if (!collection) returnconst snapshot = structuredClone(collection)+ const scope: BindingScope = { variables: snapshot.variableIds }const variables = snapshot.variableIds.map((vid) => ctx.graph.variables.get(vid)).filter((v): v is Variable => v != null)@@ -154,15 +163,15 @@ export function createVariableActions(ctx: EditorContext) {label: 'Remove collection',forward: () => {ctx.graph.removeCollection(id)- refreshVariables()+ refreshVariables(scope)},inverse: () => {ctx.graph.addCollection(snapshot)for (const v of variables) ctx.graph.addVariable(v)- refreshVariables()+ refreshVariables(scope)}})- refreshVariables()+ refreshVariables(scope)}function addVariable(variable: Variable) {@@ -171,14 +180,14 @@ export function createVariableActions(ctx: EditorContext) {label: 'Add variable',forward: () => {ctx.graph.addVariable(variable)- ctx.requestRender()+ ctx.requestRefresh()},inverse: () => {ctx.graph.removeVariable(variable.id)- ctx.requestRender()+ ctx.requestRefresh()}})- ctx.requestRender()+ ctx.requestRefresh()}function removeVariable(id: string) {@@ -191,16 +200,16 @@ export function createVariableActions(ctx: EditorContext) {label: 'Remove variable',forward: () => {ctx.graph.removeVariable(id)- refreshVariables()+ refreshVariables({ variables: [id] })},// Undo puts the variable back where it was, not at the end of its collection.inverse: () => {ctx.graph.addVariable(structuredClone(snapshot))placeVariables(snapshot.collectionId, order)- refreshVariables()+ refreshVariables({ variables: [id] })}})- refreshVariables()+ refreshVariables({ variables: [id] })}/** Puts a collection's variables in `order`; ids it does not hold are ignored. */@@ -225,14 +234,14 @@ export function createVariableActions(ctx: EditorContext) {label: 'Reorder variables',forward: () => {placeVariables(collectionId, next)- ctx.requestRender()+ ctx.requestRefresh()},inverse: () => {placeVariables(collectionId, previous)- ctx.requestRender()+ ctx.requestRefresh()}})- ctx.requestRender()+ ctx.requestRefresh()}/** Copies a variable, values and token fields included, right after the original. */@@ -252,14 +261,14 @@ export function createVariableActions(ctx: EditorContext) {forward: () => {ctx.graph.addVariable(structuredClone(copy))placeVariables(collection.id, order)- ctx.requestRender()+ ctx.requestRefresh()},inverse: () => {ctx.graph.removeVariable(copy.id)- ctx.requestRender()+ ctx.requestRefresh()}})- ctx.requestRender()+ ctx.requestRefresh()return copy.id}@@ -273,15 +282,15 @@ export function createVariableActions(ctx: EditorContext) {forward: () => {const v = ctx.graph.variables.get(id)if (v) v.name = newName- ctx.requestRender()+ ctx.requestRefresh()},inverse: () => {const v = ctx.graph.variables.get(id)if (v) v.name = prevName- ctx.requestRender()+ ctx.requestRefresh()}})- ctx.requestRender()+ ctx.requestRefresh()}function addMode(collectionId: string, name?: string): string | undefined {@@ -294,14 +303,14 @@ export function createVariableActions(ctx: EditorContext) {label: 'Add mode',forward: () => {ctx.graph.addMode(collectionId, modeId, modeName)- refreshVariables()+ refreshVariables(collectionScope(collectionId))},inverse: () => {ctx.graph.removeMode(collectionId, modeId)- refreshVariables()+ refreshVariables(collectionScope(collectionId))}})- refreshVariables()+ refreshVariables(collectionScope(collectionId))return modeId}@@ -323,7 +332,7 @@ export function createVariableActions(ctx: EditorContext) {label: 'Remove mode',forward: () => {ctx.graph.removeMode(collectionId, modeId)- refreshVariables()+ refreshVariables(collectionScope(collectionId))},inverse: () => {ctx.graph.addMode(collectionId, modeId, modeName)@@ -337,10 +346,10 @@ export function createVariableActions(ctx: EditorContext) {if (v) v.valuesByMode[modeId] = structuredClone(value)}if (wasDefault) ctx.graph.setDefaultMode(collectionId, modeId)- refreshVariables()+ refreshVariables(collectionScope(collectionId))}})- refreshVariables()+ refreshVariables(collectionScope(collectionId))}function renameMode(collectionId: string, modeId: string, newName: string) {@@ -354,14 +363,14 @@ export function createVariableActions(ctx: EditorContext) {label: 'Rename mode',forward: () => {ctx.graph.renameMode(collectionId, modeId, newName)- ctx.requestRender()+ ctx.requestRefresh()},inverse: () => {ctx.graph.renameMode(collectionId, modeId, prevName)- ctx.requestRender()+ ctx.requestRefresh()}})- ctx.requestRender()+ ctx.requestRefresh()}function setDefaultMode(collectionId: string, modeId: string) {@@ -374,7 +383,7 @@ export function createVariableActions(ctx: EditorContext) {label: 'Set default mode',forward: () => {ctx.graph.setDefaultMode(collectionId, modeId)- refreshVariables()+ refreshVariables(collectionScope(collectionId))},inverse: () => {// Setting a default moves it first; undo restores the column order too. Look the@@ -384,10 +393,10 @@ export function createVariableActions(ctx: EditorContext) {current.modes = structuredClone(prevModes)current.defaultModeId = prevDefault}- refreshVariables()+ refreshVariables(collectionScope(collectionId))}})- refreshVariables()+ refreshVariables(collectionScope(collectionId))}function duplicateMode(collectionId: string, sourceModeId: string): string | undefined {@@ -402,20 +411,20 @@ export function createVariableActions(ctx: EditorContext) {label: 'Duplicate mode',forward: () => {ctx.graph.addMode(collectionId, modeId, modeName, sourceModeId)- refreshVariables()+ refreshVariables(collectionScope(collectionId))},inverse: () => {ctx.graph.removeMode(collectionId, modeId)- refreshVariables()+ refreshVariables(collectionScope(collectionId))}})- refreshVariables()+ refreshVariables(collectionScope(collectionId))return modeId}function setActiveMode(collectionId: string, modeId: string) {ctx.graph.setActiveMode(collectionId, modeId)- refreshVariables()+ refreshVariables(collectionScope(collectionId))}/**@@ -441,7 +450,7 @@ export function createVariableActions(ctx: EditorContext) {const apply = (entry: ModeEntry) => {const target = ctx.graph.variables.get(id)if (target) setModeEntry(target, modeId, entry)- refreshVariables()+ refreshVariables({ variables: [id] })}apply(next)ctx.undo.push({@@ -472,7 +481,7 @@ export function createVariableActions(ctx: EditorContext) {)// Every variable has a description; clearing it leaves an empty one.if ('description' in values) target.description = description ?? ''- ctx.requestRender()+ ctx.requestRefresh()}apply(next)ctx.undo.push({@@ -496,7 +505,7 @@ export function createVariableActions(ctx: EditorContext) {.get(collectionId)?.modes.find((candidate) => candidate.modeId === modeId)if (target) target.condition = value- ctx.requestRender()+ ctx.requestRefresh()}apply(next)ctx.undo.push({@@ -519,7 +528,7 @@ export function createVariableActions(ctx: EditorContext) {const apply = (value: string | undefined) => {const target = ctx.graph.variableCollections.get(collectionId)if (target) target.modeAttribute = value- ctx.requestRender()+ ctx.requestRefresh()}apply(next)ctx.undo.push({diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex 2af8dcbad..6afda76e0 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -327,7 +327,7 @@ export class FigmaAPI implements NodeProxyHost {const variable = this.graph.variables.get(variableId)if (!variable) throw new Error(`Variable "${variableId}" not found`)variable.valuesByMode[modeId] = structuredClone(value)- reconcileVariableLayouts(this.graph)+ reconcileVariableLayouts(this.graph, { variables: [variableId] })}deleteVariable(id: string): void {@@ -344,12 +344,12 @@ export class FigmaAPI implements NodeProxyHost {bindVariable(nodeId: string, field: string, variableId: string): void {this.graph.bindVariable(nodeId, field, variableId)- reconcileVariableLayouts(this.graph)+ reconcileVariableLayouts(this.graph, { subtrees: [nodeId] })}unbindVariable(nodeId: string, field: string): void {this.graph.unbindVariable(nodeId, field)- reconcileVariableLayouts(this.graph)+ reconcileVariableLayouts(this.graph, { subtrees: [nodeId] })}// --- Boolean Operations ---diff --git a/packages/core/src/layout/variables.ts b/packages/core/src/layout/variables.tsindex 7a31b17d1..efe0ada18 100644--- a/packages/core/src/layout/variables.ts+++ b/packages/core/src/layout/variables.ts@@ -1,13 +1,20 @@-import { reconcileNumericVariableBindings, type SceneGraph } from '@open-pencil/scene-graph'+import {+ reconcileNumericVariableBindings,+ type BindingScope,+ type SceneGraph+} from '@open-pencil/scene-graph'import { computeLayout } from '#core/layout'import { createLayoutRunner } from './mutations'-/** Binding evaluation is derived work, not an additional history entry. */-export function reconcileVariableLayouts(graph: SceneGraph): void {+/**+ * 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 reconcileNumericVariableBindings(graph)) {+ for (const id of reconcileNumericVariableBindings(graph, scope)) {// A deliberate binding change also invalidates a placed instance's saved Hug size.computeLayout(graph, id)runLayoutForNode(id)diff --git a/packages/core/tests/editor/variables/list-changes.test.ts b/packages/core/tests/editor/variables/list-changes.test.tsindex ce5b9060e..26b8e4eec 100644--- a/packages/core/tests/editor/variables/list-changes.test.ts+++ b/packages/core/tests/editor/variables/list-changes.test.ts@@ -45,3 +45,36 @@ test('a value edit resolves the layers bound to it', () => {expect(avatar.width).toBe(48)})++test('a value edit leaves layers bound to other variables as saved', () => {+ const { editor, collection, avatar } = drifted()+ const gap = editor.graph.createVariable('Gap', 'FLOAT', collection.id, 8)++ editor.updateVariableValue(gap.id, collection.defaultModeId, 12)++ expect(avatar.width).toBe(24)+})++test('switching the mode of a collection resolves every layer bound to its variables', () => {+ const { editor, collection, avatar } = drifted()++ editor.setActiveMode(collection.id, collection.defaultModeId)++ expect(avatar.width).toBe(40)+})++test('renaming or reordering variables refreshes the views and leaves the canvas as drawn', () => {+ const { editor, collection, size } = drifted()+ const gap = editor.graph.createVariable('Gap', 'FLOAT', collection.id, 8)+ const { sceneVersion, canvasVersion } = editor.state++ editor.renameVariable(size.id, 'Icon/Big')+ editor.setVariableOrder(collection.id, [gap.id, size.id])+ editor.updateVariableToken(size.id, { codeSyntax: { WEB: 'var(--icon-big)' } })++ expect(editor.state.sceneVersion).toBeGreaterThan(sceneVersion)+ expect(editor.state.canvasVersion).toBe(canvasVersion)++ editor.updateVariableValue(size.id, collection.defaultModeId, 48)+ expect(editor.state.canvasVersion).toBeGreaterThan(canvasVersion)+})diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.tsindex 8c386e3f9..50061e797 100644--- a/packages/scene-graph/src/variables/bindings.ts+++ b/packages/scene-graph/src/variables/bindings.ts@@ -94,10 +94,64 @@ export function resolvedPaintBindings(return changes}-/** Resolve live numeric bindings in scene units, without authoring instance overrides. */-export function reconcileNumericVariableBindings(graph: SceneGraph): string[] {+/**+ * The layers a reconcile looks at: those bound to these variables, directly or through a variable+ * aliasing them, or the layers in these subtrees. Without a scope, every layer.+ */+export type BindingScope = { variables: Iterable<string> } | { subtrees: Iterable<string> }++/** These variables and every variable that aliases one of them, at any depth and in any mode. */+export function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<string>): Set<string> {+ const found = new Set(ids)+ let grew = true+ while (grew) {+ grew = false+ for (const variable of graph.variables.values()) {+ if (found.has(variable.id)) continue+ const aliases = Object.values(variable.valuesByMode).some(+ (value) => typeof value === 'object' && 'aliasId' in value && found.has(value.aliasId)+ )+ if (aliases) {+ found.add(variable.id)+ grew = true+ }+ }+ }+ return found+}++function subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {+ const nodes: SceneNode[] = []+ const pending = [...roots]+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {+ const node = graph.getNode(id)+ if (!node) continue+ nodes.push(node)+ pending.push(...node.childIds)+ }+ return nodes+}++function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {+ if (!scope) return graph.getAllNodes()+ if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)+ const variables = variablesResolvingThrough(graph, scope.variables)+ return [...graph.getAllNodes()].filter((node) =>+ Object.values(node.boundVariables).some((id) => variables.has(id))+ )+}++/**+ * Resolve live numeric bindings in scene units, without authoring instance overrides. A scope+ * limits it to the layers a change can reach, so layers whose saved values differ from their+ * bindings elsewhere in the document are left as saved.+ */+export function reconcileNumericVariableBindings(+ graph: SceneGraph,+ scope?: BindingScope+): string[] {const changed: string[] = []- for (const node of graph.getAllNodes()) {+ for (const node of scopedNodes(graph, scope)) {const updates = resolvedNumericBindings(graph, node)if (Object.keys(updates).length === 0) continuegraph.updateNode(node.id, updates)diff --git a/packages/scene-graph/tests/variable/binding/scope.test.ts b/packages/scene-graph/tests/variable/binding/scope.test.tsnew file mode 100644index 000000000..00d8f38d4--- /dev/null+++ b/packages/scene-graph/tests/variable/binding/scope.test.ts@@ -0,0 +1,56 @@+import { describe, expect, test } from 'bun:test'++import {+ reconcileNumericVariableBindings,+ SceneGraph,+ variablesResolvingThrough+} from '@open-pencil/scene-graph'++/** Two layers saved at 10 while their bindings say otherwise, as layers in imported files can be. */+function drifted() {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Size')+ const base = graph.createVariable('Base', 'FLOAT', collection.id, 40)+ const alias = graph.createVariable('Alias', 'FLOAT', collection.id, { aliasId: base.id })+ const other = graph.createVariable('Other', 'FLOAT', collection.id, 24)+ const page = graph.getPages()[0].id+ const frame = graph.createNode('FRAME', page, { width: 10, boundVariables: { width: alias.id } })+ const child = graph.createNode('RECTANGLE', frame.id, {+ width: 10,+ boundVariables: { width: other.id }+ })+ const elsewhere = graph.createNode('RECTANGLE', page, {+ width: 10,+ boundVariables: { width: other.id }+ })+ return { graph, base, alias, other, frame, child, elsewhere }+}++describe('binding scopes', () => {+ test('a variable reaches the variables that alias it, at any depth', () => {+ const { graph, base, alias } = drifted()+ const deeper = graph.createVariable('Deeper', 'FLOAT', base.collectionId, {+ aliasId: alias.id+ })++ expect(variablesResolvingThrough(graph, [base.id])).toEqual(+ new Set([base.id, alias.id, deeper.id])+ )+ })++ test('a variable scope resolves only the layers bound to it or its aliases', () => {+ const { graph, base, frame, child, elsewhere } = drifted()++ expect(reconcileNumericVariableBindings(graph, { variables: [base.id] })).toEqual([frame.id])+ expect(frame.width).toBe(40)+ expect([child.width, elsewhere.width]).toEqual([10, 10])+ })++ test('a subtree scope resolves the layers inside it and nothing else', () => {+ const { graph, frame, child, elsewhere } = drifted()++ reconcileNumericVariableBindings(graph, { subtrees: [frame.id] })++ expect([frame.width, child.width, elsewhere.width]).toEqual([40, 24, 10])+ })+})diff --git a/packages/vue/src/canvas/surface/render-loop.ts b/packages/vue/src/canvas/surface/render-loop.tsindex cb23ea6ec..8de97b550 100644--- a/packages/vue/src/canvas/surface/render-loop.ts+++ b/packages/vue/src/canvas/surface/render-loop.ts@@ -62,7 +62,7 @@ export function createCanvasRenderLoop(let dirty = truelet frameScheduled = falselet lastRenderVersion = -1- let lastSceneVersion = -1+ let lastCanvasVersion = -1let lastSelectedIds: Set<string> | null = nullfunction renderFrame() {@@ -75,7 +75,7 @@ export function createCanvasRenderLoop(}const versionChanged = state.renderVersion !== lastRenderVersion- const sceneChanged = state.sceneVersion !== lastSceneVersion+ const sceneChanged = state.canvasVersion !== lastCanvasVersionconst selectionChanged = state.selectedIds !== lastSelectedIdsif (dirty || versionChanged || sceneChanged || selectionChanged) {dirty = false@@ -107,7 +107,7 @@ export function createCanvasRenderLoop(function markRendered() {const state = getRenderState()lastRenderVersion = state.renderVersion- lastSceneVersion = state.sceneVersion+ lastCanvasVersion = state.canvasVersionlastSelectedIds = state.selectedIds}diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.tsindex 3047bfcfc..f469f5569 100644--- a/tests/engine/text/edit-undo.test.ts+++ b/tests/engine/text/edit-undo.test.ts@@ -23,7 +23,8 @@ function setup() {editingTextId: null,currentPageId: pageId,renderVersion: 0,- sceneVersion: 0+ sceneVersion: 0,+ canvasVersion: 0} as EditorStateconst ctx: EditorContext = {@@ -33,6 +34,10 @@ function setup() {requestRender: () => {state.renderVersion++state.sceneVersion+++ state.canvasVersion+++ },+ requestRefresh: () => {+ state.sceneVersion++},requestRepaint: () => {state.renderVersion++