@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/hit-test.ts CHANGED
@@ -2,6 +2,7 @@ import { hitsConnectorLine } from './connectors/hit'
2
2
  import { getWorldMatrix } from './coordinate'
3
3
  import type { SceneGraph } from './graph'
4
4
  import Matrix from './matrix'
5
+ import { hitsShape, isHitPaint, strokeReach } from './outline/hit'
5
6
  import type { SceneNode, NodeType } from './types'
6
7
 
7
8
  const CONTAINER_TYPES = new Set<NodeType>([
@@ -15,8 +16,9 @@ const CONTAINER_TYPES = new Set<NodeType>([
15
16
  ])
16
17
  const OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])
17
18
 
18
- function hasVisibleFillOrStroke(node: SceneNode): boolean {
19
- return node.fills.some((f) => f.visible) || node.strokes.some((s) => s.visible)
19
+ /** Whether a container's own paints show, so its empty area is drawn (see `isHitPaint`). */
20
+ function showsPaint(node: SceneNode): boolean {
21
+ return node.fills.some(isHitPaint) || node.strokes.some(isHitPaint)
20
22
  }
21
23
 
22
24
  function isTopLevel(graph: SceneGraph, node: SceneNode): boolean {
@@ -81,96 +83,88 @@ function containsPoint(
81
83
  )
82
84
  }
83
85
 
84
- function hitTestOpaqueContainer(
85
- graph: SceneGraph,
86
- px: number,
87
- py: number,
88
- child: SceneNode,
89
- childId: string,
90
- deep: boolean,
91
- transformCache: Map<string, boolean>,
86
+ /**
87
+ * How a walk down the layers takes a click. `deep` reaches past containers to the deepest layer;
88
+ * `pad`, in canvas units, grows each leaf layer's box, as Figma takes a click a few screen pixels
89
+ * outside a shape; `instanceBodies` lets a deep walk take an instance's empty area whatever its
90
+ * fill, as a plain click does, where a ⌘-click counts only a fill that shows.
91
+ */
92
+ interface HitWalk {
93
+ deep: boolean
92
94
  pad: number
93
- ): SceneNode | null {
94
- if (!containsPoint(px, py, child, graph, transformCache)) return null
95
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
96
- if (childHit) return child
97
- if (hasVisibleFillOrStroke(child)) return child
98
- return null
95
+ instanceBodies: boolean
96
+ transformCache: Map<string, boolean>
97
+ }
98
+
99
+ function walkOf(deep: boolean, pad = 0, instanceBodies = false): HitWalk {
100
+ return { deep, pad, instanceBodies, transformCache: new Map() }
101
+ }
102
+
103
+ /** Whether a container's empty area under the point takes a click reaching past containers. */
104
+ function takesEmptyArea(graph: SceneGraph, node: SceneNode, walk: HitWalk): boolean {
105
+ // Figma counts an empty area only where a paint shows, except a main component's, which always
106
+ // counts, and an instance's when the click is a plain one.
107
+ if (node.type === 'COMPONENT' || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true
108
+ return walk.instanceBodies && node.type === 'INSTANCE'
99
109
  }
110
+
100
111
  function hitTestTransparentContainer(
101
112
  graph: SceneGraph,
102
113
  px: number,
103
114
  py: number,
104
115
  child: SceneNode,
105
- childId: string,
106
- deep: boolean,
107
- transformCache: Map<string, boolean>,
108
- pad: number
116
+ walk: HitWalk
109
117
  ): SceneNode | null {
110
118
  if (child.type === 'GROUP') {
111
119
  // A group fits its layers, so a padded click on one at its edge falls just outside it.
112
- if (!containsPoint(px, py, child, graph, transformCache, pad)) return null
120
+ if (!containsPoint(px, py, child, graph, walk.transformCache, walk.pad)) return null
113
121
  // A group has no area of its own, as in Figma: between its layers the click falls through to
114
122
  // whatever lies under the group.
115
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
116
- return childHit ? (deep ? childHit : child) : null
123
+ const childHit = hitTestChildren(graph, px, py, child.id, walk)
124
+ return childHit ? (walk.deep ? childHit : child) : null
117
125
  }
118
126
 
119
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
127
+ const childHit = hitTestChildren(graph, px, py, child.id, walk)
120
128
  if (childHit) {
121
129
  if (child.locked) return child
122
130
  return childHit
123
131
  }
124
132
 
125
133
  if (
126
- containsPoint(px, py, child, graph, transformCache) &&
127
- (hasVisibleFillOrStroke(child) || ownsItsEmptyArea(graph, child))
134
+ containsPoint(px, py, child, graph, walk.transformCache) &&
135
+ takesEmptyArea(graph, child, walk)
128
136
  )
129
137
  return child
130
138
  return null
131
139
  }
132
140
 
133
- /**
134
- * The topmost layer under the point among a container's children. `pad`, in canvas units, grows
135
- * each leaf layer's box, as Figma takes a click a few screen pixels outside a shape.
136
- */
141
+ /** The topmost layer under the point among a container's children. */
137
142
  function hitTestChildren(
138
143
  graph: SceneGraph,
139
144
  px: number,
140
145
  py: number,
141
146
  parentId: string,
142
- deep = false,
143
- transformCache = new Map<string, boolean>(),
144
- pad = 0
147
+ walk: HitWalk
145
148
  ): SceneNode | null {
146
149
  const parent = graph.nodes.get(parentId)
147
150
  if (!parent) return null
151
+ const { transformCache, pad } = walk
148
152
 
149
153
  if (parent.clipsContent) {
150
154
  if (!containsPoint(px, py, parent, graph, transformCache)) return null
151
155
  }
152
156
 
153
157
  for (let i = parent.childIds.length - 1; i >= 0; i--) {
154
- const childId = parent.childIds[i]
155
- const child = graph.nodes.get(childId)
158
+ const child = graph.nodes.get(parent.childIds[i])
156
159
  if (!child || child.internalOnly || !child.visible) continue
157
160
  if (CONTAINER_TYPES.has(child.type)) {
158
- if (OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {
159
- const hit = hitTestOpaqueContainer(graph, px, py, child, childId, deep, transformCache, pad)
160
- if (hit) return hit
161
+ if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {
162
+ // A plain click takes an instance or component anywhere in its box, with a fill or
163
+ // without, as in Figma.
164
+ if (containsPoint(px, py, child, graph, transformCache)) return child
161
165
  continue
162
166
  }
163
-
164
- const hit = hitTestTransparentContainer(
165
- graph,
166
- px,
167
- py,
168
- child,
169
- childId,
170
- deep,
171
- transformCache,
172
- pad
173
- )
167
+ const hit = hitTestTransparentContainer(graph, px, py, child, walk)
174
168
  if (hit) return hit
175
169
  continue
176
170
  }
@@ -179,12 +173,30 @@ function hitTestChildren(
179
173
  if (hitsConnectorLine(graph, child, px, py, pad)) return child
180
174
  continue
181
175
  }
182
- if (containsPoint(px, py, child, graph, transformCache, pad)) return child
176
+ if (hitsLeaf(graph, px, py, child, transformCache, pad)) return child
183
177
  }
184
178
 
185
179
  return null
186
180
  }
187
181
 
182
+ /**
183
+ * Whether a click lands on a leaf layer: on what its paints draw, as Figma tests shapes (see
184
+ * `hitsShape`), or on its box for layers without an outline to test, such as text.
185
+ */
186
+ function hitsLeaf(
187
+ graph: SceneGraph,
188
+ px: number,
189
+ py: number,
190
+ node: SceneNode,
191
+ transformCache: Map<string, boolean>,
192
+ pad: number
193
+ ): boolean {
194
+ if (!containsPoint(px, py, node, graph, transformCache, pad + strokeReach(node))) return false
195
+ return (
196
+ hitsShape(graph, node, px, py, pad) ?? containsPoint(px, py, node, graph, transformCache, pad)
197
+ )
198
+ }
199
+
188
200
  export function hitTest(
189
201
  graph: SceneGraph,
190
202
  px: number,
@@ -192,7 +204,7 @@ export function hitTest(
192
204
  scopeId?: string
193
205
  ): SceneNode | null {
194
206
  const scope = scopeId ?? graph.rootId
195
- return hitTestChildren(graph, px, py, scope, false)
207
+ return hitTestChildren(graph, px, py, scope, walkOf(false))
196
208
  }
197
209
 
198
210
  export function hitTestDeep(
@@ -203,7 +215,7 @@ export function hitTestDeep(
203
215
  pad = 0
204
216
  ): SceneNode | null {
205
217
  const scope = scopeId ?? graph.rootId
206
- return hitTestChildren(graph, px, py, scope, true, new Map(), pad)
218
+ return hitTestChildren(graph, px, py, scope, walkOf(true, pad))
207
219
  }
208
220
 
209
221
  /**
@@ -308,7 +320,8 @@ export function hitTestSelectable(
308
320
  options: SelectableHitOptions = {}
309
321
  ): SceneNode | null {
310
322
  const { pad = 0, framesOpen = true, enteredId = null } = options
311
- const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad)
323
+ // 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))
312
325
  if (!deepest) {
313
326
  const scope = graph.nodes.get(scopeId)
314
327
  return scope ? frameChildAt(graph, scope, px, py, framesOpen) : null
@@ -351,7 +364,7 @@ export function hitTestOpenContainer(
351
364
  py: number,
352
365
  scopeId: string
353
366
  ): SceneNode | null {
354
- const deepest = hitTestChildren(graph, px, py, scopeId, true)
367
+ const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true))
355
368
  for (let node: SceneNode | undefined = deepest ?? undefined; node && node.id !== scopeId;) {
356
369
  if (!opensByItself(graph, node) || ownsItsEmptyArea(graph, node)) return null
357
370
  node = node.parentId ? graph.nodes.get(node.parentId) : undefined
@@ -43,6 +43,14 @@ export const INSTANCE_FOLLOWED_FIELDS = [
43
43
  'counterAxisAlignContent',
44
44
  'isMask',
45
45
  'maskType',
46
+ 'maskIsOutline',
47
+ 'booleanOperation',
48
+ 'isExposedInstance',
49
+ 'connectorStart',
50
+ 'connectorEnd',
51
+ 'connectorLineType',
52
+ 'connectorStartCap',
53
+ 'connectorEndCap',
46
54
  'arcData',
47
55
  'pointCount',
48
56
  'starInnerRadius',
@@ -1,17 +1,23 @@
1
1
  import type { NodeCloneMode } from '../copy'
2
2
  import type { SceneGraph } from '../graph'
3
- import { detachOwnedSlotContent, restoreOwnedSlotContent } from '../slots/frames'
3
+ import {
4
+ detachOwnedSlotContent,
5
+ restoreOwnedSlotContent,
6
+ type ParkedSlotContent
7
+ } from '../slots/frames'
4
8
  import type { SceneNode } from '../types'
5
9
  import { keepOwnContentSize } from './content-size'
6
10
  import { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from './copies'
7
11
  import { canCreateInstance } from './cycles'
8
12
  import { INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_PROPS } from './fields'
13
+ import { findInstanceAncestor, instanceMainComponent } from './main-component'
9
14
  import {
10
15
  clearInstanceOverrides,
11
16
  getInstanceOverride,
12
17
  hasInstanceOverride as hasNodeInstanceOverride,
13
18
  setInstanceOverride
14
19
  } from './overrides'
20
+ import { followComponentLayers } from './swap'
15
21
  import {
16
22
  bindingProtection,
17
23
  cloneChildrenWithMapping,
@@ -25,7 +31,7 @@ import {
25
31
  } from './sync'
26
32
 
27
33
  export { canCreateInstance, createsComponentCycle, cycleSafeParent } from './cycles'
28
- export { instanceMainComponent } from './main-component'
34
+ export { findInstanceAncestor, instanceMainComponent } from './main-component'
29
35
  export {
30
36
  INSTANCE_FOLLOWED_FIELDS,
31
37
  INSTANCE_OVERRIDE_FIELDS,
@@ -111,6 +117,19 @@ export interface SwapInstanceOptions {
111
117
  keepName?: boolean
112
118
  }
113
119
 
120
+ function namedAfter(
121
+ graph: SceneGraph,
122
+ instance: SceneNode,
123
+ component: SceneNode
124
+ ): SceneNode | undefined {
125
+ const main = instanceMainComponent(graph, instance)
126
+ const set = main?.parentId ? graph.nodes.get(main.parentId) : undefined
127
+ if (set?.type === 'COMPONENT_SET' && component.parentId === set.id) {
128
+ return main
129
+ }
130
+ return instance.componentId ? graph.nodes.get(instance.componentId) : undefined
131
+ }
132
+
114
133
  export function swapInstanceComponent(
115
134
  graph: SceneGraph,
116
135
  instanceId: string,
@@ -122,26 +141,52 @@ export function swapInstanceComponent(
122
141
  if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return
123
142
  if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return
124
143
 
125
- const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined
144
+ const previousComponent = namedAfter(graph, instance, component)
126
145
  recordNestedSwap(graph, instance, componentId)
127
- const updates: Partial<SceneNode> = { componentId }
128
146
  const source = sourceInTargetCoordinates(component, instance.componentScale)
129
- for (const key of INSTANCE_SYNC_PROPS) {
130
- if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key)) continue
131
- copyProp(updates, source, key)
147
+ const updates: Partial<SceneNode> = {
148
+ componentId,
149
+ ...ownSyncedProps(graph, instance, source).updates
132
150
  }
133
151
 
134
152
  if (!keepName && (!previousComponent || instance.name === previousComponent.name))
135
153
  updates.name = component.name
136
154
 
137
- const childIds = Array.from(instance.childIds)
138
155
  const slotContent = detachOwnedSlotContent(graph, instance)
139
- for (const childId of childIds) graph.deleteNode(childId)
140
156
  graph.updateNode(instanceId, updates)
141
- cloneChildrenWithMapping(graph, componentId, instanceId)
157
+ followComponentLayers(graph, instance, component, parkedContent(slotContent))
142
158
  restoreOwnedSlotContent(graph, instance, slotContent)
143
159
  }
144
160
 
161
+ const NOTHING_PARKED: ReadonlySet<string> = new Set()
162
+
163
+ function parkedContent(parked: ParkedSlotContent): ReadonlySet<string> {
164
+ if (parked.slots.length === 0) {
165
+ return NOTHING_PARKED
166
+ }
167
+ return new Set(parked.slots.flatMap((slot) => slot.content))
168
+ }
169
+
170
+ /** What an instance takes from its component, and which fields it keeps as its own. */
171
+ function ownSyncedProps(
172
+ graph: SceneGraph,
173
+ instance: SceneNode,
174
+ source: SceneNode
175
+ ): { updates: Partial<SceneNode>; kept: (field: string) => boolean } {
176
+ const enclosing = enclosingInstanceOverrideFields(graph, instance)
177
+ enclosing.push(new Set(instance.instanceOverrides.self.keys()))
178
+ const protectedField = bindingProtection(enclosing)
179
+ const updates: Partial<SceneNode> = {}
180
+ syncBindingFields(instance, source, updates, protectedField)
181
+ const kept = (key: string) => isProtectedSyncField(instance, key, protectedField)
182
+ for (const key of INSTANCE_SYNC_PROPS) {
183
+ if (key !== 'boundVariables' && !kept(key)) {
184
+ copyProp(updates, source, key)
185
+ }
186
+ }
187
+ return { updates, kept }
188
+ }
189
+
145
190
  const syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()
146
191
 
147
192
  export function syncInstances(graph: SceneGraph, componentId: string): void {
@@ -182,20 +227,11 @@ function syncInstancesOf(
182
227
  try {
183
228
  groupCopyRemovals(graph, (removals) => {
184
229
  for (const instance of instances) {
185
- const enclosing = enclosingInstanceOverrideFields(graph, instance)
186
- enclosing.push(new Set(instance.instanceOverrides.self.keys()))
187
- const protectedField = bindingProtection(enclosing)
188
230
  const source = sourceInTargetCoordinates(component, instance.componentScale)
189
- const updates: Partial<SceneNode> = {}
190
- syncBindingFields(instance, source, updates, protectedField)
191
- for (const key of INSTANCE_SYNC_PROPS) {
192
- if (key === 'boundVariables') continue
193
- if (isProtectedSyncField(instance, key, protectedField)) continue
194
- copyProp(updates, source, key)
195
- }
231
+ const { updates, kept } = ownSyncedProps(graph, instance, source)
196
232
  // An instance that hugs its layers sizes to what it shows, not to the component.
197
233
  keepOwnContentSize(graph, updates, instance, source)
198
- updateSyncedProps(graph, instance, updates)
234
+ updateSyncedProps(graph, instance, updates, kept)
199
235
  const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)
200
236
  syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)
201
237
  removeLeftoverCopies(graph, context, removals)
@@ -234,16 +270,6 @@ export function getInstances(graph: SceneGraph, componentId: string): SceneNode[
234
270
  return instances
235
271
  }
236
272
 
237
- /** Nearest INSTANCE at or above `nodeId` — self, parent, grandparent, etc. */
238
- export function findInstanceAncestor(graph: SceneGraph, nodeId: string): SceneNode | undefined {
239
- let current = graph.nodes.get(nodeId)
240
- while (current) {
241
- if (current.type === 'INSTANCE') return current
242
- current = current.parentId ? graph.nodes.get(current.parentId) : undefined
243
- }
244
- return undefined
245
- }
246
-
247
273
  /**
248
274
  * True when a node field is protected from instance synchronization.
249
275
  */
@@ -267,6 +293,7 @@ export function recordInstanceOverride(
267
293
 
268
294
  if (relevant.length === 0) return
269
295
 
296
+ graph.willChangeNode(instance)
270
297
  for (const field of relevant)
271
298
  setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
272
299
  graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
@@ -0,0 +1,280 @@
1
+ // Overrides a variant switch keeps for the layers it removes, to give back to the next copies.
2
+ import { omit } from 'es-toolkit/object'
3
+ import { isEqual } from 'es-toolkit/predicate'
4
+
5
+ import {
6
+ overriddenAssignmentId,
7
+ reapplyComponentPropertyAssignments
8
+ } from '../components/properties'
9
+ import type { SceneGraph } from '../graph'
10
+ import type { SceneNode } from '../types'
11
+ import { instanceMainComponent } from './main-component'
12
+ import { overriddenBindingField } from './overrides'
13
+
14
+ /** Where a switch runs: the switched instance and the instances enclosing the layers it changes. */
15
+ export interface OverrideScope {
16
+ graph: SceneGraph
17
+ instance: SceneNode
18
+ owners: readonly SceneNode[]
19
+ /** Reports an owner before its override maps are written into. */
20
+ willChange(owner: SceneNode): void
21
+ }
22
+
23
+ /**
24
+ * An instance that holds overrides on a layer: one enclosing the switch, by ID, or one inside
25
+ * the removed copy, by its path, since a new copy of it gets a new ID.
26
+ */
27
+ type OwnerRef = { id: string } | { path: string }
28
+
29
+ /** What one owner overrides on a layer, with the values the layer showed. */
30
+ interface KeptOverrides {
31
+ owner: OwnerRef
32
+ /** The owner's own fields, for a nested instance's overrides on itself. */
33
+ self: boolean
34
+ fields: Map<string, unknown>
35
+ values: Partial<SceneNode>
36
+ /** Bindings the overrides claim, with their unit scales; an absent variable claims none. */
37
+ bindings: Record<string, { variableId: string | undefined; scale: number | undefined }>
38
+ /** Set when the overrides claim every binding, as removing a variable records. */
39
+ allBindings?: { boundVariables: SceneNode['boundVariables']; scales: Scales }
40
+ /** The component a nested instance was switched to, which its new copy is switched to again. */
41
+ swappedTo?: string
42
+ /** Property values the overrides claim on a nested instance. */
43
+ assignments: Record<string, string>
44
+ }
45
+
46
+ type Scales = SceneNode['variableBindingScales']
47
+
48
+ /** Override fields that link a copy to its layer, which a new copy gets from its own layer. */
49
+ const LINK_FIELDS: ReadonlySet<string> = new Set(['sourceComponentId', 'componentId'])
50
+
51
+ /**
52
+ * Overrides on layers a switch removed, by switched instance and then by the layer's path from
53
+ * it: each step's name and its order among the same-named layers beside it, the way a switch
54
+ * pairs layers. Figma brings them back when the instance switches to a variant that draws the
55
+ * layer again, though its saved records keep none of them while the layer is gone (desktop
56
+ * 126), so they live with the open document only.
57
+ */
58
+ const keptByGraph = new WeakMap<SceneGraph, Map<string, Map<string, KeptOverrides[]>>>()
59
+
60
+ function keptFor(scope: OverrideScope, create: true): Map<string, KeptOverrides[]>
61
+ function keptFor(scope: OverrideScope, create: false): Map<string, KeptOverrides[]> | undefined
62
+ function keptFor(scope: OverrideScope, create: boolean) {
63
+ let byInstance = keptByGraph.get(scope.graph)
64
+ if (!byInstance && create) {
65
+ byInstance = new Map()
66
+ keptByGraph.set(scope.graph, byInstance)
67
+ }
68
+ let byPath = byInstance?.get(scope.instance.id)
69
+ if (!byPath && byInstance && create) {
70
+ byPath = new Map()
71
+ byInstance.set(scope.instance.id, byPath)
72
+ }
73
+ return byPath
74
+ }
75
+
76
+ /** A layer's path from the switched instance, by names and their order among namesakes. */
77
+ function layerPath(scope: OverrideScope, node: SceneNode): string | undefined {
78
+ const steps: string[] = []
79
+ let current = node
80
+ while (current.id !== scope.instance.id) {
81
+ const parent: SceneNode | undefined = current.parentId
82
+ ? scope.graph.getNode(current.parentId)
83
+ : undefined
84
+ if (!parent) return undefined
85
+ let ordinal = 0
86
+ for (const id of parent.childIds) {
87
+ if (id === current.id) break
88
+ if (scope.graph.getNode(id)?.name === current.name) ordinal++
89
+ }
90
+ steps.push(`${current.name}\u0000${ordinal}`)
91
+ current = parent
92
+ }
93
+ return steps.reverse().join('\u0001')
94
+ }
95
+
96
+ function snapshot(
97
+ graph: SceneGraph,
98
+ node: SceneNode,
99
+ owner: OwnerRef,
100
+ self: boolean,
101
+ fields: ReadonlyMap<string, unknown>
102
+ ): KeptOverrides | undefined {
103
+ const kept = new Map([...fields].filter(([field]) => !LINK_FIELDS.has(field)))
104
+ // A swap is kept as the component it shows; the new copy records it again when switched.
105
+ const swappedTo =
106
+ fields.has('componentId') && node.type === 'INSTANCE'
107
+ ? instanceMainComponent(graph, node)?.id
108
+ : undefined
109
+ if (kept.size === 0 && !swappedTo) return undefined
110
+ const values: Partial<SceneNode> = {}
111
+ const bindings: KeptOverrides['bindings'] = {}
112
+ const assignments: Record<string, string> = {}
113
+ for (const field of kept.keys()) {
114
+ const binding = overriddenBindingField(field)
115
+ const assigned = overriddenAssignmentId(field)
116
+ if (assigned !== undefined) {
117
+ if (Object.hasOwn(node.componentPropertyAssignments, assigned))
118
+ assignments[assigned] = node.componentPropertyAssignments[assigned]
119
+ } else if (binding !== null) {
120
+ bindings[binding] = {
121
+ variableId: node.boundVariables[binding],
122
+ scale: node.variableBindingScales[binding]
123
+ }
124
+ } else if (field in node && field !== 'boundVariables') {
125
+ Object.assign(values, { [field]: structuredClone(node[field as keyof SceneNode]) })
126
+ }
127
+ }
128
+ const allBindings = kept.has('boundVariables')
129
+ ? {
130
+ boundVariables: { ...node.boundVariables },
131
+ scales: { ...node.variableBindingScales }
132
+ }
133
+ : undefined
134
+ return { owner, self, fields: kept, values, bindings, allBindings, swappedTo, assignments }
135
+ }
136
+
137
+ /** Takes the overrides on a layer off its owners, outer ones and those inside the removed copy. */
138
+ function takeOverrides(
139
+ scope: OverrideScope,
140
+ node: SceneNode,
141
+ inner: readonly SceneNode[]
142
+ ): KeptOverrides[] {
143
+ const taken: KeptOverrides[] = []
144
+ for (const owner of scope.owners) {
145
+ const fields = owner.instanceOverrides.descendants.get(node.id)
146
+ if (!fields) continue
147
+ scope.willChange(owner)
148
+ owner.instanceOverrides.descendants.delete(node.id)
149
+ const kept = snapshot(scope.graph, node, { id: owner.id }, false, fields)
150
+ if (kept) taken.push(kept)
151
+ }
152
+ for (const owner of inner) {
153
+ const fields = owner.instanceOverrides.descendants.get(node.id)
154
+ const path = layerPath(scope, owner)
155
+ const kept = fields && path ? snapshot(scope.graph, node, { path }, false, fields) : undefined
156
+ if (kept) taken.push(kept)
157
+ }
158
+ const ownPath = node.type === 'INSTANCE' ? layerPath(scope, node) : undefined
159
+ const own = ownPath
160
+ ? snapshot(scope.graph, node, { path: ownPath }, true, node.instanceOverrides.self)
161
+ : undefined
162
+ if (own) taken.push(own)
163
+ return taken
164
+ }
165
+
166
+ /**
167
+ * Keeps what is overridden on a copy and its layers before a switch removes it. A layer
168
+ * removed with nothing overridden clears what an earlier removal kept for its path, so a value
169
+ * the user reset does not come back.
170
+ */
171
+ export function keepOverrides(
172
+ scope: OverrideScope,
173
+ copy: SceneNode,
174
+ inner: readonly SceneNode[] = []
175
+ ): void {
176
+ const path = layerPath(scope, copy)
177
+ const taken = takeOverrides(scope, copy, inner)
178
+ if (path && taken.length > 0) keptFor(scope, true).set(path, taken)
179
+ else if (path) keptFor(scope, false)?.delete(path)
180
+ const owners = copy.type === 'INSTANCE' ? [...inner, copy] : inner
181
+ for (const child of scope.graph.getChildren(copy.id)) keepOverrides(scope, child, owners)
182
+ }
183
+
184
+ function ownerOf(scope: OverrideScope, ref: OwnerRef): SceneNode | undefined {
185
+ if ('id' in ref) return scope.owners.find((owner) => owner.id === ref.id)
186
+ let current: SceneNode | undefined = scope.instance
187
+ for (const step of ref.path.split('\u0001')) {
188
+ const [name, ordinal] = step.split('\u0000')
189
+ current = current
190
+ ? scope.graph.getChildren(current.id).filter((child) => child.name === name)[Number(ordinal)]
191
+ : undefined
192
+ }
193
+ return current?.type === 'INSTANCE' ? current : undefined
194
+ }
195
+
196
+ /**
197
+ * Switches a nested instance switched to another variant again first, so what is kept for it
198
+ * and its layers lands on what it then shows. Returns the node as it then stands.
199
+ */
200
+ function switchAsKept(scope: OverrideScope, copy: SceneNode, kept: readonly KeptOverrides[]) {
201
+ const swappedTo = kept.find((entry) => entry.swappedTo)?.swappedTo
202
+ if (
203
+ swappedTo &&
204
+ copy.type === 'INSTANCE' &&
205
+ scope.graph.getNode(swappedTo) &&
206
+ instanceMainComponent(scope.graph, copy)?.id !== swappedTo
207
+ ) {
208
+ scope.graph.swapInstanceComponent(copy.id, swappedTo)
209
+ }
210
+ return scope.graph.getNode(copy.id) ?? copy
211
+ }
212
+
213
+ /** The bindings and unit scales a layer shows with the kept bindings applied over its own. */
214
+ function keptBindings(node: SceneNode, kept: readonly KeptOverrides[]) {
215
+ let boundVariables: Record<string, string> = { ...node.boundVariables }
216
+ let scales: Scales = { ...node.variableBindingScales }
217
+ for (const { bindings, allBindings } of kept) {
218
+ if (allBindings) {
219
+ boundVariables = { ...allBindings.boundVariables }
220
+ scales = { ...allBindings.scales }
221
+ }
222
+ for (const [field, { variableId, scale }] of Object.entries(bindings)) {
223
+ boundVariables = variableId
224
+ ? { ...boundVariables, [field]: variableId }
225
+ : omit(boundVariables, [field])
226
+ scales = scale !== undefined ? { ...scales, [field]: scale } : omit(scales, [field])
227
+ }
228
+ }
229
+ return { boundVariables, scales }
230
+ }
231
+
232
+ function giveOverrides(scope: OverrideScope, copy: SceneNode, saved: readonly KeptOverrides[]) {
233
+ // What an owner no longer standing around the copy overrode is not given back at all.
234
+ const resolved = saved.flatMap((entry) => {
235
+ const owner = ownerOf(scope, entry.owner)
236
+ return owner ? [{ entry, owner }] : []
237
+ })
238
+ const kept = resolved.map(({ entry }) => entry)
239
+ const node = switchAsKept(scope, copy, kept)
240
+ const values: Partial<SceneNode> = {}
241
+ for (const { entry, owner } of resolved) {
242
+ const { self, fields, values: shown } = entry
243
+ scope.willChange(owner)
244
+ const own = self
245
+ ? owner.instanceOverrides.self
246
+ : owner.instanceOverrides.descendants.get(node.id)
247
+ const merged = new Map([...(own ?? []), ...fields])
248
+ if (self) owner.instanceOverrides.self = merged
249
+ else owner.instanceOverrides.descendants.set(node.id, merged)
250
+ Object.assign(values, structuredClone(shown))
251
+ }
252
+ const { boundVariables, scales } = keptBindings(node, kept)
253
+ if (!isEqual(boundVariables, node.boundVariables)) values.boundVariables = boundVariables
254
+ if (!isEqual(scales, node.variableBindingScales)) values.variableBindingScales = scales
255
+ const assignments: Record<string, string> = Object.assign(
256
+ {},
257
+ ...kept.map((entry) => entry.assignments)
258
+ )
259
+ const assigns = Object.keys(assignments).length > 0
260
+ if (assigns) {
261
+ values.componentPropertyAssignments = { ...node.componentPropertyAssignments, ...assignments }
262
+ }
263
+ if (Object.keys(values).length > 0) scope.graph.updateNode(node.id, values)
264
+ // The values a nested instance is given show in its layers, as a matched copy's do.
265
+ if (assigns) reapplyComponentPropertyAssignments(scope.graph, node.id)
266
+ }
267
+
268
+ /** Gives a copy just placed, and its layers, what an earlier switch kept for their paths. */
269
+ export function restoreOverrides(scope: OverrideScope, copy: SceneNode): void {
270
+ const kept = keptFor(scope, false)
271
+ if (!kept?.size) return
272
+ const restore = (node: SceneNode) => {
273
+ const path = layerPath(scope, node)
274
+ const found = path ? kept.get(path) : undefined
275
+ // Kept, not taken: undoing this switch and switching again gives them back once more.
276
+ if (found) giveOverrides(scope, node, found)
277
+ for (const child of scope.graph.getChildren(node.id)) restore(child)
278
+ }
279
+ restore(copy)
280
+ }