@open-pencil/scene-graph 0.15.1 → 0.16.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 (234) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +607 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +577 -522
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2291 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/group-bounds.js +104 -0
  34. package/dist/chunks/group-bounds.js.map +1 -0
  35. package/dist/chunks/icons/glyph.js +147 -0
  36. package/dist/chunks/icons/glyph.js.map +1 -0
  37. package/dist/chunks/index.js +1724 -663
  38. package/dist/chunks/index.js.map +1 -1
  39. package/dist/color.d.ts +72 -0
  40. package/dist/color.d.ts.map +1 -0
  41. package/dist/color.js +3 -0
  42. package/dist/constants.d.ts +2 -2
  43. package/dist/constants.js +2 -2
  44. package/dist/constants2.d.ts +3 -1
  45. package/dist/constants2.d.ts.map +1 -1
  46. package/dist/coordinate.d.ts +2 -448
  47. package/dist/coordinate.js +2 -2
  48. package/dist/copy.d.ts +1 -1
  49. package/dist/copy.js +1 -1
  50. package/dist/css.d.ts +39 -0
  51. package/dist/css.d.ts.map +1 -0
  52. package/dist/css.js +3 -0
  53. package/dist/geometry.d.ts +1 -1
  54. package/dist/geometry.js +1 -1
  55. package/dist/gradient.d.ts +51 -0
  56. package/dist/gradient.d.ts.map +1 -0
  57. package/dist/gradient.js +132 -0
  58. package/dist/gradient.js.map +1 -0
  59. package/dist/guides.d.ts +2 -2
  60. package/dist/guides.js +39 -0
  61. package/dist/guides.js.map +1 -0
  62. package/dist/hit-test.d.ts +2 -9
  63. package/dist/hit-test.js +176 -34
  64. package/dist/hit-test.js.map +1 -1
  65. package/dist/index.d.ts +4 -8
  66. package/dist/index.js +19 -5
  67. package/dist/instances.d.ts +2 -2
  68. package/dist/instances.js +2 -2
  69. package/dist/layout.d.ts +2 -0
  70. package/dist/layout.js +4 -0
  71. package/dist/node-defaults.d.ts +2 -8
  72. package/dist/node-defaults.js +2 -2
  73. package/dist/order-keys.d.ts +39 -0
  74. package/dist/order-keys.d.ts.map +1 -0
  75. package/dist/order-keys.js +136 -0
  76. package/dist/order-keys.js.map +1 -0
  77. package/dist/parse-path.d.ts +7 -1
  78. package/dist/parse-path.d.ts.map +1 -1
  79. package/dist/parse-path.js +6 -2
  80. package/dist/parse-path.js.map +1 -1
  81. package/dist/polygon.d.ts +53 -0
  82. package/dist/polygon.d.ts.map +1 -0
  83. package/dist/polygon.js +205 -0
  84. package/dist/polygon.js.map +1 -0
  85. package/dist/preview.d.ts +1 -1
  86. package/dist/random.d.ts +7 -0
  87. package/dist/random.d.ts.map +1 -0
  88. package/dist/random.js +2 -0
  89. package/dist/resize.d.ts +11 -2
  90. package/dist/resize.d.ts.map +1 -1
  91. package/dist/resize.js +2 -184
  92. package/dist/snap.d.ts +1 -1
  93. package/dist/text-direction.d.ts +13 -0
  94. package/dist/text-direction.d.ts.map +1 -0
  95. package/dist/text-direction.js +31 -0
  96. package/dist/text-direction.js.map +1 -0
  97. package/dist/text-picture.d.ts +1 -1
  98. package/dist/text-picture.d.ts.map +1 -1
  99. package/dist/text.d.ts +2 -0
  100. package/dist/text.js +3 -0
  101. package/dist/types.d.ts +2121 -15
  102. package/dist/types.d.ts.map +1 -1
  103. package/dist/types.js +2 -1
  104. package/dist/types2.d.ts +2 -2
  105. package/dist/undo.d.ts +2 -2
  106. package/dist/undo.js +2 -2
  107. package/dist/undo2.d.ts +29 -1
  108. package/dist/undo2.d.ts.map +1 -1
  109. package/dist/variables.d.ts +2 -29
  110. package/dist/variables.js +2 -2
  111. package/dist/variant-properties.d.ts +9 -1
  112. package/dist/variant-properties.d.ts.map +1 -1
  113. package/dist/variant-properties.js +36 -1
  114. package/dist/variant-properties.js.map +1 -1
  115. package/dist/vector-network.d.ts +1 -1
  116. package/dist/vector-network.js +1 -1
  117. package/package.json +60 -9
  118. package/src/behaviours/kinds.ts +185 -0
  119. package/src/behaviours/layers.ts +51 -0
  120. package/src/behaviours/model.ts +192 -0
  121. package/src/behaviours/schema.ts +58 -0
  122. package/src/behaviours/spec.ts +223 -0
  123. package/src/buffered-events.ts +64 -0
  124. package/src/color/contrast.ts +31 -0
  125. package/src/color/index.ts +88 -0
  126. package/src/color/management.ts +210 -0
  127. package/src/color/normalize.ts +7 -0
  128. package/src/color/okhcl.ts +201 -0
  129. package/src/comments/document.ts +51 -0
  130. package/src/comments/list.ts +52 -0
  131. package/src/comments/merge.ts +63 -0
  132. package/src/comments/threads.ts +156 -0
  133. package/src/components/exposure.ts +61 -0
  134. package/src/components/properties.ts +18 -15
  135. package/src/components/variants.ts +53 -0
  136. package/src/constants.ts +2 -0
  137. package/src/coordinate.ts +100 -43
  138. package/src/copy.ts +17 -6
  139. package/src/css/grid.ts +70 -0
  140. package/src/css/index.ts +9 -0
  141. package/src/css/layout.ts +53 -0
  142. package/src/css/shadows.ts +68 -0
  143. package/src/css/values.ts +42 -0
  144. package/src/export-format.ts +12 -0
  145. package/src/fields/geometry.ts +11 -0
  146. package/src/fields/text.ts +35 -0
  147. package/src/gradient.ts +166 -0
  148. package/src/group-bounds.ts +131 -0
  149. package/src/guides.ts +39 -0
  150. package/src/hit-test.ts +262 -46
  151. package/src/icons/glyph.ts +128 -0
  152. package/src/icons/model.ts +54 -0
  153. package/src/icons/schema.ts +18 -0
  154. package/src/index.ts +347 -57
  155. package/src/instance-overrides.ts +27 -0
  156. package/src/instances/content-size.ts +58 -0
  157. package/src/instances/copies.ts +239 -0
  158. package/src/instances/cycles.ts +73 -0
  159. package/src/instances/fields.ts +143 -0
  160. package/src/instances/main-component.ts +19 -0
  161. package/src/instances/placement.ts +29 -0
  162. package/src/instances/source-walk.ts +41 -0
  163. package/src/instances/sync.ts +600 -0
  164. package/src/instances/vector-geometry.ts +81 -0
  165. package/src/instances.ts +125 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +41 -12
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/shared-styles.ts +5 -2
  187. package/src/slots/authoring.ts +101 -0
  188. package/src/slots/content.ts +124 -0
  189. package/src/slots/frames.ts +160 -0
  190. package/src/slots/limits.ts +49 -0
  191. package/src/text/direction.ts +55 -0
  192. package/src/text/index.ts +3 -0
  193. package/src/text/lists.ts +138 -0
  194. package/src/text/paragraphs.ts +241 -0
  195. package/src/{text-picture.ts → text/picture.ts} +21 -29
  196. package/src/text/references.ts +50 -0
  197. package/src/transfer/apply.ts +84 -0
  198. package/src/transfer/history.ts +49 -0
  199. package/src/transfer/identity.ts +16 -0
  200. package/src/transfer/index.ts +6 -0
  201. package/src/transfer/nodes.ts +120 -0
  202. package/src/transfer/plan.ts +130 -0
  203. package/src/transfer/references.ts +9 -0
  204. package/src/transfer/remove.ts +39 -0
  205. package/src/transfer/validation.ts +59 -0
  206. package/src/transfer/variables.ts +82 -0
  207. package/src/types.ts +257 -13
  208. package/src/undo.ts +54 -2
  209. package/src/variables/bindings.ts +224 -0
  210. package/src/variables/fields.ts +43 -0
  211. package/src/variables/token.ts +14 -0
  212. package/src/variables/units.ts +15 -0
  213. package/src/variables.ts +118 -69
  214. package/src/variant-properties.ts +50 -0
  215. package/dist/chunks/components/properties.js.map +0 -1
  216. package/dist/chunks/export-scale.js +0 -19
  217. package/dist/chunks/export-scale.js.map +0 -1
  218. package/dist/coordinate.d.ts.map +0 -1
  219. package/dist/coordinate2.d.ts +0 -2
  220. package/dist/guides2.d.ts +0 -11
  221. package/dist/guides2.d.ts.map +0 -1
  222. package/dist/hit-test.d.ts.map +0 -1
  223. package/dist/layout-guides.d.ts +0 -2
  224. package/dist/layout-guides.js +0 -2
  225. package/dist/layout-guides2.d.ts +0 -16
  226. package/dist/layout-guides2.d.ts.map +0 -1
  227. package/dist/node-defaults.d.ts.map +0 -1
  228. package/dist/preview2.d.ts +0 -12
  229. package/dist/preview2.d.ts.map +0 -1
  230. package/dist/resize.js.map +0 -1
  231. package/dist/variables.d.ts.map +0 -1
  232. package/dist/vector-network2.d.ts +0 -32
  233. package/dist/vector-network2.d.ts.map +0 -1
  234. package/src/instance-overrides.test.ts +0 -67
