@pairdraw/scene-graph 0.16.0 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,21 @@ declare function captureGraphCheckpoint(graph: SceneGraph): {
8
8
  assertPropertiesOnly: () => void;
9
9
  restore: () => void;
10
10
  };
11
+ /**
12
+ * Rollback state for an edit that may only change properties, costing what the edit touches:
13
+ * every layer is kept by reference (its values shared, the parts the graph edits in place
14
+ * copied), and a layer the graph announces with `willChangeNode` is deep-copied before it
15
+ * changes. A layer written without that announcement is still caught and restored as long as
16
+ * its values were replaced rather than written into, as the graph's contract asks. The other
17
+ * tables are copied whole, as `captureGraphCheckpoint` does. Call `release` when done.
18
+ */
19
+ declare function captureEditCheckpoint(graph: SceneGraph): {
20
+ variables: Map<string, Variable>;
21
+ changedNodes: () => Map<string, SceneNode>;
22
+ assertPropertiesOnly: () => Map<string, SceneNode>;
23
+ restore: () => void;
24
+ release: () => void;
25
+ };
11
26
  //#endregion
12
- export { captureGraphCheckpoint };
27
+ export { captureEditCheckpoint, captureGraphCheckpoint };
13
28
  //# sourceMappingURL=checkpoint.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"checkpoint.d.ts","names":[],"sources":["../src/checkpoint.ts"],"mappings":";;;;iBAKgB,uBAAuB,OAAO;qBAAA"}
1
+ {"version":3,"file":"checkpoint.d.ts","names":[],"sources":["../src/checkpoint.ts"],"mappings":";;;;iBA+HgB,uBAAuB,OAAO;;;;;;;;;;;;;;iBAiH9B,sBAAsB,OAAO;yBAAA;EAmBlB,oBAAA,YAAY;EAUJ,4BAAA,YAAY"}
@@ -1,12 +1,13 @@
1
1
  import { isEqual } from "es-toolkit";
2
2
  //#region src/checkpoint.ts
