@open-pencil/scene-graph 0.15.0 → 0.16.0-beta.1

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 (232) 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 +596 -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} +573 -521
  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 +2021 -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/fields/text.js +36 -0
  34. package/dist/chunks/fields/text.js.map +1 -0
  35. package/dist/chunks/group-bounds.js +104 -0
  36. package/dist/chunks/group-bounds.js.map +1 -0
  37. package/dist/chunks/icons/glyph.js +147 -0
  38. package/dist/chunks/icons/glyph.js.map +1 -0
  39. package/dist/chunks/index.js +1712 -662
  40. package/dist/chunks/index.js.map +1 -1
  41. package/dist/color.d.ts +72 -0
  42. package/dist/color.d.ts.map +1 -0
  43. package/dist/color.js +3 -0
  44. package/dist/constants.d.ts +2 -2
  45. package/dist/constants.js +2 -2
  46. package/dist/constants2.d.ts +3 -1
  47. package/dist/constants2.d.ts.map +1 -1
  48. package/dist/coordinate.d.ts +2 -448
  49. package/dist/coordinate.js +2 -2
  50. package/dist/copy.d.ts +1 -1
  51. package/dist/copy.js +1 -1
  52. package/dist/css.d.ts +39 -0
  53. package/dist/css.d.ts.map +1 -0
  54. package/dist/css.js +3 -0
  55. package/dist/geometry.d.ts +1 -1
  56. package/dist/geometry.js +1 -1
  57. package/dist/gradient.d.ts +51 -0
  58. package/dist/gradient.d.ts.map +1 -0
  59. package/dist/gradient.js +132 -0
  60. package/dist/gradient.js.map +1 -0
  61. package/dist/guides.d.ts +2 -2
  62. package/dist/guides.js +39 -0
  63. package/dist/guides.js.map +1 -0
  64. package/dist/hit-test.d.ts +2 -9
  65. package/dist/hit-test.js +154 -18
  66. package/dist/hit-test.js.map +1 -1
  67. package/dist/index.d.ts +4 -8
  68. package/dist/index.js +20 -5
  69. package/dist/instances.d.ts +2 -2
  70. package/dist/instances.js +2 -2
  71. package/dist/layout.d.ts +2 -0
  72. package/dist/layout.js +4 -0
  73. package/dist/node-defaults.d.ts +2 -8
  74. package/dist/node-defaults.js +2 -2
  75. package/dist/order-keys.d.ts +39 -0
  76. package/dist/order-keys.d.ts.map +1 -0
  77. package/dist/order-keys.js +136 -0
  78. package/dist/order-keys.js.map +1 -0
  79. package/dist/parse-path.d.ts +7 -1
  80. package/dist/parse-path.d.ts.map +1 -1
  81. package/dist/parse-path.js +6 -2
  82. package/dist/parse-path.js.map +1 -1
  83. package/dist/polygon.d.ts +53 -0
  84. package/dist/polygon.d.ts.map +1 -0
  85. package/dist/polygon.js +205 -0
  86. package/dist/polygon.js.map +1 -0
  87. package/dist/preview.d.ts +1 -1
  88. package/dist/random.d.ts +7 -0
  89. package/dist/random.d.ts.map +1 -0
  90. package/dist/random.js +2 -0
  91. package/dist/resize.d.ts +11 -2
  92. package/dist/resize.d.ts.map +1 -1
  93. package/dist/resize.js +2 -184
  94. package/dist/snap.d.ts +1 -1
  95. package/dist/text-direction.d.ts +13 -0
  96. package/dist/text-direction.d.ts.map +1 -0
  97. package/dist/text-direction.js +31 -0
  98. package/dist/text-direction.js.map +1 -0
  99. package/dist/text-picture.d.ts +1 -1
  100. package/dist/text-picture.d.ts.map +1 -1
  101. package/dist/text.d.ts +2 -0
  102. package/dist/text.js +3 -0
  103. package/dist/types.d.ts +2063 -13
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js +2 -1
  106. package/dist/types2.d.ts +2 -2
  107. package/dist/undo.d.ts +2 -2
  108. package/dist/undo.js +2 -2
  109. package/dist/undo2.d.ts +29 -1
  110. package/dist/undo2.d.ts.map +1 -1
  111. package/dist/variables.d.ts +2 -29
  112. package/dist/variables.js +2 -2
  113. package/dist/variant-properties.d.ts +9 -1
  114. package/dist/variant-properties.d.ts.map +1 -1
  115. package/dist/variant-properties.js +36 -1
  116. package/dist/variant-properties.js.map +1 -1
  117. package/dist/vector-network.d.ts +1 -1
  118. package/dist/vector-network.js +1 -1
  119. package/package.json +60 -9
  120. package/src/behaviours/kinds.ts +185 -0
  121. package/src/behaviours/layers.ts +51 -0
  122. package/src/behaviours/model.ts +192 -0
  123. package/src/behaviours/schema.ts +58 -0
  124. package/src/behaviours/spec.ts +223 -0
  125. package/src/buffered-events.ts +64 -0
  126. package/src/color/contrast.ts +31 -0
  127. package/src/color/index.ts +88 -0
  128. package/src/color/management.ts +210 -0
  129. package/src/color/normalize.ts +7 -0
  130. package/src/color/okhcl.ts +201 -0
  131. package/src/comments/document.ts +51 -0
  132. package/src/comments/list.ts +52 -0
  133. package/src/comments/merge.ts +63 -0
  134. package/src/comments/threads.ts +156 -0
  135. package/src/components/exposure.ts +61 -0
  136. package/src/components/properties.ts +18 -15
  137. package/src/components/variants.ts +53 -0
  138. package/src/constants.ts +2 -0
  139. package/src/coordinate.ts +100 -43
  140. package/src/copy.ts +13 -5
  141. package/src/css/grid.ts +70 -0
  142. package/src/css/index.ts +9 -0
  143. package/src/css/layout.ts +53 -0
  144. package/src/css/shadows.ts +68 -0
  145. package/src/css/values.ts +42 -0
  146. package/src/export-format.ts +12 -0
  147. package/src/fields/geometry.ts +11 -0
  148. package/src/fields/text.ts +35 -0
  149. package/src/gradient.ts +166 -0
  150. package/src/group-bounds.ts +131 -0
  151. package/src/guides.ts +39 -0
  152. package/src/hit-test.ts +219 -25
  153. package/src/icons/glyph.ts +128 -0
  154. package/src/icons/model.ts +54 -0
  155. package/src/icons/schema.ts +18 -0
  156. package/src/index.ts +344 -56
  157. package/src/instance-overrides.ts +27 -0
  158. package/src/instances/copies.ts +239 -0
  159. package/src/instances/cycles.ts +73 -0
  160. package/src/instances/fields.ts +143 -0
  161. package/src/instances/main-component.ts +19 -0
  162. package/src/instances/placement.ts +29 -0
  163. package/src/instances/source-walk.ts +41 -0
  164. package/src/instances/sync.ts +599 -0
  165. package/src/instances.ts +122 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +1 -1
  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/slots/authoring.ts +101 -0
  187. package/src/slots/content.ts +124 -0
  188. package/src/slots/frames.ts +160 -0
  189. package/src/slots/limits.ts +49 -0
  190. package/src/text/direction.ts +55 -0
  191. package/src/text/index.ts +2 -0
  192. package/src/text/lists.ts +138 -0
  193. package/src/text/paragraphs.ts +241 -0
  194. package/src/{text-picture.ts → text/picture.ts} +21 -29
  195. package/src/transfer/apply.ts +84 -0
  196. package/src/transfer/history.ts +49 -0
  197. package/src/transfer/identity.ts +16 -0
  198. package/src/transfer/index.ts +6 -0
  199. package/src/transfer/nodes.ts +108 -0
  200. package/src/transfer/plan.ts +107 -0
  201. package/src/transfer/references.ts +9 -0
  202. package/src/transfer/remove.ts +39 -0
  203. package/src/transfer/validation.ts +54 -0
  204. package/src/transfer/variables.ts +82 -0
  205. package/src/types.ts +221 -11
  206. package/src/undo.ts +54 -2
  207. package/src/variables/bindings.ts +186 -0
  208. package/src/variables/fields.ts +43 -0
  209. package/src/variables/token.ts +14 -0
  210. package/src/variables/units.ts +15 -0
  211. package/src/variables.ts +118 -69
  212. package/src/variant-properties.ts +50 -0
  213. package/dist/chunks/components/properties.js.map +0 -1
  214. package/dist/chunks/export-scale.js +0 -19
  215. package/dist/chunks/export-scale.js.map +0 -1
  216. package/dist/coordinate.d.ts.map +0 -1
  217. package/dist/coordinate2.d.ts +0 -2
  218. package/dist/guides2.d.ts +0 -11
  219. package/dist/guides2.d.ts.map +0 -1
  220. package/dist/hit-test.d.ts.map +0 -1
  221. package/dist/layout-guides.d.ts +0 -2
  222. package/dist/layout-guides.js +0 -2
  223. package/dist/layout-guides2.d.ts +0 -16
  224. package/dist/layout-guides2.d.ts.map +0 -1
  225. package/dist/node-defaults.d.ts.map +0 -1
  226. package/dist/preview2.d.ts +0 -12
  227. package/dist/preview2.d.ts.map +0 -1
  228. package/dist/resize.js.map +0 -1
  229. package/dist/variables.d.ts.map +0 -1
  230. package/dist/vector-network2.d.ts +0 -32
  231. package/dist/vector-network2.d.ts.map +0 -1
  232. package/src/instance-overrides.test.ts +0 -67