package/src/index.ts CHANGED
@@ -1,12 +1,58 @@
1
1
  /* eslint-disable max-lines -- SceneGraph exposes a stable facade over domain modules */
2
2
  export * from './mutation-impact'
3
+ export * from './variables/bindings'
4
+ export type { VariableModeFallback } from './variables'
5
+ export { modesDefaultFirst } from './variables'
6
+ export * from './variables/token'
7
+ export * from './plugin-data/field'
8
+ export * from './plugin-data/fields'
9
+ export { rescaleNodeTree, scaleNodeChanges } from './scaling'
10
+ import { TRANSFORM_FIELDS, SIZE_FIELDS } from './fields/geometry'
11
+ export { TRANSFORM_FIELDS, SIZE_FIELDS } from './fields/geometry'
12
+ export { TEXT_METRIC_FIELDS, TEXT_SHAPING_FIELDS, TEXT_LAYOUT_FIELDS } from './fields/text'
13
+ export * from './transfer'
3
14
  export * from './instance-overrides'
4
15
  export * from './images'
5
16
  export * from './components/properties'
17
+ export * from './components/variants'
18
+ export * from './slots/frames'
19
+ export { instanceMainComponent } from './instances/main-component'
20
+ export { canCreateInstance, createsComponentCycle, cycleSafeParent } from './instances/cycles'
21
+ export {
22
+ exposableInstances,
23
+ exposedInstances,
24
+ instanceExposureIssue,
25
+ type InstanceExposureIssue
26
+ } from './components/exposure'
27
+ export * from './slots/content'
28
+ export * from './slots/authoring'
29
+ export * from './slots/limits'
30
+ export * from './behaviours/kinds'
31
+ export * from './icons/schema'
32
+ export * from './icons/model'
33
+ export * from './icons/glyph'
34
+ export * from './shaders/schema'
35
+ export * from './shaders/model'
36
+ export * from './behaviours/layers'
37
+ export * from './behaviours/model'
38
+ export * from './behaviours/spec'
39
+ export * from './comments/document'
40
+ export * from './comments/list'
41
+ export * from './comments/merge'
42
+ export * from './comments/threads'
6
43
  export * from './copy'
