@open-pencil/scene-graph 0.17.0-beta.1 → 0.17.0-beta.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.
Files changed (236) hide show
  1. package/dist/arrow-caps.d.ts.map +1 -1
  2. package/dist/arrow-caps.js +2 -5
  3. package/dist/arrow-caps.js.map +1 -1
  4. package/dist/behaviours/index.d.ts +2 -2
  5. package/dist/behaviours/index.js +2 -2
  6. package/dist/behaviours/kinds.d.ts +11 -5
  7. package/dist/behaviours/kinds.d.ts.map +1 -1
  8. package/dist/behaviours/kinds.js +76 -75
  9. package/dist/behaviours/kinds.js.map +1 -1
  10. package/dist/behaviours/layers.d.ts.map +1 -1
  11. package/dist/behaviours/layers.js +3 -2
  12. package/dist/behaviours/layers.js.map +1 -1
  13. package/dist/behaviours/model.d.ts +7 -4
  14. package/dist/behaviours/model.d.ts.map +1 -1
  15. package/dist/behaviours/model.js +16 -9
  16. package/dist/behaviours/model.js.map +1 -1
  17. package/dist/behaviours/schema.d.ts +118 -4
  18. package/dist/behaviours/schema.d.ts.map +1 -1
  19. package/dist/behaviours/schema.js +18 -3
  20. package/dist/behaviours/schema.js.map +1 -1
  21. package/dist/behaviours/spec.d.ts.map +1 -1
  22. package/dist/behaviours/spec.js +3 -2
  23. package/dist/behaviours/spec.js.map +1 -1
  24. package/dist/bindings.js +9 -1
  25. package/dist/bindings.js.map +1 -1
  26. package/dist/checkpoint.d.ts +31 -2
  27. package/dist/checkpoint.d.ts.map +1 -1
  28. package/dist/checkpoint.js +176 -5
  29. package/dist/checkpoint.js.map +1 -1
  30. package/dist/components/index.d.ts +3 -3
  31. package/dist/components/index.js +3 -3
  32. package/dist/components/properties.d.ts +13 -1
  33. package/dist/components/properties.d.ts.map +1 -1
  34. package/dist/components/properties.js +58 -3
  35. package/dist/components/properties.js.map +1 -1
  36. package/dist/components/variants.d.ts +16 -10
  37. package/dist/components/variants.d.ts.map +1 -1
  38. package/dist/components/variants.js +39 -13
  39. package/dist/components/variants.js.map +1 -1
  40. package/dist/connectors/hit.d.ts.map +1 -1
  41. package/dist/connectors/hit.js +1 -7
  42. package/dist/connectors/hit.js.map +1 -1
  43. package/dist/connectors/pieces.d.ts.map +1 -1
  44. package/dist/connectors/pieces.js +2 -5
  45. package/dist/connectors/pieces.js.map +1 -1
  46. package/dist/copy.d.ts.map +1 -1
  47. package/dist/copy.js +9 -15
  48. package/dist/copy.js.map +1 -1
  49. package/dist/css/blend.d.ts +11 -0
  50. package/dist/css/blend.d.ts.map +1 -0
  51. package/dist/css/blend.js +30 -0
  52. package/dist/css/blend.js.map +1 -0
  53. package/dist/css/index.d.ts +2 -1
  54. package/dist/css/index.js +2 -1
  55. package/dist/cubic.d.ts +7 -0
  56. package/dist/cubic.d.ts.map +1 -0
  57. package/dist/cubic.js +17 -0
  58. package/dist/cubic.js.map +1 -0
  59. package/dist/export-format.d.ts +14 -1
  60. package/dist/export-format.d.ts.map +1 -1
  61. package/dist/export-format.js +26 -1
  62. package/dist/export-format.js.map +1 -1
  63. package/dist/fields/text.d.ts +2 -2
  64. package/dist/fields/text.d.ts.map +1 -1
  65. package/dist/fields/text.js +2 -1
  66. package/dist/fields/text.js.map +1 -1
  67. package/dist/figjam/index.d.ts +2 -2
  68. package/dist/figjam/index.js +2 -2
  69. package/dist/figjam/palette.d.ts +13 -2
  70. package/dist/figjam/palette.d.ts.map +1 -1
  71. package/dist/figjam/palette.js +30 -2
  72. package/dist/figjam/palette.js.map +1 -1
  73. package/dist/generated/index.d.ts +2 -2
  74. package/dist/generated/index.js +2 -2
  75. package/dist/generated/shape-with-text.d.ts +7 -2
  76. package/dist/generated/shape-with-text.d.ts.map +1 -1
  77. package/dist/generated/shape-with-text.js +20 -3
  78. package/dist/generated/shape-with-text.js.map +1 -1
  79. package/dist/geometry.d.ts +30 -46
  80. package/dist/geometry.d.ts.map +1 -1
  81. package/dist/geometry.js +63 -131
  82. package/dist/geometry.js.map +1 -1
  83. package/dist/graph.d.ts +1 -0
  84. package/dist/graph.d.ts.map +1 -1
  85. package/dist/graph.js +15 -3
  86. package/dist/graph.js.map +1 -1
  87. package/dist/guides.d.ts +3 -1
  88. package/dist/guides.d.ts.map +1 -1
  89. package/dist/guides.js +5 -1
  90. package/dist/guides.js.map +1 -1
  91. package/dist/hit-test.d.ts.map +1 -1
  92. package/dist/hit-test.js +42 -29
  93. package/dist/hit-test.js.map +1 -1
  94. package/dist/index.d.ts +2 -2
  95. package/dist/instances/fields.d.ts +2 -2
  96. package/dist/instances/fields.d.ts.map +1 -1
  97. package/dist/instances/fields.js +8 -0
  98. package/dist/instances/fields.js.map +1 -1
  99. package/dist/instances/index.d.ts +1 -3
  100. package/dist/instances/index.d.ts.map +1 -1
  101. package/dist/instances/index.js +36 -30
  102. package/dist/instances/index.js.map +1 -1
  103. package/dist/instances/kept-overrides.js +204 -0
  104. package/dist/instances/kept-overrides.js.map +1 -0
  105. package/dist/instances/main-component.d.ts +3 -1
  106. package/dist/instances/main-component.d.ts.map +1 -1
  107. package/dist/instances/main-component.js +10 -2
  108. package/dist/instances/main-component.js.map +1 -1
  109. package/dist/instances/overrides.d.ts +4 -1
  110. package/dist/instances/overrides.d.ts.map +1 -1
  111. package/dist/instances/overrides.js +18 -2
  112. package/dist/instances/overrides.js.map +1 -1
  113. package/dist/instances/swap.js +288 -0
  114. package/dist/instances/swap.js.map +1 -0
  115. package/dist/instances/sync.js +84 -32
  116. package/dist/instances/sync.js.map +1 -1
  117. package/dist/node-defaults.d.ts.map +1 -1
  118. package/dist/node-defaults.js +1 -1
  119. package/dist/node-defaults.js.map +1 -1
  120. package/dist/outline/flatten.d.ts +15 -0
  121. package/dist/outline/flatten.d.ts.map +1 -0
  122. package/dist/outline/flatten.js +189 -0
  123. package/dist/outline/flatten.js.map +1 -0
  124. package/dist/outline/heads.js +34 -0
  125. package/dist/outline/heads.js.map +1 -0
  126. package/dist/outline/hit.d.ts +21 -0
  127. package/dist/outline/hit.d.ts.map +1 -0
  128. package/dist/outline/hit.js +276 -0
  129. package/dist/outline/hit.js.map +1 -0
  130. package/dist/outline/index.d.ts +5 -0
  131. package/dist/outline/index.js +5 -0
  132. package/dist/outline/point.d.ts +16 -0
  133. package/dist/outline/point.d.ts.map +1 -0
  134. package/dist/outline/point.js +42 -0
  135. package/dist/outline/point.js.map +1 -0
  136. package/dist/outline/shapes.d.ts +35 -0
  137. package/dist/outline/shapes.d.ts.map +1 -0
  138. package/dist/outline/shapes.js +181 -0
  139. package/dist/outline/shapes.js.map +1 -0
  140. package/dist/plugin-data/fields.d.ts +2 -1
  141. package/dist/plugin-data/fields.d.ts.map +1 -1
  142. package/dist/plugin-data/fields.js +19 -4
  143. package/dist/plugin-data/fields.js.map +1 -1
  144. package/dist/scaling/tree.js +1 -1
  145. package/dist/shared-styles.d.ts +14 -1
  146. package/dist/shared-styles.d.ts.map +1 -1
  147. package/dist/shared-styles.js +63 -2
  148. package/dist/shared-styles.js.map +1 -1
  149. package/dist/slots/content.d.ts.map +1 -1
  150. package/dist/slots/content.js +2 -0
  151. package/dist/slots/content.js.map +1 -1
  152. package/dist/slots/frames.d.ts +2 -0
  153. package/dist/slots/frames.d.ts.map +1 -1
  154. package/dist/slots/frames.js +7 -2
  155. package/dist/slots/frames.js.map +1 -1
  156. package/dist/text/index.d.ts +2 -2
  157. package/dist/text/index.js +3 -3
  158. package/dist/text/lengths.d.ts +6 -1
  159. package/dist/text/lengths.d.ts.map +1 -1
  160. package/dist/text/lengths.js +10 -1
  161. package/dist/text/lengths.js.map +1 -1
  162. package/dist/text/overflow.d.ts +2 -2
  163. package/dist/text/overflow.js.map +1 -1
  164. package/dist/text/picture.d.ts +1 -2
  165. package/dist/text/picture.d.ts.map +1 -1
  166. package/dist/text/picture.js +1 -4
  167. package/dist/text/picture.js.map +1 -1
  168. package/dist/transfer/index.js +1 -1
  169. package/dist/transfer/nodes.js +9 -5
  170. package/dist/transfer/nodes.js.map +1 -1
  171. package/dist/types.d.ts +27 -1
  172. package/dist/types.d.ts.map +1 -1
  173. package/dist/types.js.map +1 -1
  174. package/dist/variables/bindings.d.ts +28 -5
  175. package/dist/variables/bindings.d.ts.map +1 -1
  176. package/dist/variables/bindings.js +104 -14
  177. package/dist/variables/bindings.js.map +1 -1
  178. package/dist/variables/fields.d.ts +19 -1
  179. package/dist/variables/fields.d.ts.map +1 -1
  180. package/dist/variables/fields.js +36 -1
  181. package/dist/variables/fields.js.map +1 -1
  182. package/dist/variables/index.d.ts +3 -3
  183. package/dist/variables/index.d.ts.map +1 -1
  184. package/dist/variables/index.js +23 -8
  185. package/dist/variables/index.js.map +1 -1
  186. package/package.json +7 -1
  187. package/src/arrow-caps.ts +2 -5
  188. package/src/behaviours/kinds.ts +51 -34
  189. package/src/behaviours/layers.ts +4 -2
  190. package/src/behaviours/model.ts +22 -11
  191. package/src/behaviours/schema.ts +20 -4
  192. package/src/behaviours/spec.ts +8 -2
  193. package/src/bindings.ts +11 -2
  194. package/src/checkpoint.ts +251 -4
  195. package/src/components/properties.ts +92 -2
  196. package/src/components/variants.ts +51 -30
  197. package/src/connectors/hit.ts +1 -12
  198. package/src/connectors/pieces.ts +2 -5
  199. package/src/copy.ts +9 -15
  200. package/src/css/blend.ts +27 -0
  201. package/src/css/index.ts +1 -0
  202. package/src/cubic.ts +14 -0
  203. package/src/export-format.ts +29 -0
  204. package/src/fields/text.ts +3 -1
  205. package/src/figjam/palette.ts +29 -1
  206. package/src/generated/shape-with-text.ts +28 -2
  207. package/src/geometry.ts +78 -198
  208. package/src/graph.ts +27 -3
  209. package/src/guides.ts +5 -0
  210. package/src/hit-test.ts +67 -54
  211. package/src/instances/fields.ts +8 -0
  212. package/src/instances/index.ts +58 -31
  213. package/src/instances/kept-overrides.ts +280 -0
  214. package/src/instances/main-component.ts +12 -0
  215. package/src/instances/overrides.ts +27 -1
  216. package/src/instances/swap.ts +451 -0
  217. package/src/instances/sync.ts +141 -42
  218. package/src/node-defaults.ts +2 -1
  219. package/src/outline/flatten.ts +190 -0
  220. package/src/outline/heads.ts +52 -0
  221. package/src/outline/hit.ts +369 -0
  222. package/src/outline/index.ts +4 -0
  223. package/src/outline/point.ts +59 -0
  224. package/src/outline/shapes.ts +207 -0
  225. package/src/plugin-data/fields.ts +15 -2
  226. package/src/shared-styles.ts +82 -1
  227. package/src/slots/content.ts +2 -0
  228. package/src/slots/frames.ts +9 -7
  229. package/src/text/lengths.ts +10 -0
  230. package/src/text/overflow.ts +2 -2
  231. package/src/text/picture.ts +0 -4
  232. package/src/transfer/nodes.ts +7 -5
  233. package/src/types.ts +28 -0
  234. package/src/variables/bindings.ts +125 -14
  235. package/src/variables/fields.ts +46 -1
  236. package/src/variables/index.ts +35 -2