package/src/instances.ts CHANGED
@@ -1,311 +1,39 @@
1
1
  import type { SceneGraph, SceneNode } from './'
2
- import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from './copy'
3
2
  import type { NodeCloneMode } from './copy'
4
3
  import {
5
4
  clearInstanceOverrides,
6
5
  getInstanceOverride,
7
6
  hasInstanceOverride as hasNodeInstanceOverride,
8
- setInstanceOverride,
9
- type InstanceOverrideState
7
+ setInstanceOverride
10
8
  } from './instance-overrides'
9
+ import {
10
+ createInstanceSyncContext,
11
+ groupCopyRemovals,
12
+ removeLeftoverCopies
13
+ } from './instances/copies'
14
+ import { canCreateInstance } from './instances/cycles'
15
+ import { INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_PROPS } from './instances/fields'
16
+ import {
17
+ bindingProtection,
18
+ cloneChildrenWithMapping,
19
+ copyProp,
20
+ enclosingInstanceOverrideFields,
21
+ isProtectedSyncField,
22
+ sourceInTargetCoordinates,
23
+ syncBindingFields,
24
+ syncChildren,
25
+ updateSyncedProps
26
+ } from './instances/sync'
27
+ import { detachOwnedSlotContent, restoreOwnedSlotContent } from './slots/frames'
11
28
 