44
+ export {
45
+ createDefaultNode,
46
+ defaultStrokeAlign,
47
+ FITTED_CONTAINER_TYPES,
48
+ newStrokeGeometry
49
+ } from './node-defaults'
7
50
  export {
8
51
  copyInstanceComponentProps,
52
+ findInstanceAncestor,
9
53
  hasInstanceOverride,
54
+ INSTANCE_FOLLOWED_FIELDS,
55
+ INSTANCE_OVERRIDE_FIELDS,
10
56
  INSTANCE_SYNC_FIELDS,
11
57
  INSTANCE_SYNC_PROPS,
12
58
  INSTANCE_SYNC_TEXT_PROPS,
@@ -21,46 +67,57 @@ export {
21
67
  type InstanceOverrideState
22
68
  } from './instance-overrides'
23
69
  export * from './snap'
70
+ export * from './export-format'
24
71
  export * from './export-scale'
25
72
  export * from './coordinate'
73
+ export * from './layout'
74
+ export * from './text'
75
+ export * from './group-bounds'
26
76
  export * from './constants'
27
77
  export * from './geometry'
28
78
  export * from './guides'
29
- export * from './layout-guides'
30
79
  export * from './font-style'
31
80
  export * from './shared-styles'
32
81
  export { default as TransformMatrix } from './matrix'
33
82
  export type { Mat3 } from './matrix'
34
- export { UndoManager, type UndoEntry, type UndoManagerOptions } from './undo'
35
-
36
- import { createNanoEvents } from 'nanoevents'
83
+ export { DEFAULT_HISTORY_LIMIT, UndoManager, type UndoEntry, type UndoManagerOptions } from './undo'
37
84
 
38
85
  import { removeStaleBindings } from './bindings'
86
+ export { CommittedGraphEventError } from './buffered-events'
87
+ import { BufferedSceneEmitter } from './buffered-events'
39
88
  import { cloneNodeProps } from './copy'
40
89
  import { bindNodeEvents } from './events'
41
90
  import * as HitTest from './hit-test'
91
+ export type { DropTargetOptions } from './hit-test'
42
92
  import * as Instances from './instances'
93
+ import Matrix, { type Mat3 } from './matrix'
43
94
  import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'
44
95
  import { updateNodePreview, type NodePreviewObserver } from './preview'
96
+ import { randomIndex } from './random'
45
97
  import { styleDetachmentChanges } from './shared-styles'
46
98
  import { markSourceFieldsEdited } from './source-metadata'
47
- import { GLYPH_AFFECTING_KEYS, invalidateTextCaches, TEXT_PICTURE_KEYS } from './text-picture'
99
+ import { GLYPH_AFFECTING_KEYS, invalidateTextCaches, TEXT_PICTURE_KEYS } from './text/picture'
48
100
  import * as Variables from './variables'
101
+ import type { VariableModeFallback } from './variables'
49
102
  import { normalizeVectorNetwork } from './vector-network'
50
103
 
51
104
  export type { GUID, Color, Size, Vector } from './primitives'
52
105
  export * from './types'
53
106
 
54
- import type { Emitter } from 'nanoevents'
55
-
56
- import { getAbsolutePosition } from './coordinate'
107
+ import {
108
+ getAbsolutePosition,
109
+ getNodeLocalMatrix,
110
+ getParentWorldMatrix,
111
+ isTranslationOnly,
112
+ localTransformFromWorld
113
+ } from './coordinate'
57
114
  import type { Color, Rect, Vector } from './primitives'
58
115
  import type {
59
116
  DocumentColorSpace,
60
117
  EnabledLibraryBinding,
61
118
  NodeType,
119
+ NodeChangeObserver,
62
120
  SceneGraphEventHandlers,
63
- SceneGraphEvents,
64
121
  SceneNode,
65
122
  SourceMetadata,
66
123
  Variable,
@@ -78,10 +135,37 @@ export {
78
135
  vectorNetworksEqual
79
136
  } from './vector-network'
80
137
 
138
+ /** Figma reads both parts of a GUID as signed 32-bit integers and drops records beyond them. */
139
+ const MAX_ID_SESSION = 0x7fffffff
140
+
141
+ /** Sessions 0 and 1 hold FIG's document and internal-resource records and counter GUIDs. */
142
+ const FIRST_RANDOM_SESSION = 2
143
+
144
+ /** A random session, as Yjs picks each document's `clientID`, so processes never share IDs. */
145
+ function randomIdSession(): number {
146
+ return FIRST_RANDOM_SESSION + randomIndex(MAX_ID_SESSION - FIRST_RANDOM_SESSION + 1)
147
+ }
148
+
149
+ let idSession = randomIdSession()
81
150
  let nextLocalID = 1
82
151
 
152
+ /**
153
+ * Sets the session part of the IDs this process mints, as in Figma's `sessionID:localID` GUIDs.
154
+ * Every process starts in a random session, so layers that the editor, the CLI, or MCP add to
155
+ * copies of one file never share IDs. Tests and fixtures that need the same IDs on every run
156
+ * set a fixed session or give the graph its own generator. Returns the previous session.
157
+ */
158
+ export function setIdSession(sessionId: number): number {
159
+ if (!Number.isInteger(sessionId) || sessionId < 0 || sessionId > MAX_ID_SESSION) {
160
+ throw new RangeError('sessionId must be a non-negative 31-bit integer')
161
+ }
162
+ const previous = idSession
163
+ idSession = sessionId
164
+ return previous
165
+ }
166
+
83
167
  export function generateId(): string {
84
- return `0:${nextLocalID++}`
168
+ return `${idSession}:${nextLocalID++}`
85
169
  }
86
170
 
87
171
  function stripUndefinedProps<T extends object>(obj: T): T {
@@ -109,17 +193,21 @@ export class SceneGraph {
109
193
  figSchemaDeflated: Uint8Array | null = null
110
194
  documentColorSpace: DocumentColorSpace = 'srgb'
111
195
  enabledLibraries = new Map<string, EnabledLibraryBinding>()
112
- readonly emitter: Emitter<SceneGraphEvents> = createNanoEvents()
196
+ readonly emitter = new BufferedSceneEmitter()
113
197
  private absPosCache = new Map<string, Vector>()
114
198
  private previewMutationDepth = 0
115
199
  private previewObservers: NodePreviewObserver[] = []
200
+ private readonly changeObservers = new Set<NodeChangeObserver>()
116
201
  private sourceMetadataPreservationDepth = 0
202
+ private importedStateApplicationDepth = 0
203
+ private importedIdGenerator: (() => string) | undefined
117
204
  private layoutMutationDepth = 0
205
+ private derivedLayoutDepth = 0
118
206
  positionPreviewVersion = 0
119
207
  instanceIndex = new Map<string, Set<string>>()
120
208
 
121
- constructor() {
122
- const root = createDefaultNode(generateId, 'FRAME', {
209
+ constructor(private readonly idGenerator: () => string = generateId) {
210
+ const root = createDefaultNode(this.idGenerator, 'FRAME', {
123
211
  name: 'Document',
124
212
  width: 0,
125
213
  height: 0
@@ -148,6 +236,23 @@ export class SceneGraph {
148
236
  return bindNodeEvents(this.emitter, handlers)
149
237
  }
150
238
 
239
+ /**
240
+ * Tells `observer` about each node an edit adds and, before it changes, each node it is about
241
+ * to change, so a recorder can keep the node as it was. Unlike node events these are never
242
+ * buffered. Graph methods report the nodes they change; code that writes into a node directly
243
+ * reports it with `willChangeNode` first.
244
+ */
245
+ observeNodeChanges(observer: NodeChangeObserver): () => void {
246
+ this.changeObservers.add(observer)
247
+ return () => this.changeObservers.delete(observer)
248
+ }
249
+
250
+ /** Tells `observeNodeChanges` observers that `node` is about to change. */
251
+ willChangeNode(node: SceneNode | undefined): void {
252
+ if (!node) return
253
+ for (const observer of this.changeObservers) observer.before(node)
254
+ }
255
+
151
256
  countDescendants(nodeId: string): number {
152
257
  const node = this.nodes.get(nodeId)
153
258
  if (!node) return 0
@@ -181,11 +286,30 @@ export class SceneGraph {
181
286
  collectionId: string,
182
287
  value?: VariableValue
183
288
  ): Variable {
184
- return Variables.createVariable(this, generateId, name, type, collectionId, value)
289
+ return Variables.createVariable(
290
+ this,
291
+ () => this.generateEntityId(),
292
+ name,
293
+ type,
294
+ collectionId,
295
+ value
296
+ )
185
297
  }
186
298
 
187
299
  createCollection(name: string): VariableCollection {
188
- return Variables.createCollection(this, generateId, name)
300
+ // The collection and its default mode are both created before either is registered.
301
+ const issued = new Set<string>()
302
+ return Variables.createCollection(this, () => this.generateEntityId(issued), name)
303
+ }
304
+
305
+ createMode(collectionId: string, name: string, sourceModeId?: string): string | undefined {
306
+ return Variables.createMode(
307
+ this,
308
+ () => this.generateEntityId(),
309
+ collectionId,
310
+ name,
311
+ sourceModeId
312
+ )
189
313
  }
190
314
 
191
315
  removeCollection(id: string): void {
@@ -236,12 +360,36 @@ export class SceneGraph {
236
360
  return Variables.resolveNumberVariable(this, variableId)
237
361
  }
238
362
 
239
- resolveColorVariableForNode(nodeId: string, variableId: string): Color | undefined {
240
- return Variables.resolveColorVariableForNode(this, nodeId, variableId)
363
+ resolveColorVariableForNode(
364
+ nodeId: string,
365
+ variableId: string,
366
+ fallback?: VariableModeFallback
367
+ ): Color | undefined {
368
+ return Variables.resolveColorVariableForNode(this, nodeId, variableId, fallback)
369
+ }
370
+
371
+ resolveNumberVariableForNode(
372
+ nodeId: string,
373
+ variableId: string,
374
+ fallback?: VariableModeFallback
375
+ ): number | undefined {
376
+ return Variables.resolveNumberVariableForNode(this, nodeId, variableId, fallback)
377
+ }
378
+
379
+ resolveVariableForNode(
380
+ nodeId: string,
381
+ variableId: string,
382
+ fallback?: VariableModeFallback
383
+ ): VariableValue | undefined {
384
+ return Variables.resolveVariableForNode(this, nodeId, variableId, fallback)
241
385
  }
242
386
 
243
- resolveNumberVariableForNode(nodeId: string, variableId: string): number | undefined {
244
- return Variables.resolveNumberVariableForNode(this, nodeId, variableId)
387
+ resolveStringVariableForNode(
388
+ nodeId: string,
389
+ variableId: string,
390
+ fallback?: VariableModeFallback
391
+ ): string | undefined {
392
+ return Variables.resolveStringVariableForNode(this, nodeId, variableId, fallback)
245
393
  }
246
394
 
247
395
  getVariablesForCollection(collectionId: string): Variable[] {
@@ -274,12 +422,28 @@ export class SceneGraph {
274
422
  }
275
423
 
276
424
  isDescendant(childId: string, ancestorId: string): boolean {
277
- let current = this.nodes.get(childId)
278
- while (current) {
279
- if (current.id === ancestorId) return true
425
+ return this.closest(childId, (node) => node.id === ancestorId) !== undefined
426
+ }
427
+
428
+ /**
429
+ * The node itself or its nearest ancestor that matches. The walk visits at most as many nodes
430
+ * as the graph holds, so a parent cycle in bad data cannot hang it.
431
+ */
432
+ closest(id: string, match: (node: SceneNode) => boolean): SceneNode | undefined {
433
+ let current = this.nodes.get(id)
434
+ for (let steps = 0; current && steps < this.nodes.size; steps++) {
435
+ if (match(current)) return current
280
436
  current = current.parentId ? this.nodes.get(current.parentId) : undefined
281
437
  }
282
- return false
438
+ return undefined
439
+ }
440
+
441
+ /**
442
+ * The page a node is on: the node itself for a page, its nearest page ancestor otherwise, and
443
+ * null for the document root or a node on no page.
444
+ */
445
+ pageOf(id: string): string | null {
446
+ return this.closest(id, (node) => node.type === 'CANVAS')?.id ?? null
283
447
  }
284
448
 
285
449
  clearAbsPosCache(): void {
@@ -308,14 +472,43 @@ export class SceneGraph {
308
472
  height: node?.height ?? 0
309
473
  }
310
474
  }
311
- private generateNodeId(): string {
312
- let id = generateId()
313
- while (this.nodes.has(id)) id = generateId()
314
- return id
475
+ /**
476
+ * An ID no entity uses; `issued` also excludes IDs handed out earlier in the same creation.
477
+ * A generator that returns more taken IDs than the graph holds must be repeating itself, so
478
+ * it counts as exhausted then; a fixed cap would reject a sequence walking past a large import.
479
+ */
480
+ private generateEntityId(issued?: Set<string>): string {
481
+ let limit = Infinity
482
+ for (let attempt = 0; attempt < limit; attempt++) {
483
+ const id = (this.importedIdGenerator ?? this.idGenerator)()
484
+ if (this.isEntityIdTaken(id) || issued?.has(id)) {
485
+ if (limit === Infinity) limit = this.entityIdCount() + (issued?.size ?? 0) + 1
486
+ continue
487
+ }
488
+ issued?.add(id)
489
+ return id
490
+ }
491
+ throw new Error('The ID generator only returned IDs that are in use')
492
+ }
493
+ private entityIdCount(): number {
494
+ let count = this.nodes.size + this.variables.size + this.variableCollections.size
495
+ for (const collection of this.variableCollections.values()) count += collection.modes.length
496
+ return count
497
+ }
498
+ private isEntityIdTaken(id: string): boolean {
499
+ if (this.nodes.has(id) || this.variables.has(id) || this.variableCollections.has(id))
500
+ return true
501
+ // Callers replace collection maps and edit `modes` in place (history snapshots, transfer,
502
+ // undo), so an index of mode IDs would go stale; walk them without allocating instead.
503
+ for (const collection of this.variableCollections.values()) {
504
+ for (const mode of collection.modes) if (mode.modeId === id) return true
505
+ }
506
+ return false
315
507
  }
316
508
  private registerNode(node: SceneNode, parentId: string | null): SceneNode {
317
509
  node.parentId = parentId
318
510
  this.nodes.set(node.id, node)
511
+ for (const observer of this.changeObservers) observer.created(node)
319
512
  if (node.type === 'INSTANCE' && node.componentId) {
320
513
  let set = this.instanceIndex.get(node.componentId)
321
514
  if (!set) {
@@ -327,9 +520,16 @@ export class SceneGraph {
327
520
  this.emitter.emit('node:created', node)
328
521
  return node
329
522
  }
523
+ /** Publish synchronous graph events only after the supplied mutation succeeds. */
524
+ withBufferedEvents<T>(action: () => T): T {
525
+ return this.emitter.batch(action)
526
+ }
527
+
330
528
  createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {
331
- const node = createDefaultNode(() => this.generateNodeId(), type, overrides)
332
- this.nodes.get(parentId)?.childIds.push(node.id)
529
+ const node = createDefaultNode(() => this.generateEntityId(), type, overrides)
530
+ const parent = this.nodes.get(parentId)
531
+ this.willChangeNode(parent)
532
+ parent?.childIds.push(node.id)
333
533
  return this.registerNode(node, parentId)
334
534
  }
335
535
  createNodeWithId(
@@ -341,7 +541,10 @@ export class SceneGraph {
341
541
  const node = createDefaultNode(() => id, type, overrides)
342
542
  node.id = id
343
543
  const parent = parentId ? this.nodes.get(parentId) : undefined
344
- if (parent && !parent.childIds.includes(id)) parent.childIds.push(id)
544
+ if (parent && !parent.childIds.includes(id)) {
545
+ this.willChangeNode(parent)
546
+ parent.childIds.push(id)
547
+ }
345
548
  return this.registerNode(node, parentId)
346
549
  }
347
550
 
@@ -349,13 +552,8 @@ export class SceneGraph {
349
552
  static GLYPH_AFFECTING_KEYS: ReadonlySet<string> = GLYPH_AFFECTING_KEYS
350
553
 
351
554
  static LAYOUT_AFFECTING_KEYS: ReadonlySet<string> = new Set([
352
- 'x',
353
- 'y',
354
- 'width',
355
- 'height',
356
- 'rotation',
357
- 'flipX',
358
- 'flipY',
555
+ ...TRANSFORM_FIELDS,
556
+ ...SIZE_FIELDS,
359
557
  'layoutMode',
360
558
  'layoutDirection',
361
559
  'itemSpacing',
@@ -384,7 +582,8 @@ export class SceneGraph {
384
582
  'minWidth',
385
583
  'maxWidth',
386
584
  'minHeight',
387
- 'maxHeight'
585
+ 'maxHeight',
586
+ 'targetAspectRatio'
388
587
  ])
389
588
 
390
589
  runPreviewUpdates(fn: () => void, beforeUpdate?: NodePreviewObserver): void {
@@ -397,14 +596,51 @@ export class SceneGraph {
397
596
  this.previewMutationDepth--
398
597
  }
399
598
  }
400
- preserveSourceMetadataDuring(fn: () => void): void {
599
+ preserveSourceMetadataDuring<T>(fn: () => T): T {
401
600
  this.sourceMetadataPreservationDepth++
402
601
  try {
403
- fn()
602
+ return fn()
404
603
  } finally {
405
604
  this.sourceMetadataPreservationDepth--
406
605
  }
407
606
  }
607
+ get isPreservingSourceMetadata(): boolean {
608
+ return this.sourceMetadataPreservationDepth > 0
609
+ }
610
+
611
+ applyImportedStateDuring<T>(fn: () => T, idGenerator?: () => string): T {
612
+ const previousGenerator = this.importedIdGenerator
613
+ this.importedIdGenerator = idGenerator ?? previousGenerator
614
+ this.importedStateApplicationDepth++
615
+ try {
616
+ return this.preserveSourceMetadataDuring(fn)
617
+ } finally {
618
+ this.importedStateApplicationDepth--
619
+ this.importedIdGenerator = previousGenerator
620
+ }
621
+ }
622
+
623
+ get isApplyingImportedState(): boolean {
624
+ return this.importedStateApplicationDepth > 0
625
+ }
626
+
627
+ /**
628
+ * Lays out what the document already holds: a page as it loads, or again once its fonts
629
+ * arrive. What this writes derives from the document; an edit's own layout is not this.
630
+ */
631
+ applyDerivedLayoutDuring(fn: () => void): void {
632
+ this.derivedLayoutDepth++
633
+ try {
634
+ fn()
635
+ } finally {
636
+ this.derivedLayoutDepth--
637
+ }
638
+ }
639
+
640
+ get isApplyingDerivedLayout(): boolean {
641
+ return this.derivedLayoutDepth > 0
642
+ }
643
+
408
644
  withLayoutMutations(fn: () => void): void {
409
645
  this.layoutMutationDepth++
410
646
  try {
@@ -454,6 +690,7 @@ export class SceneGraph {
454
690
  absent: readonly (keyof SceneNode)[] = []
455
691
  ): void {
456
692
  const { id } = node
693
+ this.willChangeNode(node)
457
694
  // Include removed keys in cache invalidation and update notifications.
458
695
  if (absent.length) {
459
696
  changes = { ...changes }
@@ -480,7 +717,7 @@ export class SceneGraph {
480
717
  }
481
718
  }
482
719
  if (node.type === 'TEXT') invalidateTextCaches(node, changes)
483
- if (this.sourceMetadataPreservationDepth === 0) {
720
+ if (this.sourceMetadataPreservationDepth === 0 && !this.isApplyingLayout) {
484
721
  markSourceFieldsEdited(node, Object.keys(changes))
485
722
  }
486
723
  if (changes.vectorNetwork) {
@@ -504,14 +741,13 @@ export class SceneGraph {
504
741
  if (node.parentId === newParentId) return
505
742
 
506
743
  const oldParentId = node.parentId
744
+ this.willChangeNode(node)
745
+ this.willChangeNode(oldParent)
746
+ this.willChangeNode(newParent)
507
747
  this.absPosCache.clear()
508
748
 
509
- const absPos = this.getAbsolutePosition(nodeId)
510
- const newParentNode = this.nodes.get(newParentId)
511
- const newParentAbs =
512
- newParentId === this.rootId || newParentNode?.type === 'CANVAS'
513
- ? { x: 0, y: 0 }
514
- : this.getAbsolutePosition(newParentId)
749
+ const oldParentWorld = this.parentWorldMatrix(oldParent)
750
+ const newParentWorld = this.parentWorldMatrix(newParent)
515
751
 
516
752
  if (oldParent) {
517
753
  oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId)
@@ -520,12 +756,22 @@ export class SceneGraph {
520
756
  node.parentId = newParentId
521
757
  newParent.childIds.push(nodeId)
522
758
 
523
- node.x = absPos.x - newParentAbs.x
524
- node.y = absPos.y - newParentAbs.y
759
+ if (isTranslationOnly(oldParentWorld) && isTranslationOnly(newParentWorld)) {
760
+ node.x += oldParentWorld[2] - newParentWorld[2]
761
+ node.y += oldParentWorld[5] - newParentWorld[5]
762
+ } else {
763
+ const world = Matrix.multiply(oldParentWorld, getNodeLocalMatrix(node))
764
+ const local = localTransformFromWorld(node, world, newParentWorld)
765
+ if (local) Object.assign(node, local)
766
+ }
525
767
 
526
768
  this.emitter.emit('node:reparented', nodeId, oldParentId, newParentId)
527
769
  }
528
770
 
771
+ private parentWorldMatrix(parent: SceneNode | undefined): Mat3 {
772
+ return getParentWorldMatrix(parent, this)
773
+ }
774
+
529
775
  reorderChild(nodeId: string, parentId: string, insertIndex: number): void {
530
776
  const node = this.nodes.get(nodeId)
531
777
  if (!node) return
@@ -534,6 +780,9 @@ export class SceneGraph {
534
780
  const oldParent = previousParentId ? this.nodes.get(previousParentId) : undefined
535
781
  const newParent = this.nodes.get(parentId)
536
782
  if (!newParent || this.isDescendant(parentId, nodeId)) return
783
+ this.willChangeNode(node)
784
+ this.willChangeNode(oldParent)
785
+ this.willChangeNode(newParent)
537
786
 
538
787
  // Remove from old parent
539
788
  if (oldParent) {
@@ -563,6 +812,9 @@ export class SceneGraph {
563
812
  if (!node || !newParent || childId === parentId || this.isDescendant(parentId, childId)) return
564
813
  const previousParentId = node.parentId
565
814
  const oldParent = previousParentId ? this.getNode(previousParentId) : undefined
815
+ this.willChangeNode(node)
816
+ this.willChangeNode(oldParent)
817
+ this.willChangeNode(newParent)
566
818
  if (oldParent) {
567
819
  oldParent.childIds = oldParent.childIds.filter((id) => id !== childId)
568
820
  }
@@ -576,9 +828,11 @@ export class SceneGraph {
576
828
  deleteNode(id: string): void {
577
829
  const node = this.nodes.get(id)
578
830
  if (!node || id === this.rootId) return
831
+ this.willChangeNode(node)
579
832
 
580
833
  if (node.parentId) {
581
834
  const parent = this.nodes.get(node.parentId)
835
+ this.willChangeNode(parent)
582
836
  if (parent) {
583
837
  parent.childIds = parent.childIds.filter((cid) => cid !== id)
584
838
  }
@@ -599,17 +853,41 @@ export class SceneGraph {
599
853
  return HitTest.hitTest(this, px, py, scopeId)
600
854
  }
601
855
 
602
- hitTestDeep(px: number, py: number, scopeId?: string): SceneNode | null {
603
- return HitTest.hitTestDeep(this, px, py, scopeId)
856
+ /** `pad`, in canvas units, grows each shape's box, as Figma takes clicks just outside one. */
857
+ hitTestDeep(px: number, py: number, scopeId?: string, pad = 0): SceneNode | null {
858
+ return HitTest.hitTestDeep(this, px, py, scopeId, pad)
859
+ }
860
+
861
+ hitTestSelectable(
862
+ px: number,
863
+ py: number,
864
+ scopeId: string,
865
+ selectedIds: ReadonlySet<string>,
866
+ pad = 0
867
+ ): SceneNode | null {
868
+ return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, pad)
869
+ }
870
+
871
+ hitTestOpenContainer(px: number, py: number, scopeId: string): SceneNode | null {
872
+ return HitTest.hitTestOpenContainer(this, px, py, scopeId)
873
+ }
874
+
875
+ isOpenContainer(nodeId: string): boolean {
876
+ return HitTest.isOpenContainer(this, nodeId)
877
+ }
878
+
879
+ isPointInNode(nodeId: string, px: number, py: number): boolean {
880
+ return HitTest.isPointInNode(this, nodeId, px, py)
604
881
  }
605
882
 
606
- hitTestFrame(
883
+ hitTestDropTarget(
607
884
  px: number,
608
885
  py: number,
609
- excludeIds: Set<string>,
610
- scopeId?: string
886
+ excludeIds: ReadonlySet<string>,
887
+ scopeId?: string,
888
+ options?: HitTest.DropTargetOptions
611
889
  ): SceneNode | null {
612
- return HitTest.hitTestFrame(this, px, py, excludeIds, scopeId)
890
+ return HitTest.hitTestDropTarget(this, px, py, excludeIds, scopeId, options)
613
891
  }
614
892
 
615
893
  cloneTree(
@@ -650,14 +928,26 @@ export class SceneGraph {
650
928
  Instances.populateInstanceChildren(this, instanceId, componentId, mode)
651
929
  }
652
930
 
653
- swapInstanceComponent(instanceId: string, componentId: string): void {
654
- Instances.swapInstanceComponent(this, instanceId, componentId)
931
+ swapInstanceComponent(
932
+ instanceId: string,
933
+ componentId: string,
934
+ options?: Instances.SwapInstanceOptions
935
+ ): void {
936
+ Instances.swapInstanceComponent(this, instanceId, componentId, options)
655
937
  }
656
938
 
657
939
  syncInstances(componentId: string): void {
658
940
  Instances.syncInstances(this, componentId)
659
941
  }
660
942
 
943
+ syncInstancesTogether(componentIds: Iterable<string>): void {
944
+ Instances.syncInstancesTogether(this, componentIds)
945
+ }
946
+
947
+ syncInstance(instanceId: string): void {
948
+ Instances.syncInstance(this, instanceId)
949
+ }
950
+
661
951
  detachInstance(instanceId: string): void {
662
952
  Instances.detachInstance(this, instanceId)
663
953
  }
@@ -89,6 +89,33 @@ export function cloneInstanceOverrideState(state: InstanceOverrideState): Instan
89
89
  }
90
90
  }
91
91
 
92
+ export interface InstanceOverrideReferenceMapper {
93
+ node: (id: string) => string
94
+ variable: (id: string) => string
95
+ }
96
+
97
+ /** Remap runtime identities only; ordinary strings and source-format payloads stay opaque. */
98
+ export function remapInstanceOverrideState(
99
+ state: InstanceOverrideState,
100
+ references: InstanceOverrideReferenceMapper
101
+ ): InstanceOverrideState {
102
+ const remapValue = (field: string, value: unknown): unknown => {
103
+ if (typeof value !== 'string') return structuredClone(value)
104
+ if (field === 'componentId' || field === 'sourceComponentId') return references.node(value)
105
+ if (field.startsWith('boundVariables/')) return references.variable(value)
106
+ return value
107
+ }
108
+ const fields = (entries: ReadonlyMap<string, unknown>) =>
109
+ new Map([...entries].map(([field, value]) => [field, remapValue(field, value)]))
110
+ const descendants = new Map<string, Map<string, unknown>>()
111
+ for (const [id, entries] of state.descendants) {
112
+ const mapped = references.node(id)
113
+ if (descendants.has(mapped)) throw new Error(`Duplicate remapped override target ${mapped}`)
114
+ descendants.set(mapped, fields(entries))
115
+ }
116
+ return { self: fields(state.self), descendants }
117
+ }
118
+
92
119
  export function getInstanceOverride(
93
120
  state: InstanceOverrideState,
94
121
  instanceId: string,