package/src/checkpoint.ts CHANGED
@@ -1,6 +1,13 @@
1
1
  import { isEqual } from 'es-toolkit'
2
2
 
3
3
  import type { SceneGraph } from './graph'
4
+ import { createSceneMutationImpact, recordSceneMutations } from './mutation-impact'
5
+ import type { SceneNode, Variable, VariableCollection } from './types'
6
+
7
+ const NODE_COUNT_ERROR = 'Atomic tools must not create or remove nodes or variables'
8
+ const NODE_IDENTITY_ERROR = 'Atomic tools must not change node hierarchy or identity'
9
+ const VARIABLE_IDENTITY_ERROR = 'Atomic tools must not change variable identity'
10
+ const DOCUMENT_ERROR = 'Atomic tools must not change collections, assets or document metadata'
4
11
 
5
12
  /** Capture rollback state without changing graph or surviving object identities. */
6
13
  export function captureGraphCheckpoint(graph: SceneGraph) {
@@ -27,7 +34,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {
27
34
  snapshot.nodes.size !== graph.nodes.size ||
28
35
  snapshot.variables.size !== graph.variables.size
29
36
  )
30
- throw new Error('Atomic tools must not create or remove nodes or variables')
37
+ throw new Error(NODE_COUNT_ERROR)
31
38
  for (const [id, before] of snapshot.nodes) {
32
39
  const after = graph.nodes.get(id)
33
40
  if (
@@ -39,7 +46,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {
39
46
  before.componentId !== after.componentId ||
40
47
  !isEqual(before.childIds, after.childIds)
41
48
  ) {
42
- throw new Error('Atomic tools must not change node hierarchy or identity')
49
+ throw new Error(NODE_IDENTITY_ERROR)
43
50
  }
44
51
  }
45
52
  for (const [id, before] of snapshot.variables) {
@@ -51,7 +58,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {
51
58
  before.collectionId !== after.collectionId ||
52
59
  before.type !== after.type
53
60
  )
54
- throw new Error('Atomic tools must not change variable identity')
61
+ throw new Error(VARIABLE_IDENTITY_ERROR)
55
62
  }
56
63
  assertDocumentUnchanged()
57
64
  }
@@ -69,7 +76,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {
69
76
  graph.figKiwiVersion !== snapshot.figKiwiVersion ||
70
77
  !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)
71
78
  ) {
72
- throw new Error('Atomic tools must not change collections, assets or document metadata')
79
+ throw new Error(DOCUMENT_ERROR)
73
80
  }