12
29
  export type { NodeCloneMode } from './copy'
13
-
14
- export const INSTANCE_SYNC_TEXT_PROPS = [
15
- 'name',
16
- 'text',
17
- 'fontSize',
18
- 'fontWeight',
19
- 'fontFamily',
20
- 'textDirection'
21
- ] as const
22
-
23
- export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [
24
- 'width',
25
- 'height',
26
- 'minWidth',
27
- 'maxWidth',
28
- 'minHeight',
29
- 'maxHeight',
30
- 'fills',
31
- 'strokes',
32
- 'effects',
33
- 'opacity',
34
- 'cornerRadius',
35
- 'topLeftRadius',
36
- 'topRightRadius',
37
- 'bottomRightRadius',
38
- 'bottomLeftRadius',
39
- 'independentCorners',
40
- 'layoutMode',
41
- 'layoutDirection',
42
- 'layoutWrap',
43
- 'primaryAxisAlign',
44
- 'counterAxisAlign',
45
- 'primaryAxisSizing',
46
- 'counterAxisSizing',
47
- 'itemSpacing',
48
- 'counterAxisSpacing',
49
- 'paddingTop',
50
- 'paddingRight',
51
- 'paddingBottom',
52
- 'paddingLeft',
53
- 'gridTemplateColumns',
54
- 'gridTemplateRows',
55
- 'gridColumnGap',
56
- 'gridRowGap',
57
- 'gridPosition',
58
- 'clipsContent',
59
- 'independentStrokeWeights',
60
- 'borderTopWeight',
61
- 'borderRightWeight',
62
- 'borderBottomWeight',
63
- 'borderLeftWeight',
64
- 'boundVariables',
65
- 'variableModes'
66
- ]
67
-
68
- export const INSTANCE_SYNC_FIELDS = [...INSTANCE_SYNC_PROPS, ...INSTANCE_SYNC_TEXT_PROPS] as const
69
-
70
- function setSceneProp<K extends keyof SceneNode>(
71
- target: Partial<SceneNode>,
72
- key: K,
73
- value: SceneNode[K]
74
- ): void {
75
- target[key] = value
76
- }
77
-
78
- function copyProp(
79
- target: Partial<SceneNode> | SceneNode,
80
- source: SceneNode,
81
- key: keyof SceneNode
82
- ): void {
83
- if (key === 'fills') {
84
- setSceneProp(target, key, copyFills(source.fills))
85
- } else if (key === 'strokes') {
86
- setSceneProp(target, key, copyStrokes(source.strokes))
87
- } else if (key === 'effects') {
88
- setSceneProp(target, key, copyEffects(source.effects))
89
- } else if (key === 'styleRuns') {
90
- setSceneProp(target, key, copyStyleRuns(source.styleRuns))
91
- } else if (key === 'boundVariables') {
92
- // Shallow copy the binding map — values are variable IDs (strings), not objects
93
- setSceneProp(target, key, { ...source.boundVariables })
94
- } else if (key === 'variableModes') {
95
- setSceneProp(target, key, { ...source.variableModes })
96
- } else if (key === 'gridPosition') {
97
- // Shallow copy the grid position object — all fields are primitives
98
- setSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null)
99
- } else {
100
- const value = source[key]
101
- setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value)
102
- }
103
- }
104
-
105
- function cloneChildrenWithMapping(
106
- graph: SceneGraph,
107
- sourceParentId: string,
108
- destParentId: string,
109
- mode: NodeCloneMode = 'deep'
110
- ): void {
111
- // Guard against cloning a subtree into itself or its own descendant. Without this,
112
- // a self-referential or cyclic component (e.g. an INSTANCE whose componentId points
113
- // to an ancestor) causes unbounded recursion and eventual stack overflow / OOM.
114
- if (sourceParentId === destParentId || graph.isDescendant(destParentId, sourceParentId)) return
115
-
116
- const sourceParent = graph.nodes.get(sourceParentId)
117
- if (!sourceParent) return
118
-
119
- for (const childId of sourceParent.childIds) {
120
- const src = graph.nodes.get(childId)
121
- if (!src) continue
122
-
123
- const clone = graph.createNode(src.type, destParentId, cloneNodeProps(src, childId, mode))
124
-
125
- if (src.childIds.length > 0) {
126
- cloneChildrenWithMapping(graph, childId, clone.id, mode)
127
- }
128
- }
129
- }
130
-
131
- function linkMatchedChild(
132
- overrides: InstanceOverrideState,
133
- instParentId: string,
134
- instChild: SceneNode,
135
- compChildId: string
136
- ): void {
137
- if (instChild.type === 'INSTANCE') {
138
- setInstanceOverride(overrides, instParentId, instChild.id, 'sourceComponentId', compChildId)
139
- } else {
140
- instChild.componentId = compChildId
141
- }
142
- }
143
-
144
- function matchFallbackChildren(
145
- graph: SceneGraph,
146
- compParent: SceneNode,
147
- instParent: SceneNode,
148
- instParentId: string,
149
- overrides: InstanceOverrideState,
150
- instChildMap: Map<string, SceneNode>,
151
- usedInstChildIds: Set<string>
152
- ): void {
153
- const fallbackByType = new Map<SceneNode['type'], Map<string, SceneNode[]>>()
154
- const remainingCandidateCount = new Map<SceneNode['type'], number>()
155
- const unmatchedComponentCount = new Map<SceneNode['type'], number>()
156
- for (const compChildId of compParent.childIds) {
157
- if (instChildMap.has(compChildId)) continue
158
- const child = graph.nodes.get(compChildId)
159
- if (child) {
160
- unmatchedComponentCount.set(child.type, (unmatchedComponentCount.get(child.type) ?? 0) + 1)
161
- }
162
- }
163
- for (const childId of instParent.childIds) {
164
- const child = graph.nodes.get(childId)
165
- if (!child || usedInstChildIds.has(child.id)) continue
166
- remainingCandidateCount.set(child.type, (remainingCandidateCount.get(child.type) ?? 0) + 1)
167
- let byName = fallbackByType.get(child.type)
168
- if (!byName) {
169
- byName = new Map()
170
- fallbackByType.set(child.type, byName)
171
- }
172
- const queue = byName.get(child.name)
173
- if (queue) queue.push(child)
174
- else byName.set(child.name, [child])
175
- }
176
-
177
- // Match by name and type with FIFO queues to preserve sibling order in linear time.
178
- for (const compChildId of compParent.childIds) {
179
- if (instChildMap.has(compChildId)) continue
180
- const compChild = graph.nodes.get(compChildId)
181
- if (!compChild) continue
182
- const candidatesByName = fallbackByType.get(compChild.type)
183
- const candidateCount = remainingCandidateCount.get(compChild.type) ?? 0
184
- if (candidateCount > (unmatchedComponentCount.get(compChild.type) ?? 0)) continue
185
- const match = candidatesByName?.get(compChild.name)?.shift()
186
- if (!match) continue
187
- remainingCandidateCount.set(compChild.type, candidateCount - 1)
188
- instChildMap.set(compChildId, match)
189
- usedInstChildIds.add(match.id)
190
- linkMatchedChild(overrides, instParentId, match, compChildId)
191
- }
192
- }
193
-
194
- function sortInstanceChildren(
195
- graph: SceneGraph,
196
- instParent: SceneNode,
197
- instParentId: string,
198
- compChildOrder: string[],
199
- overrides: InstanceOverrideState
200
- ): void {
201
- const orderMap = new Map<string, number>()
202
- for (let i = 0; i < compChildOrder.length; i++) orderMap.set(compChildOrder[i], i)
203
-
204
- const ranks = new Map<string, number>()
205
- for (let index = 0; index < instParent.childIds.length; index++) {
206
- const childId = instParent.childIds[index]
207
- const node = graph.nodes.get(childId)
208
- const source = node
209
- ? getInstanceOverride(overrides, instParentId, node.id, 'sourceComponentId')
210
- : undefined
211
- const mapped = typeof source === 'string' ? source : node?.componentId
212
- const componentIndex = mapped ? orderMap.get(mapped) : undefined
213
- ranks.set(childId, componentIndex ?? compChildOrder.length + index)
214
- }
215
- instParent.childIds.sort((left, right) => (ranks.get(left) ?? 0) - (ranks.get(right) ?? 0))
216
- }
217
-
218
- /** True when syncing `compParentId` into `instParentId` would form a cycle. */
219
- function isCyclicSync(graph: SceneGraph, compParentId: string, instParentId: string): boolean {
220
- return compParentId === instParentId || graph.isDescendant(instParentId, compParentId)
221
- }
222
-
223
- function syncChildren(
224
- graph: SceneGraph,
225
- compParentId: string,
226
- instParentId: string,
227
- overrides: InstanceOverrideState
228
- ): void {
229
- // Guard against cyclic sync: if the instance parent is inside the component's own
230
- // subtree, syncing would clone the component into itself — a self-referential cycle
231
- // that causes unbounded recursion and OOM.
232
- if (isCyclicSync(graph, compParentId, instParentId)) return
233
-
234
- const compParent = graph.nodes.get(compParentId)
235
- const instParent = graph.nodes.get(instParentId)
236
- if (!compParent || !instParent) return
237
-
238
- const instChildMap = new Map<string, SceneNode>()
239
- const usedInstChildIds = new Set<string>()
240
- const compChildIdSet = new Set(compParent.childIds)
241
-
242
- // Pass 1: Direct matching via sourceComponentId or componentId
243
- for (const childId of instParent.childIds) {
244
- const child = graph.nodes.get(childId)
245
- if (!child) continue
246
- const sourceComponentId = getInstanceOverride(
247
- overrides,
248
- instParentId,
249
- child.id,
250
- 'sourceComponentId'
251
- )
252
-
253
- const mappedComponentId =
254
- typeof sourceComponentId === 'string' ? sourceComponentId : child.componentId
255
- if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {
256
- instChildMap.set(mappedComponentId, child)
257
- usedInstChildIds.add(child.id)
258
- }
259
- }
260
-
261
- // Pass 2: Fallback matching for unmatched children (e.g. from Figma imports)
262
- matchFallbackChildren(
263
- graph,
264
- compParent,
265
- instParent,
266
- instParentId,
267
- overrides,
268
- instChildMap,
269
- usedInstChildIds
270
- )
271
-
272
- // Pass 3: Clone only genuinely missing component children
273
- for (const compChildId of compParent.childIds) {
274
- if (!instChildMap.has(compChildId)) {
275
- const src = graph.nodes.get(compChildId)
276
- if (!src) continue
277
- const clone = graph.createNode(src.type, instParentId, cloneNodeProps(src, compChildId))
278
- if (src.childIds.length > 0) {
279
- cloneChildrenWithMapping(graph, compChildId, clone.id)
280
- }
281
- instChildMap.set(compChildId, clone)
282
- usedInstChildIds.add(clone.id)
283
- }
284
- }
285
-
286
- // Pass 4: Synchronize properties and recurse
287
- for (const compChildId of compParent.childIds) {
288
- const compChild = graph.nodes.get(compChildId)
289
- const instChild = instChildMap.get(compChildId)
290
- if (!compChild || !instChild) continue
291
-
292
- for (const key of INSTANCE_SYNC_FIELDS) {
293
- if (hasNodeInstanceOverride(overrides, instParentId, instChild.id, key)) continue
294
-
295
- copyProp(instChild, compChild, key)
296
- }
297
-
298
- if (
299
- compChild.childIds.length > 0 &&
300
- !hasNodeInstanceOverride(overrides, instParentId, instChild.id, 'componentId')
301
- ) {
302
- syncChildren(graph, compChildId, instChild.id, overrides)
303
- }
304
- }
305
-
306
- // Pass 5: Sort instance children to match component child order
307
- sortInstanceChildren(graph, instParent, instParentId, compParent.childIds, overrides)
308
- }
30
+ export {
31
+ INSTANCE_FOLLOWED_FIELDS,
32
+ INSTANCE_OVERRIDE_FIELDS,
33
+ INSTANCE_SYNC_FIELDS,
34
+ INSTANCE_SYNC_PROPS,
35
+ INSTANCE_SYNC_TEXT_PROPS
36
+ } from './instances/fields'
309
37
 
