@open-pencil/scene-graph 0.17.0-beta.2 → 0.17.0-beta.4

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 (244) hide show
  1. package/dist/asset-keys.d.ts +11 -1
  2. package/dist/asset-keys.d.ts.map +1 -1
  3. package/dist/asset-keys.js +16 -1
  4. package/dist/asset-keys.js.map +1 -1
  5. package/dist/checkpoint.d.ts +3 -3
  6. package/dist/checkpoint.d.ts.map +1 -1
  7. package/dist/checkpoint.js +53 -23
  8. package/dist/checkpoint.js.map +1 -1
  9. package/dist/components/index.d.ts +2 -2
  10. package/dist/components/index.js +2 -2
  11. package/dist/components/properties.d.ts +6 -1
  12. package/dist/components/properties.d.ts.map +1 -1
  13. package/dist/components/properties.js +9 -1
  14. package/dist/components/properties.js.map +1 -1
  15. package/dist/constants.d.ts +6 -1
  16. package/dist/constants.d.ts.map +1 -1
  17. package/dist/constants.js +17 -1
  18. package/dist/constants.js.map +1 -1
  19. package/dist/constraints.d.ts +25 -0
  20. package/dist/constraints.d.ts.map +1 -0
  21. package/dist/constraints.js +51 -0
  22. package/dist/constraints.js.map +1 -0
  23. package/dist/coordinate.d.ts +64 -1
  24. package/dist/coordinate.d.ts.map +1 -1
  25. package/dist/coordinate.js +217 -1
  26. package/dist/coordinate.js.map +1 -1
  27. package/dist/copy.d.ts.map +1 -1
  28. package/dist/copy.js +8 -1
  29. package/dist/copy.js.map +1 -1
  30. package/dist/css/index.d.ts +3 -2
  31. package/dist/css/index.js +3 -2
  32. package/dist/css/text.d.ts +28 -1
  33. package/dist/css/text.d.ts.map +1 -1
  34. package/dist/css/text.js +84 -17
  35. package/dist/css/text.js.map +1 -1
  36. package/dist/css/transform.d.ts +34 -0
  37. package/dist/css/transform.d.ts.map +1 -0
  38. package/dist/css/transform.js +320 -0
  39. package/dist/css/transform.js.map +1 -0
  40. package/dist/css/values.d.ts.map +1 -1
  41. package/dist/css/values.js +11 -1
  42. package/dist/css/values.js.map +1 -1
  43. package/dist/figjam/palette.d.ts +1 -1
  44. package/dist/figjam/palette.js +1 -1
  45. package/dist/figjam/palette.js.map +1 -1
  46. package/dist/geometry.d.ts +8 -1
  47. package/dist/geometry.d.ts.map +1 -1
  48. package/dist/geometry.js +19 -8
  49. package/dist/geometry.js.map +1 -1
  50. package/dist/graph.d.ts +48 -12
  51. package/dist/graph.d.ts.map +1 -1
  52. package/dist/graph.js +110 -24
  53. package/dist/graph.js.map +1 -1
  54. package/dist/group-bounds.d.ts +14 -4
  55. package/dist/group-bounds.d.ts.map +1 -1
  56. package/dist/group-bounds.js +76 -11
  57. package/dist/group-bounds.js.map +1 -1
  58. package/dist/hit-test.d.ts +5 -0
  59. package/dist/hit-test.d.ts.map +1 -1
  60. package/dist/hit-test.js +18 -12
  61. package/dist/hit-test.js.map +1 -1
  62. package/dist/images.d.ts +27 -3
  63. package/dist/images.d.ts.map +1 -1
  64. package/dist/images.js +57 -3
  65. package/dist/images.js.map +1 -1
  66. package/dist/index.d.ts +2 -2
  67. package/dist/instances/index.d.ts.map +1 -1
  68. package/dist/instances/index.js +3 -0
  69. package/dist/instances/index.js.map +1 -1
  70. package/dist/instances/placement.js +55 -12
  71. package/dist/instances/placement.js.map +1 -1
  72. package/dist/instances/swap.js +3 -0
  73. package/dist/instances/swap.js.map +1 -1
  74. package/dist/instances/sync.js +34 -13
  75. package/dist/instances/sync.js.map +1 -1
  76. package/dist/node-defaults.d.ts.map +1 -1
  77. package/dist/node-defaults.js +1 -0
  78. package/dist/node-defaults.js.map +1 -1
  79. package/dist/order-keys.d.ts +3 -1
  80. package/dist/order-keys.d.ts.map +1 -1
  81. package/dist/order-keys.js +6 -1
  82. package/dist/order-keys.js.map +1 -1
  83. package/dist/plugin-data/fields.d.ts +2 -0
  84. package/dist/plugin-data/fields.d.ts.map +1 -1
  85. package/dist/plugin-data/fields.js +2 -0
  86. package/dist/plugin-data/fields.js.map +1 -1
  87. package/dist/resize.d.ts +22 -11
  88. package/dist/resize.d.ts.map +1 -1
  89. package/dist/resize.js +227 -93
  90. package/dist/resize.js.map +1 -1
  91. package/dist/scaling/index.d.ts +3 -2
  92. package/dist/scaling/index.js +3 -2
  93. package/dist/scaling/node.d.ts.map +1 -1
  94. package/dist/scaling/node.js +5 -1
  95. package/dist/scaling/node.js.map +1 -1
  96. package/dist/scaling/snapshot.d.ts +25 -0
  97. package/dist/scaling/snapshot.d.ts.map +1 -0
  98. package/dist/scaling/snapshot.js +39 -0
  99. package/dist/scaling/snapshot.js.map +1 -0
  100. package/dist/scaling/tree.d.ts +24 -2
  101. package/dist/scaling/tree.d.ts.map +1 -1
  102. package/dist/scaling/tree.js +37 -14
  103. package/dist/scaling/tree.js.map +1 -1
  104. package/dist/shaders/model.d.ts.map +1 -1
  105. package/dist/shaders/model.js +2 -1
  106. package/dist/shaders/model.js.map +1 -1
  107. package/dist/shared-styles.d.ts +3 -1
  108. package/dist/shared-styles.d.ts.map +1 -1
  109. package/dist/shared-styles.js +7 -1
  110. package/dist/shared-styles.js.map +1 -1
  111. package/dist/slots/authoring.d.ts +3 -2
  112. package/dist/slots/authoring.d.ts.map +1 -1
  113. package/dist/slots/authoring.js +5 -3
  114. package/dist/slots/authoring.js.map +1 -1
  115. package/dist/slots/content.d.ts.map +1 -1
  116. package/dist/slots/content.js +4 -1
  117. package/dist/slots/content.js.map +1 -1
  118. package/dist/text/direction.d.ts +3 -1
  119. package/dist/text/direction.d.ts.map +1 -1
  120. package/dist/text/direction.js +5 -1
  121. package/dist/text/direction.js.map +1 -1
  122. package/dist/transfer/apply.d.ts.map +1 -1
  123. package/dist/transfer/apply.js +1 -6
  124. package/dist/transfer/apply.js.map +1 -1
  125. package/dist/transfer/copied.d.ts +35 -3
  126. package/dist/transfer/copied.d.ts.map +1 -1
  127. package/dist/transfer/copied.js +44 -13
  128. package/dist/transfer/copied.js.map +1 -1
  129. package/dist/transfer/dependencies.d.ts +38 -0
  130. package/dist/transfer/dependencies.d.ts.map +1 -0
  131. package/dist/transfer/dependencies.js +100 -0
  132. package/dist/transfer/dependencies.js.map +1 -0
  133. package/dist/transfer/history.js +0 -1
  134. package/dist/transfer/history.js.map +1 -1
  135. package/dist/transfer/index.d.ts +5 -3
  136. package/dist/transfer/index.js +5 -3
  137. package/dist/transfer/nodes.d.ts.map +1 -1
  138. package/dist/transfer/nodes.js +7 -14
  139. package/dist/transfer/nodes.js.map +1 -1
  140. package/dist/transfer/plan.d.ts +0 -1
  141. package/dist/transfer/plan.js +3 -5
  142. package/dist/transfer/plan.js.map +1 -1
  143. package/dist/transfer/remove.js +5 -2
  144. package/dist/transfer/remove.js.map +1 -1
  145. package/dist/transfer/resources.d.ts +21 -0
  146. package/dist/transfer/resources.d.ts.map +1 -0
  147. package/dist/transfer/resources.js +38 -0
  148. package/dist/transfer/resources.js.map +1 -0
  149. package/dist/transfer/variables.d.ts +8 -1
  150. package/dist/transfer/variables.d.ts.map +1 -1
  151. package/dist/transfer/variables.js +24 -1
  152. package/dist/transfer/variables.js.map +1 -1
  153. package/dist/types.d.ts +47 -2
  154. package/dist/types.d.ts.map +1 -1
  155. package/dist/types.js.map +1 -1
  156. package/dist/undo.d.ts +28 -3
  157. package/dist/undo.d.ts.map +1 -1
  158. package/dist/undo.js +24 -7
  159. package/dist/undo.js.map +1 -1
  160. package/dist/variables/bindings.d.ts +17 -14
  161. package/dist/variables/bindings.d.ts.map +1 -1
  162. package/dist/variables/bindings.js +30 -72
  163. package/dist/variables/bindings.js.map +1 -1
  164. package/dist/variables/fields.d.ts +1 -1
  165. package/dist/variables/fields.js +1 -1
  166. package/dist/variables/fields.js.map +1 -1
  167. package/dist/variables/formula/check.d.ts +1 -1
  168. package/dist/variables/formula/index.d.ts +2 -2
  169. package/dist/variables/formula/index.js +1 -1
  170. package/dist/variables/formula/index.js.map +1 -1
  171. package/dist/variables/formula/print.d.ts +1 -1
  172. package/dist/variables/formula/signatures.js +1 -1
  173. package/dist/variables/index.d.ts +6 -6
  174. package/dist/variables/index.d.ts.map +1 -1
  175. package/dist/variables/index.js +40 -24
  176. package/dist/variables/index.js.map +1 -1
  177. package/dist/variables/paints.d.ts +57 -0
  178. package/dist/variables/paints.d.ts.map +1 -0
  179. package/dist/variables/paints.js +231 -0
  180. package/dist/variables/paints.js.map +1 -0
  181. package/dist/variables/resolution.d.ts +14 -11
  182. package/dist/variables/resolution.d.ts.map +1 -1
  183. package/dist/variables/resolution.js +36 -17
  184. package/dist/variables/resolution.js.map +1 -1
  185. package/dist/variables/subtree.js +17 -0
  186. package/dist/variables/subtree.js.map +1 -0
  187. package/dist/vector-network.d.ts.map +1 -1
  188. package/dist/vector-network.js +2 -8
  189. package/dist/vector-network.js.map +1 -1
  190. package/package.json +8 -1
  191. package/src/asset-keys.ts +20 -0
  192. package/src/checkpoint.ts +87 -32
  193. package/src/components/properties.ts +9 -0
  194. package/src/constants.ts +17 -0
  195. package/src/constraints.ts +60 -0
  196. package/src/coordinate.ts +220 -0
  197. package/src/copy.ts +9 -4
  198. package/src/css/index.ts +17 -1
  199. package/src/css/text.ts +85 -17
  200. package/src/css/transform.ts +266 -0
  201. package/src/css/values.ts +8 -0
  202. package/src/figjam/palette.ts +1 -1
  203. package/src/geometry.ts +20 -9
  204. package/src/graph.ts +128 -42
  205. package/src/group-bounds.ts +84 -17
  206. package/src/hit-test.ts +30 -14
  207. package/src/images.ts +71 -3
  208. package/src/instances/index.ts +4 -0
  209. package/src/instances/placement.ts +63 -10
  210. package/src/instances/swap.ts +5 -0
  211. package/src/instances/sync.ts +48 -21
  212. package/src/node-defaults.ts +1 -0
  213. package/src/order-keys.ts +6 -0
  214. package/src/plugin-data/fields.ts +6 -0
  215. package/src/resize.ts +267 -119
  216. package/src/scaling/index.ts +9 -1
  217. package/src/scaling/node.ts +9 -1
  218. package/src/scaling/snapshot.ts +51 -0
  219. package/src/scaling/tree.ts +63 -19
  220. package/src/shaders/model.ts +2 -3
  221. package/src/shared-styles.ts +8 -0
  222. package/src/slots/authoring.ts +5 -3
  223. package/src/slots/content.ts +4 -1
  224. package/src/text/direction.ts +5 -0
  225. package/src/transfer/apply.ts +1 -13
  226. package/src/transfer/copied.ts +83 -15
  227. package/src/transfer/dependencies.ts +126 -0
  228. package/src/transfer/history.ts +0 -6
  229. package/src/transfer/index.ts +20 -2
  230. package/src/transfer/nodes.ts +10 -26
  231. package/src/transfer/plan.ts +3 -11
  232. package/src/transfer/remove.ts +5 -2
  233. package/src/transfer/resources.ts +54 -0
  234. package/src/transfer/variables.ts +34 -0
  235. package/src/types.ts +55 -1
  236. package/src/undo.ts +48 -10
  237. package/src/variables/bindings.ts +44 -91
  238. package/src/variables/fields.ts +1 -1
  239. package/src/variables/formula/index.ts +3 -1
  240. package/src/variables/index.ts +56 -38
  241. package/src/variables/paints.ts +296 -0
  242. package/src/variables/resolution.ts +39 -28
  243. package/src/variables/subtree.ts +15 -0
  244. package/src/vector-network.ts +4 -2