74
81
  }
75
82
 
@@ -121,3 +128,243 @@ function restoreMap<K, V>(target: Map<K, V>, saved: Map<K, V>) {
121
128
  target.clear()
122
129
  for (const [key, value] of saved) target.set(key, value)
123
130
  }
131
+
132
+ /**
133
+ * Rollback state for an edit that may only change properties, which costs what the edit touches
134
+ * rather than a copy of the document: a node is copied the first time the graph reports it about
135
+ * to change (`SceneGraph.observeNodeChanges`), together with its ancestors below the page, which
136
+ * keep instance override maps the graph writes into in place.
137
+ */
138
+ export interface TouchedCheckpoint {
139
+ /** Copies of the reported nodes and their ancestors below the page, as they were before. */
140
+ readonly nodes: ReadonlyMap<string, SceneNode>
141
+ /** Nodes the graph reported changing or creating. */
142
+ readonly reported: ReadonlySet<string>
143
+ /** Copies of every variable, as variables have no change report. */
144
+ readonly variables: ReadonlyMap<string, Variable>
145
+ readonly variableCollections: ReadonlyMap<string, VariableCollection>
146
+ /** Throws unless the edit only changed properties of existing nodes and variables. */
147
+ assertPropertiesOnly(): void
148
+ /** Stops observing and puts back everything the edit changed, keeping object identities. */
149
+ restore(): void
150
+ /** Stops observing the graph. */
151
+ stop(): void
152
+ }
153
+
154
+ /**
155
+ * Starts observing `graph` for an edit that may only change properties. Node identities are
156
+ * kept as pointers, so replacing, adding, or removing a node anywhere is found; a node's fields
157
+ * are compared and restored only where the graph reported it, so code that writes into a node
158
+ * directly calls `SceneGraph.willChangeNode` first, and a node event without such a report fails
159
+ * the edit.
160
+ */
161
+ export function captureTouchedCheckpoint(graph: SceneGraph): TouchedCheckpoint {
162
+ const nodeRefs = new Map(graph.nodes)
163
+ const variableRefs = new Map(graph.variables)
164
+ const collectionRefs = new Map(graph.variableCollections)
165
+ const saved = structuredClone({
166
+ variables: graph.variables,
167
+ variableCollections: graph.variableCollections,
168
+ activeMode: graph.activeMode,
169
+ instanceIndex: graph.instanceIndex,
170
+ enabledLibraries: graph.enabledLibraries
171
+ })
172
+ // Property edits cannot edit assets. Retain existing buffers, not copies of every bitmap.
173
+ const images = new Map(graph.images)
174
+ const { rootId, figKiwiVersion, figSchemaDeflated, documentColorSpace } = graph
175
+ const nodes = new Map<string, SceneNode>()
176
+ const reported = new Set<string>()
177
+ const created = new Set<string>()
178
+ const impact = createSceneMutationImpact()
179
+
180
+ /** Copies a node as the edit found it: the original object, should the edit have replaced it. */
181
+ function copy(node: SceneNode) {
182
+ nodes.set(node.id, structuredClone(nodeRefs.get(node.id) ?? node))
183
+ }
184
+
185
+ const skipped = (node: SceneNode) => nodes.has(node.id) || created.has(node.id)
186
+
187
+ /**
188
+ * Copies `node` and each ancestor not copied yet, up to but excluding its page. An ancestor
189
+ * copied already had its own ancestors copied with it, so the walk stops there.
190
+ */
191
+ function copyLineage(node: SceneNode) {
192
+ if (skipped(node)) return
193
+ copy(node)
194
+ if (!node.parentId) return
195
+ graph.closest(node.parentId, (ancestor) => {
196
+ if (ancestor.type === 'CANVAS' || ancestor.id === rootId || skipped(ancestor)) return true
197
+ copy(ancestor)
198
+ return false
199
+ })
200
+ }
201
+
202
+ const unobserve = graph.observeNodeChanges({
203
+ created: (node) => {
204
+ created.add(node.id)
205
+ reported.add(node.id)
206
+ },
207
+ before: (node) => {
208
+ reported.add(node.id)
209
+ copyLineage(node)
210
+ }
211
+ })
212
+ const unbindEvents = recordSceneMutations(graph, impact)
213
+ let observing = true
214
+
215
+ function stop() {
216
+ if (!observing) return
217
+ observing = false
218
+ unobserve()
219
+ unbindEvents()
220
+ }
221
+
222
+ function assertNodes() {
223
+ if (
224
+ created.size > 0 ||
225
+ impact.deletedNodeIds.size > 0 ||
226
+ graph.nodes.size !== nodeRefs.size ||
227
+ graph.variables.size !== variableRefs.size
228
+ )
229
+ throw new Error(NODE_COUNT_ERROR)
230
+ for (const [id, node] of graph.nodes) {
231
+ const original = nodeRefs.get(id)
232
+ if (!original) throw new Error(NODE_COUNT_ERROR)
233
+ if (original !== node) throw new Error(NODE_IDENTITY_ERROR)
234
+ }
235
+ for (const [id, before] of nodes) {
236
+ const after = graph.nodes.get(id)
237
+ if (
238
+ !after ||
239
+ before.id !== after.id ||
240
+ before.type !== after.type ||
241
+ before.parentId !== after.parentId ||
242
+ before.componentId !== after.componentId ||
243
+ !isEqual(before.childIds, after.childIds)
244
+ )
245
+ throw new Error(NODE_IDENTITY_ERROR)
246
+ }
247
+ for (const id of [
248
+ ...impact.changedNodeIds,
249
+ ...impact.previousParentIds,
250
+ ...impact.currentParentIds
251
+ ]) {
252
+ if (!nodes.has(id) && !created.has(id)) {
253
+ throw new Error(
254
+ `Atomic tools must report layer changes to the scene graph (SceneGraph.willChangeNode): ${id}`
255
+ )
256
+ }
257
+ }
258
+ }
259
+
260
+ function assertPropertiesOnly() {
261
+ assertNodes()
262
+ for (const [id, before] of saved.variables) {
263
+ const after = graph.variables.get(id)
264
+ if (
265
+ !after ||
266
+ after !== variableRefs.get(id) ||
267
+ before.id !== after.id ||
268
+ before.collectionId !== after.collectionId ||
269
+ before.type !== after.type
270
+ )
271
+ throw new Error(VARIABLE_IDENTITY_ERROR)
272
+ }
273
+ if (
274
+ !isEqual(saved.variableCollections, graph.variableCollections) ||
275
+ !isEqual(saved.activeMode, graph.activeMode) ||
276
+ !isEqual(saved.instanceIndex, graph.instanceIndex) ||
277
+ !isEqual(saved.enabledLibraries, graph.enabledLibraries) ||
278
+ images.size !== graph.images.size ||
279
+ [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||
280
+ graph.rootId !== rootId ||
281
+ graph.documentColorSpace !== documentColorSpace ||
282
+ graph.figKiwiVersion !== figKiwiVersion ||
283
+ // Every writer assigns a new schema rather than writing into it.
284
+ graph.figSchemaDeflated !== figSchemaDeflated
285
+ )
286
+ throw new Error(DOCUMENT_ERROR)
287
+ }
288
+
289
+ /** Puts the node map back as it was, in its order, if the edit changed its entries. */
290
+ function restoreNodeMap(): { removed: Map<string, SceneNode>; readded: Set<string> } {
291
+ const removed = new Map<string, SceneNode>()
292
+ const readded = new Set<string>()
293
+ let changed = graph.nodes.size !== nodeRefs.size
294
+ if (!changed) {
295
+ // In lockstep, so a node removed and set again, which moves to the end, is put back too.
296
+ const live = graph.nodes.entries()
297
+ for (const [id, node] of nodeRefs) {
298
+ const next = live.next()
299
+ if (next.done || next.value[0] !== id || next.value[1] !== node) {
300
+ changed = true
301
+ break
302
+ }
303
+ }
304
+ }
305
+ if (!changed) return { removed, readded }
306
+ const failed = new Map(graph.nodes)
307
+ graph.nodes.clear()
308
+ for (const [id, node] of nodeRefs) {
309
+ graph.nodes.set(id, node)
310
+ if (!failed.has(id)) readded.add(id)
311
+ }
312
+ for (const [id, node] of failed) if (!nodeRefs.has(id)) removed.set(id, node)
313
+ return { removed, readded }
314
+ }
315
+
316
+ function restore() {
317
+ stop()
318
+ const { removed, readded } = restoreNodeMap()
319
+ for (const [id, copy] of nodes) {
320
+ const original = nodeRefs.get(id)
321
+ if (!original) continue
322
+ for (const key of Object.keys(original)) {
323
+ if (!Object.hasOwn(copy, key)) Reflect.deleteProperty(original, key)
324
+ }
325
+ Object.assign(original, structuredClone(copy))
326
+ }
327
+ restoreObjects(graph.variables, saved.variables, variableRefs)
328
+ restoreObjects(graph.variableCollections, saved.variableCollections, collectionRefs)
329
+ restoreMap(graph.activeMode, structuredClone(saved.activeMode))
330
+ restoreMap(graph.instanceIndex, structuredClone(saved.instanceIndex))
331
+ restoreMap(graph.enabledLibraries, structuredClone(saved.enabledLibraries))
332
+ restoreMap(graph.images, images)
333
+ graph.rootId = rootId
334
+ graph.figKiwiVersion = figKiwiVersion
335
+ graph.figSchemaDeflated = figSchemaDeflated
336
+ graph.documentColorSpace = documentColorSpace
337
+ graph.clearAbsPosCache()
338
+ const touched = new Set([
339
+ ...nodes.keys(),
340
+ ...created,
341
+ ...readded,
342
+ ...removed.keys(),
343
+ ...impact.changedNodeIds,
344
+ ...impact.previousParentIds,
345
+ ...impact.currentParentIds
346
+ ])
347
+ for (const id of touched) {
348
+ if (graph.nodes.get(id)?.type === 'CONNECTOR') graph.connectorIds.add(id)
349
+ else graph.connectorIds.delete(id)
350
+ }
351
+ // Notify consumers only after the complete hierarchy and indexes have been restored.
352
+ for (const [id, node] of removed) graph.emitter.emit('node:deleted', id, node.parentId)
353
+ for (const id of touched) {
354
+ const node = graph.nodes.get(id)
355
+ if (!node) continue
356
+ if (readded.has(id)) graph.emitter.emit('node:created', node)
357
+ else graph.emitter.emit('node:updated', id, node)
358
+ }
359
+ }
360
+
361
+ return {
362
+ nodes,
363
+ reported,
364
+ variables: saved.variables,
365
+ variableCollections: saved.variableCollections,
366
+ assertPropertiesOnly,
367
+ restore,
368
+ stop
369
+ }
370
+ }
@@ -1,6 +1,5 @@
1
1
  import type { SceneGraph } from '../graph'
2
- import { findInstanceAncestor } from '../instances'
3
- import { instanceMainComponent } from '../instances/main-component'
2
+ import { findInstanceAncestor, instanceMainComponent } from '../instances/main-component'
4
3
  import { setInstanceOverride } from '../instances/overrides'
5
4
  import { walkInstanceSources } from '../instances/source-walk'
6
5
  import { randomHex } from '../random'
@@ -172,6 +171,60 @@ export function applyComponentPropertyValue(
172
171
  return definition.type === 'INSTANCE_SWAP' ? target : instance
173
172
  }
174
173
 
174
+ export function reapplyComponentPropertyAssignments(
175
+ graph: SceneGraph,
176
+ instanceId: string
177
+ ): ComponentPropertyDefinition[] {
178
+ const instance = graph.getNode(instanceId)
179
+ if (instance?.type !== 'INSTANCE') {
180
+ return []
181
+ }
182
+ const definitions = new Map(
183
+ componentPropertyDefinitions(graph, instance).map((definition) => [definition.id, definition])
184
+ )
185
+ const applied: ComponentPropertyDefinition[] = []
186
+ for (const [propertyId, value] of Object.entries(instance.componentPropertyAssignments)) {
187
+ const definition = definitions.get(propertyId)
188
+ if (definition && definition.type !== 'VARIANT') {
189
+ applyComponentPropertyValue(graph, instanceId, definition, value)
190
+ applied.push(definition)
191
+ }
192
+ }
193
+ return applied
194
+ }
195
+
196
+ const ASSIGNMENT_OVERRIDE_PREFIX = 'componentPropertyAssignments/'
197
+
198
+ export function assignmentOverrideField(propertyId: string): string {
199
+ return `${ASSIGNMENT_OVERRIDE_PREFIX}${propertyId}`
200
+ }
201
+
202
+ export function overriddenAssignmentId(field: string): string | undefined {
203
+ return field.startsWith(ASSIGNMENT_OVERRIDE_PREFIX)
204
+ ? field.slice(ASSIGNMENT_OVERRIDE_PREFIX.length)
205
+ : undefined
206
+ }
207
+
208
+ export function recordAssignmentOverride(
209
+ graph: SceneGraph,
210
+ instanceId: string,
211
+ propertyId: string
212
+ ): void {
213
+ const instance = graph.getNode(instanceId)
214
+ const owner = instance?.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined
215
+ if (!instance || !owner) {
216
+ return
217
+ }
218
+ setInstanceOverride(
219
+ owner.instanceOverrides,
220
+ owner.id,
221
+ instance.id,
222
+ assignmentOverrideField(propertyId),
223
+ instance.componentPropertyAssignments[propertyId]
224
+ )
225
+ graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })
226
+ }
227
+
175
228
  function componentSubtree(graph: SceneGraph, componentId: string): SceneNode[] {
176
229
  const component = graph.getNode(componentId)
177
230
  if (!component) return []
@@ -235,6 +288,43 @@ export function removeComponentProperty(
235
288
  return true
236
289
  }
237
290
 
291
+ /**
292
+ * Moves the boolean, text, instance swap, and slot properties a set's variants define themselves
293
+ * onto the set, under their IDs, so the layers and instances naming them still do: a variant's
294
+ * properties are its set's, as Figma keeps them, and combining components moves theirs to the
295
+ * set (desktop 126). A property the set already has under that ID is not added again. Returns
296
+ * the IDs of the set and the variants it changed.
297
+ */
298
+ export function moveVariantPropertiesToSet(graph: SceneGraph, setId: string): string[] {
299
+ const set = graph.getNode(setId)
300
+ if (set?.type !== 'COMPONENT_SET') return []
301
+ const changed: string[] = []
302
+ const known = new Set(set.componentPropertyDefinitions.map((definition) => definition.id))
303
+ const moved: ComponentPropertyDefinition[] = []
304
+ for (const variant of graph.getChildren(setId)) {
305
+ const own = variant.componentPropertyDefinitions.filter(
306
+ (definition) => definition.type !== 'VARIANT'
307
+ )
308
+ if (variant.type !== 'COMPONENT' || own.length === 0) continue
309
+ for (const definition of own) {
310
+ if (known.has(definition.id)) continue
311
+ known.add(definition.id)
312
+ moved.push(definition)
313
+ }
314
+ graph.updateNode(variant.id, {
315
+ componentPropertyDefinitions: variant.componentPropertyDefinitions.filter(
316
+ (definition) => definition.type === 'VARIANT'
317
+ )
318
+ })
319
+ changed.push(variant.id)
320
+ }
321
+ if (moved.length === 0) return changed
322
+ graph.updateNode(setId, {
323
+ componentPropertyDefinitions: [...moved, ...set.componentPropertyDefinitions]
324
+ })
325
+ return [setId, ...changed]
326
+ }
327
+
238
328
  /** A new component property ID, in the `prop:` form the editor, plugin API, and design JSX share. */
239
329
  export function createComponentPropertyId(): string {
240
330
  return `prop:${randomHex(8)}`
@@ -1,5 +1,7 @@
1
+ import { compact, uniq } from 'es-toolkit/array'
2
+
1
3
  import type { SceneGraph } from '../graph'
2
- import type { SceneNode } from '../types'
4
+ import type { ComponentPropertyDefinition, SceneNode } from '../types'
3
5
 
4
6
  /** Variants in reading order on the canvas: top to bottom, then left to right, then by name. */
5
7
  export function compareCanvasPosition(a: SceneNode, b: SceneNode): number {
@@ -7,47 +9,66 @@ export function compareCanvasPosition(a: SceneNode, b: SceneNode): number {
7
9
  }
8
10
 
9
11
  /**
10
- * A component set's default variant, the one an instance starts as: the variant in its
11
- * top-left corner, as Figma defines it.
12
+ * Whether `a` comes before `b` reading the set as Figma does: variants whose rows overlap, edges
13
+ * touching included, read left to right, and others top to bottom.
14
+ */
15
+ function readsBefore(a: SceneNode, b: SceneNode): boolean {
16
+ const sameRow = a.y <= b.y + b.height && b.y <= a.y + a.height
17
+ return sameRow ? a.x < b.x || (a.x === b.x && a.y < b.y) : a.y < b.y
18
+ }
19
+
20
+ /**
21
+ * A component set's default variant, the one an instance starts as: the first in reading order,
22
+ * and the first in layer order of those at the same place (measured in Figma desktop 126).
12
23
  */
13
24
  export function defaultVariant(graph: SceneGraph, set: SceneNode): SceneNode | undefined {
14
- return graph
15
- .getChildren(set.id)
16
- .filter((child) => child.type === 'COMPONENT')
17
- .sort(compareCanvasPosition)[0]
25
+ let first: SceneNode | undefined
26
+ for (const child of graph.getChildren(set.id)) {
27
+ if (child.type !== 'COMPONENT') continue
28
+ if (!first || readsBefore(child, first)) first = child
29
+ }
30
+ return first
18
31
  }
19
32
 
20
33
  /**
21
- * The value a variant property starts at: its recorded default when that is one of its options,
22
- * or else the default variant's, since a document may leave the recorded default empty.
34
+ * The value a variant property starts at: the default variant's, as Figma reads it whatever
35
+ * default the document records, and follows when another variant moves to the top left. The
36
+ * recorded default stands only while the default variant has no value for the property.
23
37
  */
24
38
  export function variantDefaultValue(
25
39
  graph: SceneGraph,
26
40
  set: SceneNode,
27
- property: { name: string; defaultValue: string; variantOptions?: string[] }
41
+ property: { name: string; defaultValue: string }
28
42
  ): string {
29
- if (property.variantOptions?.includes(property.defaultValue)) return property.defaultValue
30
- return defaultVariant(graph, set)?.componentPropertyValues[property.name] ?? property.defaultValue
43
+ const value = defaultVariant(graph, set)?.componentPropertyValues[property.name]
44
+ return value || property.defaultValue
31
45
  }
32
46
 
33
47
  /**
34
- * The variant with every property at its default value: the recorded defaults when they name a
35
- * variant, else the default variant, as a document that leaves them out draws it.
48
+ * A variant property's values: the ones the document records, then any its variants use that it
49
+ * does not, since older documents record none and a set's page may have loaded only some
50
+ * variants.
36
51
  */
37
- export function restingVariant(graph: SceneGraph, set: SceneNode): SceneNode | undefined {
38
- const properties = set.componentPropertyDefinitions.filter(
39
- (definition) => definition.type === 'VARIANT'
40
- )
41
- const values = properties.map(
42
- (property) => [property.name, variantDefaultValue(graph, set, property)] as const
43
- )
44
- return (
45
- graph
46
- .getChildren(set.id)
47
- .find(
48
- (child) =>
49
- child.type === 'COMPONENT' &&
50
- values.every(([name, value]) => child.componentPropertyValues[name] === value)
51
- ) ?? defaultVariant(graph, set)
52
- )
52
+ export function variantOptions(
53
+ graph: SceneGraph,
54
+ set: SceneNode,
55
+ property: { name: string; variantOptions?: string[] }
56
+ ): string[] {
57
+ const used = graph
58
+ .getChildren(set.id)
59
+ .map((child) =>
60
+ child.type === 'COMPONENT' ? child.componentPropertyValues[property.name] : ''
61
+ )
62
+ return compact(uniq([...(property.variantOptions ?? []), ...used]))
63
+ }
64
+
65
+ /** A set's definition with a variant property's values and default filled in from its variants. */
66
+ export function resolvedVariantDefinition(
67
+ graph: SceneGraph,
68
+ set: SceneNode,
69
+ definition: ComponentPropertyDefinition
70
+ ): ComponentPropertyDefinition {
71
+ if (definition.type !== 'VARIANT') return definition
72
+ const options = { ...definition, variantOptions: variantOptions(graph, set, definition) }
73
+ return { ...options, defaultValue: variantDefaultValue(graph, set, options) }
53
74
  }
@@ -1,7 +1,7 @@
1
1
  import { getWorldMatrix } from '../coordinate'
2
2
  import type { SceneGraph } from '../graph'
3
3
  import Matrix from '../matrix'
4
- import type { Vector } from '../primitives'
4
+ import { distanceToSegment } from '../outline/point'
5
5
  import type { SceneNode } from '../types'
6
6
  import { isStraight, pointAt, type ConnectorPiece } from './pieces'
7
7
  import { connectorSublayers } from './sublayers'
@@ -11,17 +11,6 @@ const CONNECTOR_HIT_SLOP = 4
11
11
  /** Points sampled along a curved segment to measure distance to it. */
12
12
  const CURVE_SAMPLES = 24
13
13
 
14
- function distanceToSegment(p: Vector, a: Vector, b: Vector): number {
15
- const dx = b.x - a.x
16
- const dy = b.y - a.y
17
- const lengthSquared = dx * dx + dy * dy
18
- const t =
19
- lengthSquared === 0
20
- ? 0
21
- : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSquared))
22
- return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))
23
- }
24
-
25
14
  /**
26
15
  * Whether a canvas point lands on a connector's line: within half its stroke and a few units of
27
16
  * slop, plus `pad`. A connector is picked by its line, not by the box around its route.
@@ -1,3 +1,4 @@
1
+ import { cubicPoint } from '../cubic'
1
2
  import { computeBounds } from '../geometry'
2
3
  import type { Rect, Vector } from '../primitives'
3
4
  import type { StrokeCap, VectorNetwork } from '../types'
@@ -47,11 +48,7 @@ export function pointAt(piece: ConnectorPiece, t: number): Vector {
47
48
  const { from: a, to: b } = piece
48
49
  if (isStraight(piece)) return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }
49
50
  const [c1, c2] = controls(piece)
50
- const u = 1 - t
51
- return {
52
- x: u * u * u * a.x + 3 * u * u * t * c1.x + 3 * u * t * t * c2.x + t * t * t * b.x,
53
- y: u * u * u * a.y + 3 * u * u * t * c1.y + 3 * u * t * t * c2.y + t * t * t * b.y
54
- }
51
+ return cubicPoint(a, c1, c2, b, t)
55
52
  }
56
53
 
57
54
  function derivativeAt(piece: ConnectorPiece, t: number): Vector {
package/src/copy.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * no shared references between source and copy.
9
9
  */