310
38
  export function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {
311
39
  const props: Partial<SceneNode> = {}
@@ -320,15 +48,16 @@ export function createInstance(
320
48
  overrides: Partial<SceneNode> = {}
321
49
  ): SceneNode | null {
322
50
  const component = graph.nodes.get(componentId)
323
- if (component?.type !== 'COMPONENT') return null
51
+ if (component?.type !== 'COMPONENT' || !canCreateInstance(graph, componentId, parentId))
52
+ return null
324
53
 
325
54
  const props: Partial<SceneNode> = {
326
55
  ...copyInstanceComponentProps(component),
327
- name: component.name,
328
- componentId
56
+ name: component.name
329
57
  }
330
58
 
331
- const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides })
59
+ // The component checked above is the one the instance shows, whatever `overrides` holds.
60
+ const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })
332
61
 
333
62
  cloneChildrenWithMapping(graph, component.id, instance.id)
334
63
 
@@ -347,33 +76,101 @@ export function populateInstanceChildren(
347
76
  cloneChildrenWithMapping(graph, componentId, instanceId, mode)
348
77
  }
349
78
 
79
+ /**
80
+ * A nested instance's link to the enclosing component's record is its `componentId` when it
81
+ * was populated by cloning. A swap replaces that field, so keep the correspondence as the
82
+ * owner's `sourceComponentId` override and record the swap itself; materialized documents
83
+ * already carry the correspondence and only gain the swap.
84
+ */
85
+ function recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: string): void {
86
+ const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined
87
+ if (!owner) return
88
+ const existing = getInstanceOverride(
89
+ owner.instanceOverrides,
90
+ owner.id,
91
+ instance.id,
92
+ 'sourceComponentId'
93
+ )
94
+ if (typeof existing !== 'string' && instance.componentId)
95
+ setInstanceOverride(
96
+ owner.instanceOverrides,
97
+ owner.id,
98
+ instance.id,
99
+ 'sourceComponentId',
100
+ instance.componentId
101
+ )
102
+ setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, 'componentId', componentId)
103
+ graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })
104
+ }
105
+
106
+ export interface SwapInstanceOptions {
107
+ /**
108
+ * Keep the instance's name even when it is its old component's. A swap otherwise renames such
109
+ * an instance after the new component, as Figma does; a view that only shows another variant,
110
+ * such as preview, keeps names so layer paths stay the same.
111
+ */
112
+ keepName?: boolean
113
+ }
114
+
350
115
  export function swapInstanceComponent(
351
116
  graph: SceneGraph,
352
117
  instanceId: string,
353
- componentId: string
118
+ componentId: string,
119
+ { keepName = false }: SwapInstanceOptions = {}
354
120
  ): void {
355
121
  const instance = graph.nodes.get(instanceId)
356
122
  const component = graph.nodes.get(componentId)
357
123
  if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return
124
+ if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return
358
125
 
359
126
  const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined
127
+ recordNestedSwap(graph, instance, componentId)
360
128
  const updates: Partial<SceneNode> = { componentId }
129
+ const source = sourceInTargetCoordinates(component, instance.componentScale)
361
130
  for (const key of INSTANCE_SYNC_PROPS) {
362
131
  if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key)) continue