3
- /** Capture rollback state without changing graph or surviving object identities. */
4
- function captureGraphCheckpoint(graph) {
5
- const nodeRefs = new Map(graph.nodes);
3
+ /**
4
+ * The document state outside its layers, copied: variables, collections, modes, the instance
5
+ * index, libraries, images, and document metadata, which a rollback restores in place.
6
+ */
7
+ function captureTables(graph) {
6
8
  const variableRefs = new Map(graph.variables);
7
9
  const collectionRefs = new Map(graph.variableCollections);
8
10
  const snapshot = structuredClone({
9
- nodes: graph.nodes,
10
11
  variables: graph.variables,
11
12
  variableCollections: graph.variableCollections,
12
13
  activeMode: graph.activeMode,
@@ -18,24 +19,16 @@ function captureGraphCheckpoint(graph) {
18
19
  documentColorSpace: graph.documentColorSpace
19
20
  });
20
21
  const images = new Map(graph.images);
21
- function assertPropertiesOnly() {
22
- if (snapshot.nodes.size !== graph.nodes.size || snapshot.variables.size !== graph.variables.size) throw new Error("Atomic tools must not create or remove nodes or variables");
23
- for (const [id, before] of snapshot.nodes) {
24
- const after = graph.nodes.get(id);
25
- if (!after || after !== nodeRefs.get(id) || before.id !== after.id || before.type !== after.type || before.parentId !== after.parentId || before.componentId !== after.componentId || !isEqual(before.childIds, after.childIds)) throw new Error("Atomic tools must not change node hierarchy or identity");
26
- }
22
+ function assertVariablesKept() {
27
23
  for (const [id, before] of snapshot.variables) {
28
24
  const after = graph.variables.get(id);
29
25
  if (!after || after !== variableRefs.get(id) || before.id !== after.id || before.collectionId !== after.collectionId || before.type !== after.type) throw new Error("Atomic tools must not change variable identity");
30
26
  }
31
- assertDocumentUnchanged();
32
27
  }
33
28
  function assertDocumentUnchanged() {
34
29
  if (!isEqual(snapshot.variableCollections, graph.variableCollections) || !isEqual(snapshot.activeMode, graph.activeMode) || !isEqual(snapshot.instanceIndex, graph.instanceIndex) || !isEqual(snapshot.enabledLibraries, graph.enabledLibraries) || images.size !== graph.images.size || [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) || graph.rootId !== snapshot.rootId || graph.documentColorSpace !== snapshot.documentColorSpace || graph.figKiwiVersion !== snapshot.figKiwiVersion || !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)) throw new Error("Atomic tools must not change collections, assets or document metadata");
35
30
  }
36
31
  function restore() {
37
- const failedNodes = new Map(graph.nodes);
38
- restoreObjects(graph.nodes, snapshot.nodes, nodeRefs);
39
32
  restoreObjects(graph.variables, snapshot.variables, variableRefs);
40
33
  restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs);
41
34
  restoreMap(graph.activeMode, structuredClone(snapshot.activeMode));
@@ -46,18 +39,193 @@ function captureGraphCheckpoint(graph) {
46
39
  graph.figKiwiVersion = snapshot.figKiwiVersion;
47
40
  graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated);
48
41
  graph.documentColorSpace = snapshot.documentColorSpace;
49
- graph.clearAbsPosCache();
50
- for (const [id, node] of failedNodes) if (!graph.nodes.has(id)) graph.emitter.emit("node:deleted", id, node.parentId);
51
- for (const [id, node] of graph.nodes) if (failedNodes.has(id)) graph.emitter.emit("node:updated", id, node);
52
- else graph.emitter.emit("node:created", node);
53
42
  }
54
43
  return {
55
- nodes: snapshot.nodes,
56
44
  variables: snapshot.variables,
45
+ variableCount: snapshot.variables.size,
46
+ assertVariablesKept,
47
+ assertDocumentUnchanged,
48
+ restore
49
+ };
50
+ }
51
+ function assertSameNodes(graph, refs, variableCount) {
52
+ if (refs.size !== graph.nodes.size || variableCount !== graph.variables.size) throw new Error("Atomic tools must not create or remove nodes or variables");
53
+ }
54
+ function assertHierarchyKept(graph, refs, before, id) {
55
+ const after = graph.nodes.get(id);
56
+ if (!after || after !== refs.get(id) || before.id !== after.id || before.type !== after.type || before.parentId !== after.parentId || before.componentId !== after.componentId || !isEqual(before.childIds, after.childIds)) throw new Error("Atomic tools must not change node hierarchy or identity");
57
+ }
58
+ /**
59
+ * Lets consumers know the restored hierarchy and indexes, once all of it is in place: removed
60
+ * layers first, then the layers put back, then `changed` ones.
61
+ */
62
+ function announceRestore(graph, failedNodes, changed) {
63
+ for (const [id, node] of failedNodes) if (!graph.nodes.has(id)) graph.emitter.emit("node:deleted", id, node.parentId);
64
+ for (const id of changed) {
65
+ const node = graph.nodes.get(id);
66
+ if (node && failedNodes.has(id)) graph.emitter.emit("node:updated", id, node);
67
+ }
68
+ for (const node of graph.nodes.values()) if (!failedNodes.has(node.id)) graph.emitter.emit("node:created", node);
69
+ }
70
+ /** Capture rollback state without changing graph or surviving object identities. */
71
+ function captureGraphCheckpoint(graph) {
72
+ const nodeRefs = new Map(graph.nodes);
73
+ const nodes = structuredClone(graph.nodes);
74
+ const tables = captureTables(graph);
75
+ function assertPropertiesOnly() {
76
+ assertSameNodes(graph, nodeRefs, tables.variableCount);
77
+ for (const [id, before] of nodes) assertHierarchyKept(graph, nodeRefs, before, id);
78
+ tables.assertVariablesKept();
79
+ tables.assertDocumentUnchanged();
80
+ }
81
+ function restore() {
82
+ const failedNodes = new Map(graph.nodes);
83
+ restoreObjects(graph.nodes, nodes, nodeRefs);
84
+ tables.restore();
85
+ graph.clearAbsPosCache();
86
+ announceRestore(graph, failedNodes, graph.nodes.keys());
87
+ }
88
+ return {
89
+ nodes,
90
+ variables: tables.variables,
57
91
  assertPropertiesOnly,
58
92
  restore
59
93
  };
60
94
  }
95
+ function copyOverrides(state) {
96
+ return {
97
+ self: new Map(state.self),
98
+ descendants: new Map([...state.descendants].map(([id, fields]) => [id, new Map(fields)]))
99
+ };
100
+ }
101
+ /**
102
+ * A layer's fields as they are, sharing their values, with the parts the graph edits in place
103
+ * (child list, source metadata, override maps) copied, as undo recording copies a page.
104
+ */
105
+ function referenceCopy(node) {
106
+ const { source } = node;
107
+ return {
108
+ ...node,
109
+ childIds: [...node.childIds],
110
+ source: {
111
+ ...source,
112
+ fig: {
113
+ ...source.fig,
114
+ rawNodeFields: { ...source.fig.rawNodeFields }
115
+ }
116
+ },
117
+ instanceOverrides: copyOverrides(node.instanceOverrides)
118
+ };
119
+ }
120
+ function keyCount(value) {
121
+ let count = 0;
122
+ for (const key in value) if (Object.hasOwn(value, key)) count++;
123
+ return count;
124
+ }
125
+ /**
126
+ * Whether `current` holds the same keys as `saved`, each with the same value, except `skip`;
127
+ * `savedKeys` is how many keys `saved` has, when already counted.
128
+ */
129
+ function sameFields(current, saved, skip, savedKeys = keyCount(saved)) {
130
+ let currentKeys = 0;
131
+ for (const key in current) {
132
+ if (!Object.hasOwn(current, key)) continue;
133
+ currentKeys++;
134
+ if (skip?.has(key)) continue;
135
+ if (current[key] !== saved[key]) return false;
136
+ }
137
+ return currentKeys === savedKeys;
138
+ }
139
+ function sameMap(current, saved) {
140
+ if (current.size !== saved.size) return false;
141
+ for (const [key, value] of current) if (saved.get(key) !== value) return false;
142
+ return true;
143
+ }
144
+ const COPIED_FIELDS = /* @__PURE__ */ new Set([
145
+ "childIds",
146
+ "source",
147
+ "instanceOverrides"
148
+ ]);
149
+ const SOURCE_FIG = /* @__PURE__ */ new Set(["fig"]);
150
+ const FIG_RAW_FIELDS = /* @__PURE__ */ new Set(["rawNodeFields"]);
151
+ /** Whether anything of `node` differs from its reference copy, even written in place. */
152
+ function differs(node, { node: saved, fields }) {
153
+ const { source, instanceOverrides: overrides } = node;
154
+ const savedOverrides = saved.instanceOverrides;
155
+ return !(sameFields(node, saved, COPIED_FIELDS, fields) && isEqual(node.childIds, saved.childIds) && sameFields(source, saved.source, SOURCE_FIG) && sameFields(source.fig, saved.source.fig, FIG_RAW_FIELDS) && sameFields(source.fig.rawNodeFields, saved.source.fig.rawNodeFields) && sameMap(overrides.self, savedOverrides.self) && overrides.descendants.size === savedOverrides.descendants.size && [...overrides.descendants].every(([id, fields]) => {
156
+ const savedFields = savedOverrides.descendants.get(id);
157
+ return savedFields !== void 0 && sameMap(fields, savedFields);
158
+ }));
159
+ }
160
+ /**
161
+ * Rollback state for an edit that may only change properties, costing what the edit touches:
162
+ * every layer is kept by reference (its values shared, the parts the graph edits in place
163
+ * copied), and a layer the graph announces with `willChangeNode` is deep-copied before it
164
+ * changes. A layer written without that announcement is still caught and restored as long as
165
+ * its values were replaced rather than written into, as the graph's contract asks. The other
166
+ * tables are copied whole, as `captureGraphCheckpoint` does. Call `release` when done.
167
+ */
168
+ function captureEditCheckpoint(graph) {
169
+ const nodeRefs = new Map(graph.nodes);
170
+ const references = /* @__PURE__ */ new Map();
171
+ for (const [id, node] of nodeRefs) {
172
+ const copy = referenceCopy(node);
173
+ references.set(id, {
174
+ node: copy,
175
+ fields: keyCount(copy)
176
+ });
177
+ }
178
+ const announced = /* @__PURE__ */ new Map();
179
+ const release = graph.observeNodeChanges({
180
+ created: () => void 0,
181
+ before: (node) => {
182
+ const saved = references.get(node.id);
183
+ if (saved && !announced.has(node.id)) announced.set(node.id, structuredClone(saved.node));
184
+ }
185
+ });
186
+ const tables = captureTables(graph);
187
+ /** Each layer the edit changed so far, as it was before: announced ones and any other. */
188
+ function changedNodes() {
189
+ const changed = new Map(announced);
190
+ for (const [id, node] of graph.nodes) {
191
+ const saved = references.get(id);
192
+ if (saved && !changed.has(id) && differs(node, saved)) changed.set(id, saved.node);
193
+ }
194
+ return changed;
195
+ }
196
+ /** Throws unless the edit only changed properties; returns what it changed, as `changedNodes`. */
197
+ function assertPropertiesOnly() {
198
+ assertSameNodes(graph, nodeRefs, tables.variableCount);
199
+ for (const [id, ref] of nodeRefs) if (graph.nodes.get(id) !== ref) throw new Error("Atomic tools must not change node hierarchy or identity");
200
+ const changed = changedNodes();
201
+ for (const [id, before] of changed) assertHierarchyKept(graph, nodeRefs, before, id);
202
+ tables.assertVariablesKept();
203
+ tables.assertDocumentUnchanged();
204
+ return changed;
205
+ }
206
+ function restore() {
207
+ const changed = changedNodes();
208
+ const failedNodes = new Map(graph.nodes);
209
+ graph.nodes.clear();
210
+ for (const [id, node] of nodeRefs) graph.nodes.set(id, node);
211
+ for (const [id, saved] of changed) {
212
+ const node = nodeRefs.get(id);
213
+ if (!node) continue;
214
+ for (const key of Object.keys(node)) if (!(key in saved)) Reflect.deleteProperty(node, key);
215
+ Object.assign(node, announced.has(id) ? structuredClone(saved) : saved);
216
+ }
217
+ tables.restore();
218
+ graph.clearAbsPosCache();
219
+ announceRestore(graph, failedNodes, changed.keys());
220
+ }
221
+ return {
222
+ variables: tables.variables,
223
+ changedNodes,
224
+ assertPropertiesOnly,
225
+ restore,
226
+ release
227
+ };
228
+ }
61
229
  function restoreObjects(target, snapshot, refs) {
62
230
  target.clear();
63
231
  for (const [id, saved] of snapshot) {
@@ -73,6 +241,6 @@ function restoreMap(target, saved) {
73
241
  for (const [key, value] of saved) target.set(key, value);
74
242
  }
75
243
  //#endregion
76
- export { captureGraphCheckpoint };
244
+ export { captureEditCheckpoint, captureGraphCheckpoint };
77
245
 
78
246
  //# sourceMappingURL=checkpoint.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"checkpoint.js","names":[],"sources":["../src/checkpoint.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit'\n\nimport type { SceneGraph } from './graph'\n\n/** Capture rollback state without changing graph or surviving object identities. */\nexport function captureGraphCheckpoint(graph: SceneGraph) {\n const nodeRefs = new Map(graph.nodes)\n const variableRefs = new Map(graph.variables)\n const collectionRefs = new Map(graph.variableCollections)\n const snapshot = structuredClone({\n nodes: graph.nodes,\n variables: graph.variables,\n variableCollections: graph.variableCollections,\n activeMode: graph.activeMode,\n instanceIndex: graph.instanceIndex,\n enabledLibraries: graph.enabledLibraries,\n rootId: graph.rootId,\n figKiwiVersion: graph.figKiwiVersion,\n figSchemaDeflated: graph.figSchemaDeflated,\n documentColorSpace: graph.documentColorSpace\n })\n // Atomic property tools cannot edit assets. Retain existing buffers, not copies of every bitmap.\n const images = new Map(graph.images)\n\n function assertPropertiesOnly() {\n if (\n snapshot.nodes.size !== graph.nodes.size ||\n snapshot.variables.size !== graph.variables.size\n )\n throw new Error('Atomic tools must not create or remove nodes or variables')\n for (const [id, before] of snapshot.nodes) {\n const after = graph.nodes.get(id)\n if (\n !after ||\n after !== nodeRefs.get(id) ||\n before.id !== after.id ||\n before.type !== after.type ||\n before.parentId !== after.parentId ||\n before.componentId !== after.componentId ||\n !isEqual(before.childIds, after.childIds)\n ) {\n throw new Error('Atomic tools must not change node hierarchy or identity')\n }\n }\n for (const [id, before] of snapshot.variables) {\n const after = graph.variables.get(id)\n if (\n !after ||\n after !== variableRefs.get(id) ||\n before.id !== after.id ||\n before.collectionId !== after.collectionId ||\n before.type !== after.type\n )\n throw new Error('Atomic tools must not change variable identity')\n }\n assertDocumentUnchanged()\n }\n\n function assertDocumentUnchanged() {\n if (\n !isEqual(snapshot.variableCollections, graph.variableCollections) ||\n !isEqual(snapshot.activeMode, graph.activeMode) ||\n !isEqual(snapshot.instanceIndex, graph.instanceIndex) ||\n !isEqual(snapshot.enabledLibraries, graph.enabledLibraries) ||\n images.size !== graph.images.size ||\n [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||\n graph.rootId !== snapshot.rootId ||\n graph.documentColorSpace !== snapshot.documentColorSpace ||\n graph.figKiwiVersion !== snapshot.figKiwiVersion ||\n !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)\n ) {\n throw new Error('Atomic tools must not change collections, assets or document metadata')\n }\n }\n\n function restore() {\n const failedNodes = new Map(graph.nodes)\n restoreObjects(graph.nodes, snapshot.nodes, nodeRefs)\n restoreObjects(graph.variables, snapshot.variables, variableRefs)\n restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs)\n restoreMap(graph.activeMode, structuredClone(snapshot.activeMode))\n restoreMap(graph.instanceIndex, structuredClone(snapshot.instanceIndex))\n restoreMap(graph.enabledLibraries, structuredClone(snapshot.enabledLibraries))\n restoreMap(graph.images, images)\n graph.rootId = snapshot.rootId\n graph.figKiwiVersion = snapshot.figKiwiVersion\n graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated)\n graph.documentColorSpace = snapshot.documentColorSpace\n graph.clearAbsPosCache()\n // Notify consumers only after the complete hierarchy and indexes have been restored.\n for (const [id, node] of failedNodes) {\n if (!graph.nodes.has(id)) graph.emitter.emit('node:deleted', id, node.parentId)\n }\n for (const [id, node] of graph.nodes) {\n if (failedNodes.has(id)) graph.emitter.emit('node:updated', id, node)\n else graph.emitter.emit('node:created', node)\n }\n }\n\n return { nodes: snapshot.nodes, variables: snapshot.variables, assertPropertiesOnly, restore }\n}\n\nfunction restoreObjects<T extends object>(\n target: Map<string, T>,\n snapshot: Map<string, T>,\n refs: Map<string, T>\n) {\n target.clear()\n for (const [id, saved] of snapshot) {\n const original = refs.get(id)\n if (!original) throw new Error(`Missing checkpoint reference: ${id}`)\n for (const key of Object.keys(original) as (keyof T)[]) {\n if (!(key in saved)) Reflect.deleteProperty(original, key)\n }\n Object.assign(original, structuredClone(saved))\n target.set(id, original)\n }\n}\n\nfunction restoreMap<K, V>(target: Map<K, V>, saved: Map<K, V>) {\n target.clear()\n for (const [key, value] of saved) target.set(key, value)\n}\n"],"mappings":";;;AAKA,SAAgB,uBAAuB,OAAmB;CACxD,MAAM,WAAW,IAAI,IAAI,MAAM,KAAK;CACpC,MAAM,eAAe,IAAI,IAAI,MAAM,SAAS;CAC5C,MAAM,iBAAiB,IAAI,IAAI,MAAM,mBAAmB;CACxD,MAAM,WAAW,gBAAgB;EAC/B,OAAO,MAAM;EACb,WAAW,MAAM;EACjB,qBAAqB,MAAM;EAC3B,YAAY,MAAM;EAClB,eAAe,MAAM;EACrB,kBAAkB,MAAM;EACxB,QAAQ,MAAM;EACd,gBAAgB,MAAM;EACtB,mBAAmB,MAAM;EACzB,oBAAoB,MAAM;CAC5B,CAAC;CAED,MAAM,SAAS,IAAI,IAAI,MAAM,MAAM;CAEnC,SAAS,uBAAuB;EAC9B,IACE,SAAS,MAAM,SAAS,MAAM,MAAM,QACpC,SAAS,UAAU,SAAS,MAAM,UAAU,MAE5C,MAAM,IAAI,MAAM,2DAA2D;EAC7E,KAAK,MAAM,CAAC,IAAI,WAAW,SAAS,OAAO;GACzC,MAAM,QAAQ,MAAM,MAAM,IAAI,EAAE;GAChC,IACE,CAAC,SACD,UAAU,SAAS,IAAI,EAAE,KACzB,OAAO,OAAO,MAAM,MACpB,OAAO,SAAS,MAAM,QACtB,OAAO,aAAa,MAAM,YAC1B,OAAO,gBAAgB,MAAM,eAC7B,CAAC,QAAQ,OAAO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MAAM,SAAS,SAAS;EACxB,MAAM,iBAAiB,SAAS;EAChC,MAAM,oBAAoB,gBAAgB,SAAS,iBAAiB;EACpE,MAAM,qBAAqB,SAAS;EACpC,MAAM,iBAAiB;EAEvB,KAAK,MAAM,CAAC,IAAI,SAAS,aACvB,IAAI,CAAC,MAAM,MAAM,IAAI,EAAE,GAAG,MAAM,QAAQ,KAAK,gBAAgB,IAAI,KAAK,QAAQ;EAEhF,KAAK,MAAM,CAAC,IAAI,SAAS,MAAM,OAC7B,IAAI,YAAY,IAAI,EAAE,GAAG,MAAM,QAAQ,KAAK,gBAAgB,IAAI,IAAI;OAC/D,MAAM,QAAQ,KAAK,gBAAgB,IAAI;CAEhD;CAEA,OAAO;EAAE,OAAO,SAAS;EAAO,WAAW,SAAS;EAAW;EAAsB;CAAQ;AAC/F;AAEA,SAAS,eACP,QACA,UACA,MACA;CACA,OAAO,MAAM;CACb,KAAK,MAAM,CAAC,IAAI,UAAU,UAAU;EAClC,MAAM,WAAW,KAAK,IAAI,EAAE;EAC5B,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,iCAAiC,IAAI;EACpE,KAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,GACpC,IAAI,EAAE,OAAO,QAAQ,QAAQ,eAAe,UAAU,GAAG;EAE3D,OAAO,OAAO,UAAU,gBAAgB,KAAK,CAAC;EAC9C,OAAO,IAAI,IAAI,QAAQ;CACzB;AACF;AAEA,SAAS,WAAiB,QAAmB,OAAkB;CAC7D,OAAO,MAAM;CACb,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,OAAO,IAAI,KAAK,KAAK;AACzD"}
1
+ {"version":3,"file":"checkpoint.js","names":[],"sources":["../src/checkpoint.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit'\n\nimport type { SceneGraph } from './graph'\nimport type { InstanceOverrideState } from './instances/overrides'\nimport type { SceneNode } from './types'\n\n/**\n * The document state outside its layers, copied: variables, collections, modes, the instance\n * index, libraries, images, and document metadata, which a rollback restores in place.\n */\nfunction captureTables(graph: SceneGraph) {\n const variableRefs = new Map(graph.variables)\n const collectionRefs = new Map(graph.variableCollections)\n const snapshot = structuredClone({\n variables: graph.variables,\n variableCollections: graph.variableCollections,\n activeMode: graph.activeMode,\n instanceIndex: graph.instanceIndex,\n enabledLibraries: graph.enabledLibraries,\n rootId: graph.rootId,\n figKiwiVersion: graph.figKiwiVersion,\n figSchemaDeflated: graph.figSchemaDeflated,\n documentColorSpace: graph.documentColorSpace\n })\n // Atomic property tools cannot edit assets. Retain existing buffers, not copies of every bitmap.\n const images = new Map(graph.images)\n\n function assertVariablesKept() {\n for (const [id, before] of snapshot.variables) {\n const after = graph.variables.get(id)\n if (\n !after ||\n after !== variableRefs.get(id) ||\n before.id !== after.id ||\n before.collectionId !== after.collectionId ||\n before.type !== after.type\n )\n throw new Error('Atomic tools must not change variable identity')\n }\n }\n\n function assertDocumentUnchanged() {\n if (\n !isEqual(snapshot.variableCollections, graph.variableCollections) ||\n !isEqual(snapshot.activeMode, graph.activeMode) ||\n !isEqual(snapshot.instanceIndex, graph.instanceIndex) ||\n !isEqual(snapshot.enabledLibraries, graph.enabledLibraries) ||\n images.size !== graph.images.size ||\n [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||\n graph.rootId !== snapshot.rootId ||\n graph.documentColorSpace !== snapshot.documentColorSpace ||\n graph.figKiwiVersion !== snapshot.figKiwiVersion ||\n !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)\n ) {\n throw new Error('Atomic tools must not change collections, assets or document metadata')\n }\n }\n\n function restore() {\n restoreObjects(graph.variables, snapshot.variables, variableRefs)\n restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs)\n restoreMap(graph.activeMode, structuredClone(snapshot.activeMode))\n restoreMap(graph.instanceIndex, structuredClone(snapshot.instanceIndex))\n restoreMap(graph.enabledLibraries, structuredClone(snapshot.enabledLibraries))\n restoreMap(graph.images, images)\n graph.rootId = snapshot.rootId\n graph.figKiwiVersion = snapshot.figKiwiVersion\n graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated)\n graph.documentColorSpace = snapshot.documentColorSpace\n }\n\n return {\n variables: snapshot.variables,\n variableCount: snapshot.variables.size,\n assertVariablesKept,\n assertDocumentUnchanged,\n restore\n }\n}\n\nfunction assertSameNodes(graph: SceneGraph, refs: Map<string, SceneNode>, variableCount: number) {\n if (refs.size !== graph.nodes.size || variableCount !== graph.variables.size)\n throw new Error('Atomic tools must not create or remove nodes or variables')\n}\n\nfunction assertHierarchyKept(\n graph: SceneGraph,\n refs: Map<string, SceneNode>,\n before: SceneNode,\n id: string\n) {\n const after = graph.nodes.get(id)\n if (\n !after ||\n after !== refs.get(id) ||\n before.id !== after.id ||\n before.type !== after.type ||\n before.parentId !== after.parentId ||\n before.componentId !== after.componentId ||\n !isEqual(before.childIds, after.childIds)\n ) {\n throw new Error('Atomic tools must not change node hierarchy or identity')\n }\n}\n\n/**\n * Lets consumers know the restored hierarchy and indexes, once all of it is in place: removed\n * layers first, then the layers put back, then `changed` ones.\n */\nfunction announceRestore(\n graph: SceneGraph,\n failedNodes: Map<string, SceneNode>,\n changed: Iterable<string>\n) {\n for (const [id, node] of failedNodes) {\n if (!graph.nodes.has(id)) graph.emitter.emit('node:deleted', id, node.parentId)\n }\n for (const id of changed) {\n const node = graph.nodes.get(id)\n if (node && failedNodes.has(id)) graph.emitter.emit('node:updated', id, node)\n }\n for (const node of graph.nodes.values()) {\n if (!failedNodes.has(node.id)) graph.emitter.emit('node:created', node)\n }\n}\n\n/** Capture rollback state without changing graph or surviving object identities. */\nexport function captureGraphCheckpoint(graph: SceneGraph) {\n const nodeRefs = new Map(graph.nodes)\n const nodes = structuredClone(graph.nodes)\n const tables = captureTables(graph)\n\n function assertPropertiesOnly() {\n assertSameNodes(graph, nodeRefs, tables.variableCount)\n for (const [id, before] of nodes) assertHierarchyKept(graph, nodeRefs, before, id)\n tables.assertVariablesKept()\n tables.assertDocumentUnchanged()\n }\n\n function restore() {\n const failedNodes = new Map(graph.nodes)\n restoreObjects(graph.nodes, nodes, nodeRefs)\n tables.restore()\n graph.clearAbsPosCache()\n announceRestore(graph, failedNodes, graph.nodes.keys())\n }\n\n return { nodes, variables: tables.variables, assertPropertiesOnly, restore }\n}\n\nfunction copyOverrides(state: InstanceOverrideState): InstanceOverrideState {\n return {\n self: new Map(state.self),\n descendants: new Map([...state.descendants].map(([id, fields]) => [id, new Map(fields)]))\n }\n}\n\n/**\n * A layer's fields as they are, sharing their values, with the parts the graph edits in place\n * (child list, source metadata, override maps) copied, as undo recording copies a page.\n */\nfunction referenceCopy(node: SceneNode): SceneNode {\n const { source } = node\n return {\n ...node,\n childIds: [...node.childIds],\n source: { ...source, fig: { ...source.fig, rawNodeFields: { ...source.fig.rawNodeFields } } },\n instanceOverrides: copyOverrides(node.instanceOverrides)\n }\n}\n\nfunction keyCount(value: object): number {\n let count = 0\n for (const key in value) if (Object.hasOwn(value, key)) count++\n return count\n}\n\n/**\n * Whether `current` holds the same keys as `saved`, each with the same value, except `skip`;\n * `savedKeys` is how many keys `saved` has, when already counted.\n */\nfunction sameFields<T extends object>(\n current: T,\n saved: T,\n skip?: ReadonlySet<string>,\n savedKeys = keyCount(saved)\n): boolean {\n let currentKeys = 0\n for (const key in current) {\n if (!Object.hasOwn(current, key)) continue\n currentKeys++\n if (skip?.has(key)) continue\n if (current[key] !== saved[key]) return false\n }\n return currentKeys === savedKeys\n}\n\nfunction sameMap<K, V>(current: Map<K, V>, saved: Map<K, V>): boolean {\n if (current.size !== saved.size) return false\n for (const [key, value] of current) if (saved.get(key) !== value) return false\n return true\n}\n\nconst COPIED_FIELDS: ReadonlySet<string> = new Set(['childIds', 'source', 'instanceOverrides'])\nconst SOURCE_FIG: ReadonlySet<string> = new Set(['fig'])\nconst FIG_RAW_FIELDS: ReadonlySet<string> = new Set(['rawNodeFields'])\n\n/** A layer's reference copy, and how many fields it has. */\ninterface Reference {\n node: SceneNode\n fields: number\n}\n\n/** Whether anything of `node` differs from its reference copy, even written in place. */\nfunction differs(node: SceneNode, { node: saved, fields }: Reference): boolean {\n const { source, instanceOverrides: overrides } = node\n const savedOverrides = saved.instanceOverrides\n return !(\n sameFields(node, saved, COPIED_FIELDS, fields) &&\n isEqual(node.childIds, saved.childIds) &&\n sameFields(source, saved.source, SOURCE_FIG) &&\n sameFields(source.fig, saved.source.fig, FIG_RAW_FIELDS) &&\n sameFields(source.fig.rawNodeFields, saved.source.fig.rawNodeFields) &&\n sameMap(overrides.self, savedOverrides.self) &&\n overrides.descendants.size === savedOverrides.descendants.size &&\n [...overrides.descendants].every(([id, fields]) => {\n const savedFields = savedOverrides.descendants.get(id)\n return savedFields !== undefined && sameMap(fields, savedFields)\n })\n )\n}\n\n/**\n * Rollback state for an edit that may only change properties, costing what the edit touches:\n * every layer is kept by reference (its values shared, the parts the graph edits in place\n * copied), and a layer the graph announces with `willChangeNode` is deep-copied before it\n * changes. A layer written without that announcement is still caught and restored as long as\n * its values were replaced rather than written into, as the graph's contract asks. The other\n * tables are copied whole, as `captureGraphCheckpoint` does. Call `release` when done.\n */\nexport function captureEditCheckpoint(graph: SceneGraph) {\n const nodeRefs = new Map(graph.nodes)\n const references = new Map<string, Reference>()\n for (const [id, node] of nodeRefs) {\n const copy = referenceCopy(node)\n references.set(id, { node: copy, fields: keyCount(copy) })\n }\n // Deep copies of announced layers, taken before they change.\n const announced = new Map<string, SceneNode>()\n const release = graph.observeNodeChanges({\n created: () => undefined,\n before: (node) => {\n const saved = references.get(node.id)\n if (saved && !announced.has(node.id)) announced.set(node.id, structuredClone(saved.node))\n }\n })\n const tables = captureTables(graph)\n\n /** Each layer the edit changed so far, as it was before: announced ones and any other. */\n function changedNodes(): Map<string, SceneNode> {\n const changed = new Map(announced)\n for (const [id, node] of graph.nodes) {\n const saved = references.get(id)\n if (saved && !changed.has(id) && differs(node, saved)) changed.set(id, saved.node)\n }\n return changed\n }\n\n /** Throws unless the edit only changed properties; returns what it changed, as `changedNodes`. */\n function assertPropertiesOnly(): Map<string, SceneNode> {\n assertSameNodes(graph, nodeRefs, tables.variableCount)\n for (const [id, ref] of nodeRefs) {\n if (graph.nodes.get(id) !== ref)\n throw new Error('Atomic tools must not change node hierarchy or identity')\n }\n const changed = changedNodes()\n for (const [id, before] of changed) assertHierarchyKept(graph, nodeRefs, before, id)\n tables.assertVariablesKept()\n tables.assertDocumentUnchanged()\n return changed\n }\n\n function restore() {\n const changed = changedNodes()\n const failedNodes = new Map(graph.nodes)\n graph.nodes.clear()\n for (const [id, node] of nodeRefs) graph.nodes.set(id, node)\n for (const [id, saved] of changed) {\n const node = nodeRefs.get(id)\n if (!node) continue\n for (const key of Object.keys(node) as (keyof SceneNode)[]) {\n if (!(key in saved)) Reflect.deleteProperty(node, key)\n }\n // A deep copy is the checkpoint's own; a reference copy holds the values the layer had.\n Object.assign(node, announced.has(id) ? structuredClone(saved) : saved)\n }\n tables.restore()\n graph.clearAbsPosCache()\n announceRestore(graph, failedNodes, changed.keys())\n }\n\n return { variables: tables.variables, changedNodes, assertPropertiesOnly, restore, release }\n}\n\nfunction restoreObjects<T extends object>(\n target: Map<string, T>,\n snapshot: Map<string, T>,\n refs: Map<string, T>\n) {\n target.clear()\n for (const [id, saved] of snapshot) {\n const original = refs.get(id)\n if (!original) throw new Error(`Missing checkpoint reference: ${id}`)\n for (const key of Object.keys(original) as (keyof T)[]) {\n if (!(key in saved)) Reflect.deleteProperty(original, key)\n }\n Object.assign(original, structuredClone(saved))\n target.set(id, original)\n }\n}\n\nfunction restoreMap<K, V>(target: Map<K, V>, saved: Map<K, V>) {\n target.clear()\n for (const [key, value] of saved) target.set(key, value)\n}\n"],"mappings":";;;;;;AAUA,SAAS,cAAc,OAAmB;CACxC,MAAM,eAAe,IAAI,IAAI,MAAM,SAAS;CAC5C,MAAM,iBAAiB,IAAI,IAAI,MAAM,mBAAmB;CACxD,MAAM,WAAW,gBAAgB;EAC/B,WAAW,MAAM;EACjB,qBAAqB,MAAM;EAC3B,YAAY,M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IAAI;EAC3D,KAAK,MAAM,CAAC,IAAI,UAAU,SAAS;GACjC,MAAM,OAAO,SAAS,IAAI,EAAE;GAC5B,IAAI,CAAC,MAAM;GACX,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAChC,IAAI,EAAE,OAAO,QAAQ,QAAQ,eAAe,MAAM,GAAG;GAGvD,OAAO,OAAO,MAAM,UAAU,IAAI,EAAE,IAAI,gBAAgB,KAAK,IAAI,KAAK;EACxE;EACA,OAAO,QAAQ;EACf,MAAM,iBAAiB;EACvB,gBAAgB,OAAO,aAAa,QAAQ,KAAK,CAAC;CACpD;CAEA,OAAO;EAAE,WAAW,OAAO;EAAW;EAAc;EAAsB;EAAS;CAAQ;AAC7F;AAEA,SAAS,eACP,QACA,UACA,MACA;CACA,OAAO,MAAM;CACb,KAAK,MAAM,CAAC,IAAI,UAAU,UAAU;EAClC,MAAM,WAAW,KAAK,IAAI,EAAE;EAC5B,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,iCAAiC,IAAI;EACpE,KAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,GACpC,IAAI,EAAE,OAAO,QAAQ,QAAQ,eAAe,UAAU,GAAG;EAE3D,OAAO,OAAO,UAAU,gBAAgB,KAAK,CAAC;EAC9C,OAAO,IAAI,IAAI,QAAQ;CACzB;AACF;AAEA,SAAS,WAAiB,QAAmB,OAAkB;CAC7D,OAAO,MAAM;CACb,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,OAAO,IAAI,KAAK,KAAK;AACzD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/scene-graph",
3
- "version": "0.16.0",
3
+ "version": "0.16.2",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -344,6 +344,18 @@
344
344
  "imports": {
345
345
  "#scene-graph/*": "./src/*.ts"
346
346
  },
347
+ "description": "The framework-neutral Pairdraw design document model: node types, geometry, variables, instances, and hit testing.",
348
+ "keywords": [
349
+ "pairdraw",
350
+ "design",
351
+ "scene-graph",
352
+ "geometry"
353
+ ],
354
+ "author": "Badryansah Bangsawan",
355
+ "homepage": "https://github.com/BadryansahBangsawan/pairdraw/tree/main/packages/scene-graph#readme",
356
+ "bugs": {
357
+ "url": "https://github.com/BadryansahBangsawan/pairdraw/issues"
358
+ },
347
359
  "repository": {
348
360
  "type": "git",
349
361
  "url": "git+https://github.com/BadryansahBangsawan/pairdraw.git",
package/src/checkpoint.ts CHANGED
@@ -1,14 +1,17 @@
1
1
  import { isEqual } from 'es-toolkit'
2
2
 
3
3
  import type { SceneGraph } from './graph'
4
+ import type { InstanceOverrideState } from './instances/overrides'
5
+ import type { SceneNode } from './types'
4
6
 
5
- /** Capture rollback state without changing graph or surviving object identities. */
6
- export function captureGraphCheckpoint(graph: SceneGraph) {
7
- const nodeRefs = new Map(graph.nodes)
7
+ /**
8
+ * The document state outside its layers, copied: variables, collections, modes, the instance
9
+ * index, libraries, images, and document metadata, which a rollback restores in place.
10
+ */
11
+ function captureTables(graph: SceneGraph) {
8
12
  const variableRefs = new Map(graph.variables)
9
13
  const collectionRefs = new Map(graph.variableCollections)
10
14
  const snapshot = structuredClone({
11
- nodes: graph.nodes,
12
15
  variables: graph.variables,
13
16
  variableCollections: graph.variableCollections,
14
17
  activeMode: graph.activeMode,
@@ -22,26 +25,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {
22
25
  // Atomic property tools cannot edit assets. Retain existing buffers, not copies of every bitmap.
23
26
  const images = new Map(graph.images)
24
27
 
25
- function assertPropertiesOnly() {
26
- if (
27
- snapshot.nodes.size !== graph.nodes.size ||
28
- snapshot.variables.size !== graph.variables.size
29
- )
30
- throw new Error('Atomic tools must not create or remove nodes or variables')
31
- for (const [id, before] of snapshot.nodes) {
32
- const after = graph.nodes.get(id)
33
- if (
34
- !after ||
35
- after !== nodeRefs.get(id) ||
36
- before.id !== after.id ||
37
- before.type !== after.type ||
38
- before.parentId !== after.parentId ||
39
- before.componentId !== after.componentId ||
40
- !isEqual(before.childIds, after.childIds)
41
- ) {
42
- throw new Error('Atomic tools must not change node hierarchy or identity')
43
- }
44
- }
28
+ function assertVariablesKept() {
45
29
  for (const [id, before] of snapshot.variables) {
46
30
  const after = graph.variables.get(id)
47
31
  if (
@@ -53,7 +37,6 @@ export function captureGraphCheckpoint(graph: SceneGraph) {
53
37
  )
54
38
  throw new Error('Atomic tools must not change variable identity')
55
39
  }
56
- assertDocumentUnchanged()
57
40
  }
58
41
 
59
42
  function assertDocumentUnchanged() {
@@ -74,8 +57,6 @@ export function captureGraphCheckpoint(graph: SceneGraph) {
74
57
  }
75
58
 
76
59
  function restore() {
77
- const failedNodes = new Map(graph.nodes)
78
- restoreObjects(graph.nodes, snapshot.nodes, nodeRefs)
79
60
  restoreObjects(graph.variables, snapshot.variables, variableRefs)
80
61
  restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs)
81
62
  restoreMap(graph.activeMode, structuredClone(snapshot.activeMode))
@@ -86,18 +67,239 @@ export function captureGraphCheckpoint(graph: SceneGraph) {
86
67
  graph.figKiwiVersion = snapshot.figKiwiVersion
87
68
  graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated)
88
69
  graph.documentColorSpace = snapshot.documentColorSpace
70
+ }
71
+
72
+ return {
73
+ variables: snapshot.variables,
74
+ variableCount: snapshot.variables.size,
75
+ assertVariablesKept,
76
+ assertDocumentUnchanged,
77
+ restore
78
+ }
79
+ }
80
+
81
+ function assertSameNodes(graph: SceneGraph, refs: Map<string, SceneNode>, variableCount: number) {
82
+ if (refs.size !== graph.nodes.size || variableCount !== graph.variables.size)
83
+ throw new Error('Atomic tools must not create or remove nodes or variables')
84
+ }
85
+
86
+ function assertHierarchyKept(
87
+ graph: SceneGraph,
88
+ refs: Map<string, SceneNode>,
89
+ before: SceneNode,
90
+ id: string
91
+ ) {
92
+ const after = graph.nodes.get(id)
93
+ if (
94
+ !after ||
95
+ after !== refs.get(id) ||
96
+ before.id !== after.id ||
97
+ before.type !== after.type ||
98
+ before.parentId !== after.parentId ||
99
+ before.componentId !== after.componentId ||
100
+ !isEqual(before.childIds, after.childIds)
101
+ ) {
102
+ throw new Error('Atomic tools must not change node hierarchy or identity')
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Lets consumers know the restored hierarchy and indexes, once all of it is in place: removed
108
+ * layers first, then the layers put back, then `changed` ones.
109
+ */
110
+ function announceRestore(
111
+ graph: SceneGraph,
112
+ failedNodes: Map<string, SceneNode>,
113
+ changed: Iterable<string>
114
+ ) {
115
+ for (const [id, node] of failedNodes) {
116
+ if (!graph.nodes.has(id)) graph.emitter.emit('node:deleted', id, node.parentId)
117
+ }
118
+ for (const id of changed) {
119
+ const node = graph.nodes.get(id)
120
+ if (node && failedNodes.has(id)) graph.emitter.emit('node:updated', id, node)
121
+ }
122
+ for (const node of graph.nodes.values()) {
123
+ if (!failedNodes.has(node.id)) graph.emitter.emit('node:created', node)
124
+ }
125
+ }
126
+
127
+ /** Capture rollback state without changing graph or surviving object identities. */
128
+ export function captureGraphCheckpoint(graph: SceneGraph) {
129
+ const nodeRefs = new Map(graph.nodes)
130
+ const nodes = structuredClone(graph.nodes)
131
+ const tables = captureTables(graph)
132
+
133
+ function assertPropertiesOnly() {
134
+ assertSameNodes(graph, nodeRefs, tables.variableCount)
135
+ for (const [id, before] of nodes) assertHierarchyKept(graph, nodeRefs, before, id)
136
+ tables.assertVariablesKept()
137
+ tables.assertDocumentUnchanged()
138
+ }
139
+
140
+ function restore() {
141
+ const failedNodes = new Map(graph.nodes)
142
+ restoreObjects(graph.nodes, nodes, nodeRefs)
143
+ tables.restore()
89
144
  graph.clearAbsPosCache()
90
- // Notify consumers only after the complete hierarchy and indexes have been restored.
91
- for (const [id, node] of failedNodes) {
92
- if (!graph.nodes.has(id)) graph.emitter.emit('node:deleted', id, node.parentId)
145
+ announceRestore(graph, failedNodes, graph.nodes.keys())
146
+ }
147
+
148
+ return { nodes, variables: tables.variables, assertPropertiesOnly, restore }
149
+ }
150
+
151
+ function copyOverrides(state: InstanceOverrideState): InstanceOverrideState {
152
+ return {
153
+ self: new Map(state.self),
154
+ descendants: new Map([...state.descendants].map(([id, fields]) => [id, new Map(fields)]))
155
+ }
156
+ }
157
+
158
+ /**
159
+ * A layer's fields as they are, sharing their values, with the parts the graph edits in place
160
+ * (child list, source metadata, override maps) copied, as undo recording copies a page.
161
+ */
162
+ function referenceCopy(node: SceneNode): SceneNode {
163
+ const { source } = node
164
+ return {
165
+ ...node,
166
+ childIds: [...node.childIds],
167
+ source: { ...source, fig: { ...source.fig, rawNodeFields: { ...source.fig.rawNodeFields } } },
168
+ instanceOverrides: copyOverrides(node.instanceOverrides)
169
+ }
170
+ }
171
+
172
+ function keyCount(value: object): number {
173
+ let count = 0
174
+ for (const key in value) if (Object.hasOwn(value, key)) count++
175
+ return count
176
+ }
177
+
178
+ /**
179
+ * Whether `current` holds the same keys as `saved`, each with the same value, except `skip`;
180
+ * `savedKeys` is how many keys `saved` has, when already counted.
181
+ */
182
+ function sameFields<T extends object>(
183
+ current: T,
184
+ saved: T,
185
+ skip?: ReadonlySet<string>,
186
+ savedKeys = keyCount(saved)
187
+ ): boolean {
188
+ let currentKeys = 0
189
+ for (const key in current) {
190
+ if (!Object.hasOwn(current, key)) continue
191
+ currentKeys++
192
+ if (skip?.has(key)) continue
193
+ if (current[key] !== saved[key]) return false
194
+ }
195
+ return currentKeys === savedKeys
196
+ }
197
+
198
+ function sameMap<K, V>(current: Map<K, V>, saved: Map<K, V>): boolean {
199
+ if (current.size !== saved.size) return false
200
+ for (const [key, value] of current) if (saved.get(key) !== value) return false
201
+ return true
202
+ }
203
+
204
+ const COPIED_FIELDS: ReadonlySet<string> = new Set(['childIds', 'source', 'instanceOverrides'])
205
+ const SOURCE_FIG: ReadonlySet<string> = new Set(['fig'])
206
+ const FIG_RAW_FIELDS: ReadonlySet<string> = new Set(['rawNodeFields'])
207
+
208
+ /** A layer's reference copy, and how many fields it has. */
209
+ interface Reference {
210
+ node: SceneNode
211
+ fields: number
212
+ }
213
+
214
+ /** Whether anything of `node` differs from its reference copy, even written in place. */
215
+ function differs(node: SceneNode, { node: saved, fields }: Reference): boolean {
216
+ const { source, instanceOverrides: overrides } = node
217
+ const savedOverrides = saved.instanceOverrides
218
+ return !(
219
+ sameFields(node, saved, COPIED_FIELDS, fields) &&
220
+ isEqual(node.childIds, saved.childIds) &&
221
+ sameFields(source, saved.source, SOURCE_FIG) &&
222
+ sameFields(source.fig, saved.source.fig, FIG_RAW_FIELDS) &&
223
+ sameFields(source.fig.rawNodeFields, saved.source.fig.rawNodeFields) &&
224
+ sameMap(overrides.self, savedOverrides.self) &&
225
+ overrides.descendants.size === savedOverrides.descendants.size &&
226
+ [...overrides.descendants].every(([id, fields]) => {
227
+ const savedFields = savedOverrides.descendants.get(id)
228
+ return savedFields !== undefined && sameMap(fields, savedFields)
229
+ })
230
+ )
231
+ }
232
+
233
+ /**
234
+ * Rollback state for an edit that may only change properties, costing what the edit touches:
235
+ * every layer is kept by reference (its values shared, the parts the graph edits in place
236
+ * copied), and a layer the graph announces with `willChangeNode` is deep-copied before it
237
+ * changes. A layer written without that announcement is still caught and restored as long as
238
+ * its values were replaced rather than written into, as the graph's contract asks. The other
239
+ * tables are copied whole, as `captureGraphCheckpoint` does. Call `release` when done.
240
+ */
241
+ export function captureEditCheckpoint(graph: SceneGraph) {
242
+ const nodeRefs = new Map(graph.nodes)
243
+ const references = new Map<string, Reference>()
244
+ for (const [id, node] of nodeRefs) {
245
+ const copy = referenceCopy(node)
246
+ references.set(id, { node: copy, fields: keyCount(copy) })
247
+ }
248
+ // Deep copies of announced layers, taken before they change.
249
+ const announced = new Map<string, SceneNode>()
250
+ const release = graph.observeNodeChanges({
251
+ created: () => undefined,
252
+ before: (node) => {
253
+ const saved = references.get(node.id)
254
+ if (saved && !announced.has(node.id)) announced.set(node.id, structuredClone(saved.node))
93
255
  }
256
+ })
257
+ const tables = captureTables(graph)
258
+
259
+ /** Each layer the edit changed so far, as it was before: announced ones and any other. */
260
+ function changedNodes(): Map<string, SceneNode> {
261
+ const changed = new Map(announced)
94
262
  for (const [id, node] of graph.nodes) {
95
- if (failedNodes.has(id)) graph.emitter.emit('node:updated', id, node)
96
- else graph.emitter.emit('node:created', node)
263
+ const saved = references.get(id)
264
+ if (saved && !changed.has(id) && differs(node, saved)) changed.set(id, saved.node)
265
+ }
266
+ return changed
267
+ }
268
+
269
+ /** Throws unless the edit only changed properties; returns what it changed, as `changedNodes`. */
270
+ function assertPropertiesOnly(): Map<string, SceneNode> {
271
+ assertSameNodes(graph, nodeRefs, tables.variableCount)
272
+ for (const [id, ref] of nodeRefs) {
273
+ if (graph.nodes.get(id) !== ref)
274
+ throw new Error('Atomic tools must not change node hierarchy or identity')
97
275
  }
276
+ const changed = changedNodes()
277
+ for (const [id, before] of changed) assertHierarchyKept(graph, nodeRefs, before, id)
278
+ tables.assertVariablesKept()
279
+ tables.assertDocumentUnchanged()
280
+ return changed
281
+ }
282
+
283
+ function restore() {
284
+ const changed = changedNodes()
285
+ const failedNodes = new Map(graph.nodes)
286
+ graph.nodes.clear()
287
+ for (const [id, node] of nodeRefs) graph.nodes.set(id, node)
288
+ for (const [id, saved] of changed) {
289
+ const node = nodeRefs.get(id)
290
+ if (!node) continue
291
+ for (const key of Object.keys(node) as (keyof SceneNode)[]) {
292
+ if (!(key in saved)) Reflect.deleteProperty(node, key)
293
+ }
294
+ // A deep copy is the checkpoint's own; a reference copy holds the values the layer had.
295
+ Object.assign(node, announced.has(id) ? structuredClone(saved) : saved)
296
+ }
297
+ tables.restore()
298
+ graph.clearAbsPosCache()
299
+ announceRestore(graph, failedNodes, changed.keys())
98
300
  }
99
301
 
100
- return { nodes: snapshot.nodes, variables: snapshot.variables, assertPropertiesOnly, restore }
302
+ return { variables: tables.variables, changedNodes, assertPropertiesOnly, restore, release }
101
303
  }
102
304
 
103
305
  function restoreObjects<T extends object>(