10
10
 
11
- import { geometryCommandCoordCount } from './geometry'
11
+ import { readGeometryBlob } from './geometry'
12
12
  import { cloneInstanceOverrideState } from './instances/overrides'
13
13
  import { createDefaultSourceMetadata } from './node-defaults'
14
14
  import type {
@@ -159,21 +159,15 @@ export function transformGeometryBlob(
159
159
  ty = 0
160
160
  ): Uint8Array {
161
161
  const out = blob.slice()
162
- const dv = new DataView(out.buffer, out.byteOffset, out.byteLength)
163
- let offset = 0
164
- while (offset < out.length) {
165
- const command = out[offset++]
166
- const coords = geometryCommandCoordCount(command)
167
- if (coords == null) break
168
- for (let i = 0; i < coords; i++) {
169
- if (offset + 8 > out.length) break
170
- const x = dv.getFloat32(offset, true)
171
- const y = dv.getFloat32(offset + 4, true)
172
- dv.setFloat32(offset, m00 * x + m01 * y + tx, true)
173
- dv.setFloat32(offset + 4, m10 * x + m11 * y + ty, true)
174
- offset += 8
162
+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength)
163
+ readGeometryBlob(out, (_, coords, offset) => {
164
+ for (let i = 0; i < coords.length; i += 2) {
165
+ const x = coords[i]
166
+ const y = coords[i + 1]
167
+ view.setFloat32(offset + i * 4, m00 * x + m01 * y + tx, true)
168
+ view.setFloat32(offset + i * 4 + 4, m10 * x + m11 * y + ty, true)
175
169
  }
176
- }
170
+ })
177
171
  return out
178
172
  }
179
173
 
@@ -0,0 +1,27 @@
1
+ import type { BlendMode } from '../types'
2
+
3
+ /**
4
+ * Each blend mode as CSS names it, for `mix-blend-mode` and `background-blend-mode`. Linear
5
+ * burn and linear dodge are the `plus-` modes, which `mix-blend-mode` takes and
6
+ * `background-blend-mode` does not.
7
+ */
8
+ export const CSS_BLEND_MODE: Partial<Record<BlendMode, string>> = {
9
+ NORMAL: 'normal',
10
+ DARKEN: 'darken',
11
+ MULTIPLY: 'multiply',
12
+ COLOR_BURN: 'color-burn',
13
+ LIGHTEN: 'lighten',
14
+ LINEAR_BURN: 'plus-darker',
15
+ SCREEN: 'screen',
16
+ LINEAR_DODGE: 'plus-lighter',
17
+ COLOR_DODGE: 'color-dodge',
18
+ OVERLAY: 'overlay',
19
+ SOFT_LIGHT: 'soft-light',
20
+ HARD_LIGHT: 'hard-light',
21
+ DIFFERENCE: 'difference',
22
+ EXCLUSION: 'exclusion',
23
+ HUE: 'hue',
24
+ SATURATION: 'saturation',
25
+ COLOR: 'color',
26
+ LUMINOSITY: 'luminosity'
27
+ }
package/src/css/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { CSS_BLEND_MODE } from './blend'
1
2
  export { parseCSSGridTracks } from './grid'
2
3
  export {
3
4
  parseCSSAlignItems,
package/src/cubic.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { Vector } from './primitives'
2
+
3
+ /** The point at `t` along the cubic from `p0` to `p3` with control points `p1` and `p2`. */
4
+ export function cubicPoint(p0: Vector, p1: Vector, p2: Vector, p3: Vector, t: number): Vector {
5
+ const u = 1 - t
6
+ const a = u * u * u
7
+ const b = 3 * u * u * t
8
+ const c = 3 * u * t * t
9
+ const d = t * t * t
10
+ return {
11
+ x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
12
+ y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
13
+ }
14
+ }