363
- copyProp(updates, component, key)
132
+ copyProp(updates, source, key)
364
133
  }
365
134
 
366
- if (!previousComponent || instance.name === previousComponent.name) updates.name = component.name
135
+ if (!keepName && (!previousComponent || instance.name === previousComponent.name))
136
+ updates.name = component.name
367
137
 
368
138
  const childIds = Array.from(instance.childIds)
139
+ const slotContent = detachOwnedSlotContent(graph, instance)
369
140
  for (const childId of childIds) graph.deleteNode(childId)
370
141
  graph.updateNode(instanceId, updates)
371
142
  cloneChildrenWithMapping(graph, componentId, instanceId)
143
+ restoreOwnedSlotContent(graph, instance, slotContent)
372
144
  }
373
145
 
374
146
  const syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()
375
147
 
376
148
  export function syncInstances(graph: SceneGraph, componentId: string): void {
149
+ syncInstancesOf(graph, componentId, getInstances(graph, componentId))
150
+ }
151
+
152
+ /**
153
+ * Syncs each component's instances, in order, as one edit: the copies they remove stay
154
+ * restorable together for as long as undo keeps that edit.
155
+ */
156
+ export function syncInstancesTogether(graph: SceneGraph, componentIds: Iterable<string>): void {
157
+ groupCopyRemovals(graph, () => {
158
+ for (const id of componentIds) syncInstances(graph, id)
159
+ })
160
+ }
161
+
162
+ /** Syncs one instance from its component, as `syncInstances` does for every instance. */
163
+ export function syncInstance(graph: SceneGraph, instanceId: string): void {
164
+ const instance = graph.nodes.get(instanceId)
165
+ if (instance?.type !== 'INSTANCE' || !instance.componentId) return
166
+ syncInstancesOf(graph, instance.componentId, [instance])
167
+ }
168
+
169
+ function syncInstancesOf(
170
+ graph: SceneGraph,
171
+ componentId: string,
172
+ instances: Iterable<SceneNode>
173
+ ): void {
377
174
  const component = graph.nodes.get(componentId)
378
175
  if (component?.type !== 'COMPONENT') return
379
176
  let syncing = syncingComponentsByGraph.get(graph)
@@ -384,14 +181,25 @@ export function syncInstances(graph: SceneGraph, componentId: string): void {
384
181
  if (syncing.has(componentId)) return
385
182
  syncing.add(componentId)
386
183
  try {
387
- for (const instance of getInstances(graph, componentId)) {
388
- for (const key of INSTANCE_SYNC_PROPS) {
389
- if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key))
390
- continue
391
- copyProp(instance, component, key)
184
+ groupCopyRemovals(graph, (removals) => {
185
+ for (const instance of instances) {
186
+ const enclosing = enclosingInstanceOverrideFields(graph, instance)
187
+ enclosing.push(new Set(instance.instanceOverrides.self.keys()))
188
+ const protectedField = bindingProtection(enclosing)
189
+ const source = sourceInTargetCoordinates(component, instance.componentScale)
190
+ const updates: Partial<SceneNode> = {}
191
+ syncBindingFields(instance, source, updates, protectedField)
192
+ for (const key of INSTANCE_SYNC_PROPS) {
193
+ if (key === 'boundVariables') continue
194
+ if (isProtectedSyncField(instance, key, protectedField)) continue
195
+ copyProp(updates, source, key)
196
+ }
197
+ updateSyncedProps(graph, instance, updates)
198
+ const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)
199
+ syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)
200
+ removeLeftoverCopies(graph, context, removals)
392
201
  }
393
- syncChildren(graph, component.id, instance.id, instance.instanceOverrides)
394
- }
202
+ })
395
203
  } finally {
396
204
  syncing.delete(componentId)
397
205
  }