package/src/geometry.ts CHANGED
@@ -95,15 +95,18 @@ function includeRect(bounds: BoundsAccumulator, rect: Rect): void {
95
95
  includePoint(bounds, rect.x + rect.width, rect.y + rect.height)
96
96
  }
97
97
 
98
+ /** `bounds` as a rect at its top-left corner. */
99
+ export function visualBoundsToRect(bounds: VisualBounds): Rect {
100
+ return {
101
+ x: bounds.minX,
102
+ y: bounds.minY,
103
+ width: bounds.maxX - bounds.minX,
104
+ height: bounds.maxY - bounds.minY
105
+ }
106
+ }
107
+
98
108
  function boundsToRect(bounds: BoundsAccumulator): Rect {
99
- return bounds.minX === Infinity
100
- ? { x: 0, y: 0, width: 0, height: 0 }
101
- : {
102
- x: bounds.minX,
103
- y: bounds.minY,
104
- width: bounds.maxX - bounds.minX,
105
- height: bounds.maxY - bounds.minY
106
- }
109
+ return bounds.minX === Infinity ? { x: 0, y: 0, width: 0, height: 0 } : visualBoundsToRect(bounds)
107
110
  }
108
111
 
109
112
  export function computeBounds(items: Iterable<Rect>): Rect {
@@ -225,6 +228,14 @@ export function drawnBlurRadius(radius: number): number {
225
228
  return Math.max(0, radius)
226
229
  }
227
230
 
231
+ /**
232
+ * The widest radius an effect blurs by: its radius, or the larger end of a progressive blur,
233
+ * which can start wider than it ends. Bounds and padding that must hold the whole blur use it.
234
+ */
235
+ export function widestBlurRadius(effect: Pick<Effect, 'radius' | 'progressive'>): number {
236
+ return Math.max(effect.radius, effect.progressive?.startRadius ?? effect.radius)
237
+ }
238
+
228
239
  const BLUR_SIGMA_PER_RADIUS = 0.43
229
240
 
230
241
  /**
@@ -256,7 +267,7 @@ export function effectOverflow(effects?: Effect[]) {
256
267
  ) {
257
268
  continue
258
269
  }
259
- const blurSpread = drawnBlurRadius(effect.radius) + effect.spread
270
+ const blurSpread = drawnBlurRadius(widestBlurRadius(effect)) + effect.spread
260
271
  left = Math.max(left, blurSpread + Math.max(0, -effect.offset.x))
261
272
  right = Math.max(right, blurSpread + Math.max(0, effect.offset.x))
262
273
  top = Math.max(top, blurSpread + Math.max(0, -effect.offset.y))
package/src/graph.ts CHANGED
@@ -42,18 +42,22 @@ import type {
42
42
  VariableLiteral
43
43
  } from './types'
44
44
  import * as Variables from './variables'
45
- import type { VariableModeFallback } from './variables'
46
45
  import { normalizeVectorNetwork } from './vector-network'
47
46
 
48
47
  /** Scopes that graph methods check while a caller's callback runs; scopes nest. */
49
- type GraphScope = 'preview' | 'sourceMetadata' | 'importedState' | 'layout' | 'derivedLayout'
48
+ type GraphScope =
49
+ | 'preview'
50
+ | 'sourceMetadata'
51
+ | 'importedState'
52
+ | 'layout'
53
+ | 'derivedLayout'
54
+ | 'componentDerived'
50
55
 
51
56
  export class SceneGraph {
52
57
  nodes = new Map<string, SceneNode>()
53
58
  images = new Map<string, Uint8Array>()
54
59
  variables = new Map<string, Variable>()
55
60
  variableCollections = new Map<string, VariableCollection>()
56
- activeMode = new Map<string, string>()
57
61
  rootId: string
58
62
  figKiwiVersion: number | null = null
59
63
  /** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */
@@ -68,10 +72,14 @@ export class SceneGraph {
68
72
  sourceMetadata: 0,
69
73
  importedState: 0,
70
74
  layout: 0,
71
- derivedLayout: 0
75
+ derivedLayout: 0,
76
+ componentDerived: 0
72
77
  }
73
78
  private previewObservers: NodePreviewObserver[] = []
74
79
  private readonly changeObservers = new Set<NodeChangeObserver>()
80
+ /** How many waits outside the edit each recorder is paused for. */
81
+ private readonly outsideWaits = new Map<NodeChangeObserver, number>()
82
+ private outsideWrites = 0
75
83
  private importedIdGenerator: (() => string) | undefined
76
84
  private layoutWrites: LayoutWrites | null = null
77
85
  positionPreviewVersion = 0
@@ -110,22 +118,96 @@ export class SceneGraph {
110
118
  }
111
119
 
112
120
  /**
113
- * Tells `observer` about each node an edit adds and, before it changes, each node it is about
114
- * to change, so a recorder can keep the node as it was. Unlike node events these are never
115
- * buffered. Graph methods report the nodes they change; code that writes into a node directly
116
- * reports it with `willChangeNode` first.
121
+ * Tells `observer` about each node an edit adds and, before it changes, each node, variable,
122
+ * and collection it is about to change, so a recorder can keep it as it was. Unlike node events
123
+ * these are never buffered. Graph methods report what they change; code that writes into a
124
+ * node, variable, or collection directly reports it with `willChangeNode`,
125
+ * `willChangeVariable`, or `willChangeCollection` first.
117
126
  */
118
127
  observeNodeChanges(observer: NodeChangeObserver): () => void {
119
128
  this.changeObservers.add(observer)
120
129
  return () => this.changeObservers.delete(observer)
121
130
  }
122
131
 
132
+ /**
133
+ * Waits for `promise`, such as a font or an image download an edit needs, outside the edit in
134
+ * progress: what changes meanwhile, such as the user's or a collaborator's edit, is not recorded
135
+ * as the waiting edit's. Only for code that writes nothing itself until the wait ends.
136
+ */
137
+ async waitOutsideEdit<T>(promise: Promise<T>): Promise<T> {
138
+ const resume = this.pauseOpenEdits()
139
+ try {
140
+ return await promise
141
+ } finally {
142
+ resume()
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Runs `write`, a change someone else makes, such as a collaborator's arriving or an undo,
148
+ * outside every edit in progress, so none records it as its own.
149
+ */
150
+ runOutsideEdits<T>(write: () => T): T {
151
+ const resume = this.pauseOpenEdits()
152
+ this.outsideWrites++
153
+ try {
154
+ return write()
155
+ } finally {
156
+ this.outsideWrites--
157
+ resume()
158
+ }
159
+ }
160
+
161
+ /** Whether a write run with `runOutsideEdits`, such as a collaborator's change, is in progress. */
162
+ get isWritingOutsideEdits(): boolean {
163
+ return this.outsideWrites > 0
164
+ }
165
+
166
+ /**
167
+ * Pauses the recorders open now, and only those, until the returned function resumes them: a
168
+ * recorder that opens while an earlier pause is still pending, such as during a script's load
169
+ * left unawaited, pauses for its own waits and is not resumed by the earlier one.
170
+ */
171
+ private pauseOpenEdits(): () => void {
172
+ const paused = [...this.changeObservers]
173
+ for (const observer of paused) {
174
+ const waits = this.outsideWaits.get(observer) ?? 0
175
+ if (waits === 0) observer.pause?.()
176
+ this.outsideWaits.set(observer, waits + 1)
177
+ }
178
+ return () => {
179
+ for (const observer of paused) {
180
+ const waits = (this.outsideWaits.get(observer) ?? 1) - 1
181
+ if (waits > 0) {
182
+ this.outsideWaits.set(observer, waits)
183
+ continue
184
+ }
185
+ this.outsideWaits.delete(observer)
186
+ if (this.changeObservers.has(observer)) observer.resume?.()
187
+ }
188
+ }
189
+ }
190
+
123
191
  /** Tells `observeNodeChanges` observers that `node` is about to change. */
124
192
  willChangeNode(node: SceneNode | undefined): void {
125
193
  if (!node) return
126
194
  for (const observer of this.changeObservers) observer.before(node)
127
195
  }
128
196
 
197
+ /**
198
+ * Tells `observeNodeChanges` observers that the variable `id` is about to change, be added, or
199
+ * be removed. Graph methods report the variables they change; code that writes into one
200
+ * directly reports it first.
201
+ */
202
+ willChangeVariable(id: string): void {
203
+ for (const observer of this.changeObservers) observer.beforeRecord?.('variable', id)
204
+ }
205
+
206
+ /** As `willChangeVariable`, for the collection `id`. */
207
+ willChangeCollection(id: string): void {
208
+ for (const observer of this.changeObservers) observer.beforeRecord?.('collection', id)
209
+ }
210
+
129
211
  countDescendants(nodeId: string): number {
130
212
  const node = this.nodes.get(nodeId)
131
213
  if (!node) return 0
@@ -189,18 +271,10 @@ export class SceneGraph {
189
271
  Variables.removeCollection(this, id)
190
272
  }
191
273
 
192
- getActiveModeId(collectionId: string): string {
193
- return Variables.getActiveModeId(this, collectionId)
194
- }
195
-
196
274
  getNodeVariableModeId(nodeId: string, collectionId: string): string {
197
275
  return Variables.getNodeVariableModeId(this, nodeId, collectionId)
198
276
  }
199
277
 
200
- setActiveMode(collectionId: string, modeId: string): void {
201
- Variables.setActiveMode(this, collectionId, modeId)
202
- }
203
-
204
278
  addMode(collectionId: string, modeId: string, name: string, sourceMode?: string): void {
205
279
  Variables.addMode(this, collectionId, modeId, name, sourceMode)
206
280
  }
@@ -233,36 +307,20 @@ export class SceneGraph {
233
307
  return Variables.resolveNumberVariable(this, variableId)
234
308
  }
235
309
 
236
- resolveColorVariableForNode(
237
- nodeId: string,
238
- variableId: string,
239
- fallback?: VariableModeFallback
240
- ): Color | undefined {
241
- return Variables.resolveColorVariableForNode(this, nodeId, variableId, fallback)
310
+ resolveColorVariableForNode(nodeId: string, variableId: string): Color | undefined {
311
+ return Variables.resolveColorVariableForNode(this, nodeId, variableId)
242
312
  }
243
313
 
244
- resolveNumberVariableForNode(
245
- nodeId: string,
246
- variableId: string,
247
- fallback?: VariableModeFallback
248
- ): number | undefined {
249
- return Variables.resolveNumberVariableForNode(this, nodeId, variableId, fallback)
314
+ resolveNumberVariableForNode(nodeId: string, variableId: string): number | undefined {
315
+ return Variables.resolveNumberVariableForNode(this, nodeId, variableId)
250
316
  }
251
317
 
252
- resolveVariableForNode(
253
- nodeId: string,
254
- variableId: string,
255
- fallback?: VariableModeFallback
256
- ): VariableLiteral | undefined {
257
- return Variables.resolveVariableForNode(this, nodeId, variableId, fallback)
318
+ resolveVariableForNode(nodeId: string, variableId: string): VariableLiteral | undefined {
319
+ return Variables.resolveVariableForNode(this, nodeId, variableId)
258
320
  }
259
321
 
260
- resolveStringVariableForNode(
261
- nodeId: string,
262
- variableId: string,
263
- fallback?: VariableModeFallback
264
- ): string | undefined {
265
- return Variables.resolveStringVariableForNode(this, nodeId, variableId, fallback)
322
+ resolveStringVariableForNode(nodeId: string, variableId: string): string | undefined {
323
+ return Variables.resolveStringVariableForNode(this, nodeId, variableId)
266
324
  }
267
325
 
268
326
  getVariablesForCollection(collectionId: string): Variable[] {
@@ -474,6 +532,19 @@ export class SceneGraph {
474
532
  this.withScope('derivedLayout', fn)
475
533
  }
476
534
 
535
+ /**
536
+ * Runs `fn` as values a copy takes from its component, such as the bound paints of a layer an
537
+ * instance copies, refreshed for it. Source metadata is preserved, and a save leaves them to the
538
+ * component rather than writing them as edits of the copy.
539
+ */
540
+ applyComponentDerivedDuring(fn: () => void): void {
541
+ this.withScope('componentDerived', () => this.preserveSourceMetadataDuring(fn))
542
+ }
543
+
544
+ get isApplyingComponentDerived(): boolean {
545
+ return this.scopeDepths.componentDerived > 0
546
+ }
547
+
477
548
  get isApplyingDerivedLayout(): boolean {
478
549
  return this.scopeDepths.derivedLayout > 0
479
550
  }
@@ -595,11 +666,19 @@ export class SceneGraph {
595
666
  this.scopeDepths.sourceMetadata === 0 && !this.isApplyingDerivedLayout
596
667
  )
597
668
  Object.assign(node, changes)
669
+ this.followListBindings(node, changes)
670
+ for (const key of absent) Reflect.deleteProperty(node, key)
671
+ this.publishNodeUpdate(id, changes)
672
+ }
673
+
674
+ /** Bindings of paints and effects a write sets follow the lists it wrote. */
675
+ private followListBindings(node: SceneNode, changes: Partial<SceneNode>): void {
598
676
  if (changes.fills) removeStaleBindings(node, 'fills', changes)
599
677
  if (changes.strokes) removeStaleBindings(node, 'strokes', changes)
600
678
  if (changes.effects) removeStaleBindings(node, 'effects', changes)
601
- for (const key of absent) Reflect.deleteProperty(node, key)
602
- this.publishNodeUpdate(id, changes)
679
+ // A bound paint written keeps what it was given until its variable's color changes.
680
+ if ((changes.fills || changes.strokes) && !this.isApplyingImportedState)
681
+ Variables.recordWrittenBoundPaints(this, node, changes)
603
682
  }
604
683
 
605
684
  /** Marks fields an edit changed, unless metadata is being restored or layout is writing them. */
@@ -656,6 +735,8 @@ export class SceneGraph {
656
735
  )
657
736
 
658
737
  this.emitter.emit('node:reparented', nodeId, oldParentId, newParentId)
738
+ // Bound paints show their variables in the modes the layer now sits in.
739
+ Variables.refreshMovedBoundPaints(this, nodeId, oldParentId)
659
740
  }
660
741
 
661
742
  /**
@@ -681,6 +762,8 @@ export class SceneGraph {
681
762
  node.parentId = parentId
682
763
  this.absPosCache.clear()
683
764
  this.emitter.emit('node:reordered', childId, parentId, at, previousParentId)
765
+ if (previousParentId !== parentId)
766
+ Variables.refreshMovedBoundPaints(this, childId, previousParentId)
684
767
  }
685
768
 
686
769
  deleteNode(id: string): void {
@@ -757,6 +840,8 @@ export class SceneGraph {
757
840
  // Copies point at one another, as a paste's do: an instance at a component cloned with it,
758
841
  // as Figma's clone does (desktop 126), and its override records at its copies' new ids.
759
842
  remapCopiedReferences(this, ids)
843
+ // A copy placed in other modes than its source shows its bound paints there, as a move does.
844
+ if (clone) Variables.refreshMovedBoundPaints(this, clone.id, this.nodes.get(sourceId)?.parentId)
760
845
  return clone
761
846
  }
762
847
 
@@ -775,6 +860,7 @@ export class SceneGraph {
775
860
  // A copy is a new design nobody has reviewed: Figma's duplicate and clone() drop the status.
776
861
  props.status = null
777
862
  const clone = this.createNode(src.type, parentId, { ...props, ...overrides })
863
+ Variables.copyAppliedBoundPaints(src, clone)
778
864
  if (src.status) markSourceFieldsEdited(clone, ['status'])
779
865
  ids.set(src.id, clone.id)
780
866
 
@@ -1,9 +1,16 @@
1
- import { getAxisAlignedBoundsInParent } from './coordinate'
1
+ import { getAxisAlignedBoundsInParent, getNodeLocalMatrix } from './coordinate'
2
2
  import type { SceneGraph } from './graph'
3
+ import Matrix from './matrix'
3
4
  import { FITTED_CONTAINER_TYPES } from './node-defaults'
4
5
  import type { Rect, Vector } from './primitives'
5
6
  import type { SceneNode } from './types'
6
7
 
8
+ /**
9
+ * What fitting a group reads: its layers and their parents, as the graph has them or as a resize
10
+ * plans them before writing.
11
+ */
12
+ export type GroupFitGraph = Pick<SceneGraph, 'getNode' | 'rootId'>
13
+
7
14
  /** Where a layer sits, with a connector's ends, since a free end is in the parent's axes too. */
8
15
  type Placement = Pick<SceneNode, 'x' | 'y' | 'width' | 'height'> &
9
16
  Partial<Pick<SceneNode, 'connectorStart' | 'connectorEnd'>>
@@ -80,7 +87,7 @@ function groupBoundingLayers(children: readonly SceneNode[]): SceneNode[] {
80
87
  * empty at `origin`, where Figma leaves it.
81
88
  */
82
89
  export function groupBounds(
83
- graph: SceneGraph,
90
+ graph: GroupFitGraph,
84
91
  children: readonly SceneNode[],
85
92
  parentId: string,
86
93
  origin: Vector
@@ -102,6 +109,76 @@ function shiftedBack(child: SceneNode, dx: number, dy: number): Partial<SceneNod
102
109
  }
103
110
  }
104
111
 
112
+ function isTransformed(node: SceneNode): boolean {
113
+ return node.rotation !== 0 || node.flipX || node.flipY
114
+ }
115
+
116
+ /**
117
+ * The group's new box in its parent's space and how far its children shift in its own frame, so
118
+ * that the group holds its children while they stay put on the canvas. An unrotated group takes
119
+ * their bounds in its parent's space. A rotated or flipped group keeps its angle: it takes their
120
+ * bounds in its own frame, and its position is solved so its frame still maps every child to the
121
+ * same canvas point, as its rotation and flips are unchanged. A rotated or flipped boolean, whose
122
+ * box comes from its result's path, keeps its bounds.
123
+ */
124
+ function fittedBox(
125
+ graph: GroupFitGraph,
126
+ group: SceneNode,
127
+ parentId: string,
128
+ children: SceneNode[],
129
+ options: GroupFitOptions
130
+ ): { box: Rect; shift: Vector } | null {
131
+ if (!isTransformed(group)) {
132
+ const box =
133
+ (group.type === 'BOOLEAN_OPERATION' ? options.booleanBounds?.(group) : null) ??
134
+ groupBounds(graph, children, parentId, group)
135
+ return { box, shift: { x: box.x - group.x, y: box.y - group.y } }
136
+ }
137
+ if (group.type === 'BOOLEAN_OPERATION') return null
138
+ const local = groupBounds(graph, children, group.id, { x: 0, y: 0 })
139
+ const [px, py] = Matrix.mapPoints(getNodeLocalMatrix(group), [local.x, local.y])
140
+ const sized = { ...group, width: local.width, height: local.height }
141
+ const [qx, qy] = Matrix.mapPoints(getNodeLocalMatrix(sized, { x: 0, y: 0 }), [0, 0])
142
+ return {
143
+ box: { x: px - qx, y: py - qy, width: local.width, height: local.height },
144
+ shift: { x: local.x, y: local.y }
145
+ }
146
+ }
147
+
148
+ const FIT_TOLERANCE = 1e-9
149
+
150
+ function unchanged(value: number, previous: number): boolean {
151
+ return Math.abs(value - previous) <= FIT_TOLERANCE * Math.max(1, Math.abs(previous))
152
+ }
153
+
154
+ /**
155
+ * The changes that fit `group` to `children`: its box in its parent's space, and each child moved
156
+ * back so it stays put on the canvas. Null when the fit changes nothing.
157
+ */
158
+ export function groupFitChanges(
159
+ graph: GroupFitGraph,
160
+ group: SceneNode,
161
+ children: SceneNode[],
162
+ options: GroupFitOptions = {}
163
+ ): Map<string, Partial<SceneNode>> | null {
164
+ if (!group.parentId) return null
165
+ const fitted = fittedBox(graph, group, group.parentId, children, options)
166
+ if (!fitted) return null
167
+ const { box, shift } = fitted
168
+ // A rotated group's frame leaves rounding residue; a fit within it changes nothing.
169
+ if (
170
+ unchanged(shift.x, 0) &&
171
+ unchanged(shift.y, 0) &&
172
+ unchanged(box.width, group.width) &&
173
+ unchanged(box.height, group.height)
174
+ ) {
175
+ return null
176
+ }
177
+ const changes = new Map<string, Partial<SceneNode>>([[group.id, box]])
178
+ for (const child of children) changes.set(child.id, shiftedBack(child, shift.x, shift.y))
179
+ return changes
180
+ }
181
+
105
182
  /** Moves the group to its children's bounds, shifting them back so they stay put. */
106
183
  function fitGroup(
107
184
  graph: SceneGraph,
@@ -110,22 +187,12 @@ function fitGroup(
110
187
  fit: GroupFit,
111
188
  options: GroupFitOptions
112
189
  ) {
113
- if (!group.parentId || group.rotation !== 0 || group.flipX || group.flipY) return
114
- const bounds =
115
- (group.type === 'BOOLEAN_OPERATION' ? options.booleanBounds?.(group) : null) ??
116
- groupBounds(graph, children, group.parentId, group)
117
- const dx = bounds.x - group.x
118
- const dy = bounds.y - group.y
119
- if (dx === 0 && dy === 0 && bounds.width === group.width && bounds.height === group.height) {
120
- return
121
- }
190
+ const changes = groupFitChanges(graph, group, children, options)
191
+ if (!changes) return
122
192
  for (const node of [group, ...children]) {
123
193
  if (!fit.before.has(node.id)) fit.before.set(node.id, placement(node))
124
194
  }
125
- graph.updateNode(group.id, bounds)
126
- for (const child of children) {
127
- graph.updateNode(child.id, shiftedBack(child, dx, dy))
128
- }
195
+ for (const [id, change] of changes) graph.updateNode(id, change)
129
196
  for (const node of [group, ...children]) {
130
197
  const current = graph.getNode(node.id)
131
198
  if (current) fit.after.set(node.id, placement(current))
@@ -143,8 +210,8 @@ function removeEmptyGroup(graph: SceneGraph, group: SceneNode, fit: GroupFit) {
143
210
  /**
144
211
  * Refits the groups and booleans around these parents to their children, keeping every child where
145
212
  * it is on the canvas, and removes groups left empty, as Figma does after a layer inside one moves,
146
- * resizes, or leaves. Rotated or flipped containers keep their bounds. Returns null when nothing
147
- * changed.
213
+ * resizes, or leaves. Rotated or flipped groups keep their angle; a rotated or flipped boolean keeps
214
+ * its bounds. Returns null when nothing changed.
148
215
  */
149
216
  export function fitEnclosingGroups(
150
217
  graph: SceneGraph,
package/src/hit-test.ts CHANGED
@@ -93,11 +93,13 @@ interface HitWalk {
93
93
  deep: boolean
94
94
  pad: number
95
95
  instanceBodies: boolean
96
+ /** Whether locked layers are hit, as by a right-click; see `SelectableHitOptions.locked`. */
97
+ locked: boolean
96
98
  transformCache: Map<string, boolean>
97
99
  }
98
100
 
99
- function walkOf(deep: boolean, pad = 0, instanceBodies = false): HitWalk {
100
- return { deep, pad, instanceBodies, transformCache: new Map() }
101
+ function walkOf(deep: boolean, pad = 0, instanceBodies = false, locked = false): HitWalk {
102
+ return { deep, pad, instanceBodies, locked, transformCache: new Map() }
101
103
  }
102
104
 
103
105
  /** Whether a container's empty area under the point takes a click reaching past containers. */
@@ -108,6 +110,14 @@ function takesEmptyArea(graph: SceneGraph, node: SceneNode, walk: HitWalk): bool
108
110
  return walk.instanceBodies && node.type === 'INSTANCE'
109
111
  }
110
112
 
113
+ /**
114
+ * What a hit inside a container reports: the container itself when it is locked (a locked layer,
115
+ * where one is hit at all, stands in for everything inside it) or the walk stops at containers.
116
+ */
117
+ function standIn(container: SceneNode, hit: SceneNode, deep: boolean): SceneNode {
118
+ return container.locked || !deep ? container : hit
119
+ }
120
+
111
121
  function hitTestTransparentContainer(
112
122
  graph: SceneGraph,
113
123
  px: number,
@@ -121,14 +131,11 @@ function hitTestTransparentContainer(
121
131
  // A group has no area of its own, as in Figma: between its layers the click falls through to
122
132
  // whatever lies under the group.
123
133
  const childHit = hitTestChildren(graph, px, py, child.id, walk)
124
- return childHit ? (walk.deep ? childHit : child) : null
134
+ return childHit ? standIn(child, childHit, walk.deep) : null
125
135
  }
126
136
 
127
137
  const childHit = hitTestChildren(graph, px, py, child.id, walk)
128
- if (childHit) {
129
- if (child.locked) return child
130
- return childHit
131
- }
138
+ if (childHit) return standIn(child, childHit, true)
132
139
 
133
140
  if (
134
141
  containsPoint(px, py, child, graph, walk.transformCache) &&
@@ -156,7 +163,9 @@ function hitTestChildren(
156
163
 
157
164
  for (let i = parent.childIds.length - 1; i >= 0; i--) {
158
165
  const child = graph.nodes.get(parent.childIds[i])
159
- if (!child || child.internalOnly || !child.visible) continue
166
+ // A locked layer and everything in it are invisible to a press and to hover, as in Figma: a
167
+ // click falls through to what lies under it, and a drag from it draws a marquee.
168
+ if (!child || child.internalOnly || !child.visible || (child.locked && !walk.locked)) continue
160
169
  if (CONTAINER_TYPES.has(child.type)) {
161
170
  if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {
162
171
  // A plain click takes an instance or component anywhere in its box, with a fill or
@@ -240,12 +249,14 @@ function frameChildAt(
240
249
  container: SceneNode,
241
250
  px: number,
242
251
  py: number,
243
- framesOpen = true
252
+ framesOpen = true,
253
+ locked = false
244
254
  ): SceneNode | null {
245
255
  const transformCache = new Map<string, boolean>()
246
256
  for (let i = container.childIds.length - 1; i >= 0; i--) {
247
257
  const child = graph.nodes.get(container.childIds[i])
248
258
  if (!child || child.internalOnly || !child.visible || child.type !== 'FRAME') continue
259
+ if (child.locked && !locked) continue
249
260
  // A board, such as a top-level frame in a section, keeps its empty area as background.
250
261
  if (opensByItself(graph, child, framesOpen) && !ownsItsEmptyArea(graph, child)) continue
251
262
  if (containsPoint(px, py, child, graph, transformCache)) return child
@@ -309,6 +320,11 @@ export interface SelectableHitOptions {
309
320
  framesOpen?: boolean
310
321
  /** The container a double-click entered, open along with its ancestors. */
311
322
  enteredId?: string | null
323
+ /**
324
+ * Whether locked layers are hit, each standing in for everything inside it: a right-click
325
+ * selects one, as in Figma, while a press and hover pass through it.
326
+ */
327
+ locked?: boolean
312
328
  }
313
329
 
314
330
  export function hitTestSelectable(
@@ -319,12 +335,12 @@ export function hitTestSelectable(
319
335
  selectedIds: ReadonlySet<string>,
320
336
  options: SelectableHitOptions = {}
321
337
  ): SceneNode | null {
322
- const { pad = 0, framesOpen = true, enteredId = null } = options
338
+ const { pad = 0, framesOpen = true, enteredId = null, locked = false } = options
323
339
  // A plain click: the walk takes an instance's empty area whatever its fill.
324
- const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true, pad, true))
340
+ const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true, pad, true, locked))
325
341
  if (!deepest) {
326
342
  const scope = graph.nodes.get(scopeId)
327
- return scope ? frameChildAt(graph, scope, px, py, framesOpen) : null
343
+ return scope ? frameChildAt(graph, scope, px, py, framesOpen, locked) : null
328
344
  }
329
345
 
330
346
  const chain: SceneNode[] = []
@@ -336,13 +352,13 @@ export function hitTestSelectable(
336
352
  const opened = openedBySelection(graph, selectedIds, scopeId, framesOpen, enteredId)
337
353
 
338
354
  for (const node of chain) {
339
- // A locked layer stands in for everything inside it.
355
+ // A locked layer, hit only with `locked`, stands in for everything inside it.
340
356
  if (node.locked) return node
341
357
  if (!opened.has(node.id) && !opensByItself(graph, node, framesOpen)) return node
342
358
  }
343
359
  const last = chain.at(-1)
344
360
  if (!last) return null
345
- const frame = frameChildAt(graph, last, px, py, framesOpen)
361
+ const frame = frameChildAt(graph, last, px, py, framesOpen, locked)
346
362
  if (frame) return frame
347
363
  if (ownsItsEmptyArea(graph, last)) return last
348
364
  return opened.has(last.id) && !opensByItself(graph, last, framesOpen) ? last : null