@@ -444,22 +252,6 @@ export function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: st
444
252
  return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
445
253
  }
446
254
 
447
- /*
448
- * syncInstances) won't clobber them, and — if `nodeId` sits inside an INSTANCE —
449
- * so the .fig exporter knows to write the diff out as a symbol override. A no-op
450
- * for fields outside INSTANCE_SYNC_PROPS or nodes with no INSTANCE ancestor.
451
- */
452
- export function recordInstanceOverrideValue(
453
- graph: SceneGraph,
454
- nodeId: string,
455
- field: string,
456
- value: unknown
457
- ): void {
458
- const instance = findInstanceAncestor(graph, nodeId)
459
- if (!instance) return
460
- setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field, value)
461
- graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
462
- }
463
255
  export function recordInstanceOverride(
464
256
  graph: SceneGraph,
465
257
  nodeId: string,
@@ -469,7 +261,7 @@ export function recordInstanceOverride(
469
261
  if (!instance) return
470
262
 
471
263
  const relevant = [...fields].filter((field) =>
472
- (INSTANCE_SYNC_FIELDS as readonly string[]).includes(field)
264
+ (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field)
473
265
  )
474
266
 
475
267
  if (relevant.length === 0) return
@@ -0,0 +1,51 @@
1
+ import type { SceneGraph } from '../index'
2
+ import type { Vector } from '../primitives'
3
+ import type { SceneNode } from '../types'
4
+
5
+ type AspectRatioNode = Pick<SceneNode, 'type' | 'targetAspectRatio' | 'textAutoResize'>
6
+
7
+ /** The value Figma's `lockAspectRatio()` stores: the size the layer has when it is locked. */
8
+ export function lockedAspectRatioTarget(width: number, height: number): Vector {
9
+ return { x: width, y: height }
10
+ }
11
+
12
+ /** Whether the lock can change: a layer inside an instance keeps its component's, as in Figma. */
13
+ export function aspectRatioLockEditable(graph: SceneGraph, node: SceneNode): boolean {
14
+ return !node.parentId || !graph.closest(node.parentId, (layer) => layer.type === 'INSTANCE')
15
+ }
16
+
17
+ /**
18
+ * The width-to-height ratio a resize keeps, or `null` when the layer's proportions are free.
19
+ * Text that sizes itself to its content keeps the lock without following it, as in Figma.
20
+ */
21
+ export function enforcedAspectRatio(node: AspectRatioNode): number | null {
22
+ const target = node.targetAspectRatio
23
+ if (!target || !(target.x > 0) || !(target.y > 0)) return null
24
+ if (node.type === 'TEXT' && node.textAutoResize !== 'NONE') return null
25
+ return target.x / target.y
26
+ }
27
+
28
+ /**
29
+ * A resize that ignores a locked ratio, such as Figma's plugin `resize()` or a Control-drag,
30
+ * keeps the lock and stores the new size as the ratio to keep.
31
+ */
32
+ export function recapturedAspectRatio(
33
+ node: Pick<SceneNode, 'targetAspectRatio'>,
34
+ width: number,
35
+ height: number
36
+ ): Partial<Pick<SceneNode, 'targetAspectRatio'>> {
37
+ if (!node.targetAspectRatio) return {}
38
+ if (node.targetAspectRatio.x === width && node.targetAspectRatio.y === height) return {}
39
+ return { targetAspectRatio: lockedAspectRatioTarget(width, height) }
40
+ }
41
+
42
+ /** The size that keeps `ratio` when one axis is set to `value`. */
43
+ export function sizeKeepingAspectRatio(
44
+ ratio: number,
45
+ axis: 'width' | 'height',
46
+ value: number
47
+ ): { width: number; height: number } {
48
+ return axis === 'width'
49
+ ? { width: value, height: value / ratio }
50
+ : { width: value * ratio, height: value }
51
+ }
@@ -1,4 +1,4 @@
1
- import type { LayoutGrid, SceneNode } from './types'
1
+ import type { LayoutGrid, SceneNode } from '../types'
2
2
 
3
3
  export interface LayoutGuideLine {
4
4
  axis: 'x' | 'y'
@@ -0,0 +1,4 @@
1
+ export * from './aspect-ratio'
2
+ export * from './guides'
3
+ export * from './keywords'
4
+ export * from './sizing'
@@ -0,0 +1,73 @@
1
+ import type { LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, SceneNode } from '../types'
2
+
3
+ /**
4
+ * Auto layout as the formats that author it spell it: flexbox keywords from CSS, design JSX,
5
+ * and `.pen` files. Each format keeps its own syntax and defaults; what a keyword means for the
6
+ * scene graph is decided here once, so `space-between` or `baseline` cannot mean one thing in
7
+ * one format and fall back to start in another.
8
+ */
9
+ export type AutoLayoutDirection = 'HORIZONTAL' | 'VERTICAL'
10
+
11
+ const DIRECTIONS = new Map<string, AutoLayoutDirection>([
12
+ ['row', 'HORIZONTAL'],
13
+ ['horizontal', 'HORIZONTAL'],
14
+ ['column', 'VERTICAL'],
15
+ ['col', 'VERTICAL'],
16
+ ['vertical', 'VERTICAL']
17
+ ])
18
+
19
+ const POSITIONS = new Map<string, 'MIN' | 'CENTER' | 'MAX'>([
20
+ ['start', 'MIN'],
21
+ ['flex-start', 'MIN'],
22
+ ['center', 'CENTER'],
23
+ ['end', 'MAX'],
24
+ ['flex-end', 'MAX']
25
+ ])
26
+
27
+ function keyword(value: string | undefined): string | undefined {
28
+ return value?.trim().toLowerCase()
29
+ }
30
+
31
+ /** The stack direction a `flex-direction`-like keyword names, or `undefined` for any other. */
32
+ export function parseAutoLayoutDirection(
33
+ value: string | undefined
34
+ ): AutoLayoutDirection | undefined {
35
+ const name = keyword(value)
36
+ return name === undefined ? undefined : DIRECTIONS.get(name)
37
+ }
38
+
39
+ /**
40
+ * Primary axis alignment from a `justify-content` keyword. Auto layout has no
41
+ * `space-around` or `space-evenly`, so those, like unknown keywords, give `undefined`.
42
+ */
43
+ export function parsePrimaryAxisAlign(value: string | undefined): LayoutAlign | undefined {
44
+ const name = keyword(value)
45
+ if (name === undefined) return undefined
46
+ if (name === 'space-between' || name === 'between') return 'SPACE_BETWEEN'
47
+ return POSITIONS.get(name)
48
+ }
49
+
50
+ /** Cross axis alignment of a stack's children from an `align-items` keyword. */
51
+ export function parseCounterAxisAlign(value: string | undefined): LayoutCounterAlign | undefined {
52
+ const name = keyword(value)
53
+ if (name === undefined) return undefined
54
+ if (name === 'stretch') return 'STRETCH'
55
+ if (name === 'baseline') return 'BASELINE'
56
+ return POSITIONS.get(name)
57
+ }
58
+
59
+ /** One child's cross axis alignment from an `align-self` keyword; `auto` follows the parent. */
60
+ export function parseLayoutAlignSelf(value: string | undefined): LayoutAlignSelf | undefined {
61
+ return keyword(value) === 'auto' ? 'AUTO' : parseCounterAxisAlign(value)
62
+ }
63
+
64
+ type PaddingFields = Pick<
65
+ SceneNode,
66
+ 'paddingTop' | 'paddingRight' | 'paddingBottom' | 'paddingLeft'
67
+ >
68
+
69
+ /** Padding from one to four values in CSS shorthand order: top, right, bottom, left. */
70
+ export function paddingFromShorthand(values: readonly number[]): PaddingFields {
71
+ const [top = 0, right = top, bottom = top, left = right] = values
72
+ return { paddingTop: top, paddingRight: right, paddingBottom: bottom, paddingLeft: left }
73
+ }