@open-pencil/scene-graph 0.15.1 → 0.16.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +607 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +577 -522
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2291 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/group-bounds.js +104 -0
  34. package/dist/chunks/group-bounds.js.map +1 -0
  35. package/dist/chunks/icons/glyph.js +147 -0
  36. package/dist/chunks/icons/glyph.js.map +1 -0
  37. package/dist/chunks/index.js +1724 -663
  38. package/dist/chunks/index.js.map +1 -1
  39. package/dist/color.d.ts +72 -0
  40. package/dist/color.d.ts.map +1 -0
  41. package/dist/color.js +3 -0
  42. package/dist/constants.d.ts +2 -2
  43. package/dist/constants.js +2 -2
  44. package/dist/constants2.d.ts +3 -1
  45. package/dist/constants2.d.ts.map +1 -1
  46. package/dist/coordinate.d.ts +2 -448
  47. package/dist/coordinate.js +2 -2
  48. package/dist/copy.d.ts +1 -1
  49. package/dist/copy.js +1 -1
  50. package/dist/css.d.ts +39 -0
  51. package/dist/css.d.ts.map +1 -0
  52. package/dist/css.js +3 -0
  53. package/dist/geometry.d.ts +1 -1
  54. package/dist/geometry.js +1 -1
  55. package/dist/gradient.d.ts +51 -0
  56. package/dist/gradient.d.ts.map +1 -0
  57. package/dist/gradient.js +132 -0
  58. package/dist/gradient.js.map +1 -0
  59. package/dist/guides.d.ts +2 -2
  60. package/dist/guides.js +39 -0
  61. package/dist/guides.js.map +1 -0
  62. package/dist/hit-test.d.ts +2 -9
  63. package/dist/hit-test.js +176 -34
  64. package/dist/hit-test.js.map +1 -1
  65. package/dist/index.d.ts +4 -8
  66. package/dist/index.js +19 -5
  67. package/dist/instances.d.ts +2 -2
  68. package/dist/instances.js +2 -2
  69. package/dist/layout.d.ts +2 -0
  70. package/dist/layout.js +4 -0
  71. package/dist/node-defaults.d.ts +2 -8
  72. package/dist/node-defaults.js +2 -2
  73. package/dist/order-keys.d.ts +39 -0
  74. package/dist/order-keys.d.ts.map +1 -0
  75. package/dist/order-keys.js +136 -0
  76. package/dist/order-keys.js.map +1 -0
  77. package/dist/parse-path.d.ts +7 -1
  78. package/dist/parse-path.d.ts.map +1 -1
  79. package/dist/parse-path.js +6 -2
  80. package/dist/parse-path.js.map +1 -1
  81. package/dist/polygon.d.ts +53 -0
  82. package/dist/polygon.d.ts.map +1 -0
  83. package/dist/polygon.js +205 -0
  84. package/dist/polygon.js.map +1 -0
  85. package/dist/preview.d.ts +1 -1
  86. package/dist/random.d.ts +7 -0
  87. package/dist/random.d.ts.map +1 -0
  88. package/dist/random.js +2 -0
  89. package/dist/resize.d.ts +11 -2
  90. package/dist/resize.d.ts.map +1 -1
  91. package/dist/resize.js +2 -184
  92. package/dist/snap.d.ts +1 -1
  93. package/dist/text-direction.d.ts +13 -0
  94. package/dist/text-direction.d.ts.map +1 -0
  95. package/dist/text-direction.js +31 -0
  96. package/dist/text-direction.js.map +1 -0
  97. package/dist/text-picture.d.ts +1 -1
  98. package/dist/text-picture.d.ts.map +1 -1
  99. package/dist/text.d.ts +2 -0
  100. package/dist/text.js +3 -0
  101. package/dist/types.d.ts +2121 -15
  102. package/dist/types.d.ts.map +1 -1
  103. package/dist/types.js +2 -1
  104. package/dist/types2.d.ts +2 -2
  105. package/dist/undo.d.ts +2 -2
  106. package/dist/undo.js +2 -2
  107. package/dist/undo2.d.ts +29 -1
  108. package/dist/undo2.d.ts.map +1 -1
  109. package/dist/variables.d.ts +2 -29
  110. package/dist/variables.js +2 -2
  111. package/dist/variant-properties.d.ts +9 -1
  112. package/dist/variant-properties.d.ts.map +1 -1
  113. package/dist/variant-properties.js +36 -1
  114. package/dist/variant-properties.js.map +1 -1
  115. package/dist/vector-network.d.ts +1 -1
  116. package/dist/vector-network.js +1 -1
  117. package/package.json +60 -9
  118. package/src/behaviours/kinds.ts +185 -0
  119. package/src/behaviours/layers.ts +51 -0
  120. package/src/behaviours/model.ts +192 -0
  121. package/src/behaviours/schema.ts +58 -0
  122. package/src/behaviours/spec.ts +223 -0
  123. package/src/buffered-events.ts +64 -0
  124. package/src/color/contrast.ts +31 -0
  125. package/src/color/index.ts +88 -0
  126. package/src/color/management.ts +210 -0
  127. package/src/color/normalize.ts +7 -0
  128. package/src/color/okhcl.ts +201 -0
  129. package/src/comments/document.ts +51 -0
  130. package/src/comments/list.ts +52 -0
  131. package/src/comments/merge.ts +63 -0
  132. package/src/comments/threads.ts +156 -0
  133. package/src/components/exposure.ts +61 -0
  134. package/src/components/properties.ts +18 -15
  135. package/src/components/variants.ts +53 -0
  136. package/src/constants.ts +2 -0
  137. package/src/coordinate.ts +100 -43
  138. package/src/copy.ts +17 -6
  139. package/src/css/grid.ts +70 -0
  140. package/src/css/index.ts +9 -0
  141. package/src/css/layout.ts +53 -0
  142. package/src/css/shadows.ts +68 -0
  143. package/src/css/values.ts +42 -0
  144. package/src/export-format.ts +12 -0
  145. package/src/fields/geometry.ts +11 -0
  146. package/src/fields/text.ts +35 -0
  147. package/src/gradient.ts +166 -0
  148. package/src/group-bounds.ts +131 -0
  149. package/src/guides.ts +39 -0
  150. package/src/hit-test.ts +262 -46
  151. package/src/icons/glyph.ts +128 -0
  152. package/src/icons/model.ts +54 -0
  153. package/src/icons/schema.ts +18 -0
  154. package/src/index.ts +347 -57
  155. package/src/instance-overrides.ts +27 -0
  156. package/src/instances/content-size.ts +58 -0
  157. package/src/instances/copies.ts +239 -0
  158. package/src/instances/cycles.ts +73 -0
  159. package/src/instances/fields.ts +143 -0
  160. package/src/instances/main-component.ts +19 -0
  161. package/src/instances/placement.ts +29 -0
  162. package/src/instances/source-walk.ts +41 -0
  163. package/src/instances/sync.ts +600 -0
  164. package/src/instances/vector-geometry.ts +81 -0
  165. package/src/instances.ts +125 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +41 -12
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/shared-styles.ts +5 -2
  187. package/src/slots/authoring.ts +101 -0
  188. package/src/slots/content.ts +124 -0
  189. package/src/slots/frames.ts +160 -0
  190. package/src/slots/limits.ts +49 -0
  191. package/src/text/direction.ts +55 -0
  192. package/src/text/index.ts +3 -0
  193. package/src/text/lists.ts +138 -0
  194. package/src/text/paragraphs.ts +241 -0
  195. package/src/{text-picture.ts → text/picture.ts} +21 -29
  196. package/src/text/references.ts +50 -0
  197. package/src/transfer/apply.ts +84 -0
  198. package/src/transfer/history.ts +49 -0
  199. package/src/transfer/identity.ts +16 -0
  200. package/src/transfer/index.ts +6 -0
  201. package/src/transfer/nodes.ts +120 -0
  202. package/src/transfer/plan.ts +130 -0
  203. package/src/transfer/references.ts +9 -0
  204. package/src/transfer/remove.ts +39 -0
  205. package/src/transfer/validation.ts +59 -0
  206. package/src/transfer/variables.ts +82 -0
  207. package/src/types.ts +257 -13
  208. package/src/undo.ts +54 -2
  209. package/src/variables/bindings.ts +224 -0
  210. package/src/variables/fields.ts +43 -0
  211. package/src/variables/token.ts +14 -0
  212. package/src/variables/units.ts +15 -0
  213. package/src/variables.ts +118 -69
  214. package/src/variant-properties.ts +50 -0
  215. package/dist/chunks/components/properties.js.map +0 -1
  216. package/dist/chunks/export-scale.js +0 -19
  217. package/dist/chunks/export-scale.js.map +0 -1
  218. package/dist/coordinate.d.ts.map +0 -1
  219. package/dist/coordinate2.d.ts +0 -2
  220. package/dist/guides2.d.ts +0 -11
  221. package/dist/guides2.d.ts.map +0 -1
  222. package/dist/hit-test.d.ts.map +0 -1
  223. package/dist/layout-guides.d.ts +0 -2
  224. package/dist/layout-guides.js +0 -2
  225. package/dist/layout-guides2.d.ts +0 -16
  226. package/dist/layout-guides2.d.ts.map +0 -1
  227. package/dist/node-defaults.d.ts.map +0 -1
  228. package/dist/preview2.d.ts +0 -12
  229. package/dist/preview2.d.ts.map +0 -1
  230. package/dist/resize.js.map +0 -1
  231. package/dist/variables.d.ts.map +0 -1
  232. package/dist/vector-network2.d.ts +0 -32
  233. package/dist/vector-network2.d.ts.map +0 -1
  234. package/src/instance-overrides.test.ts +0 -67
package/src/instances.ts CHANGED
@@ -1,311 +1,40 @@
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 { keepOwnContentSize } from './instances/content-size'
10
+ import {
11
+ createInstanceSyncContext,
12
+ groupCopyRemovals,
13
+ removeLeftoverCopies
14
+ } from './instances/copies'
15
+ import { canCreateInstance } from './instances/cycles'
16
+ import { INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_PROPS } from './instances/fields'
17
+ import {
18
+ bindingProtection,
19
+ cloneChildrenWithMapping,
20
+ copyProp,
21
+ enclosingInstanceOverrideFields,
22
+ isProtectedSyncField,
23
+ sourceInTargetCoordinates,
24
+ syncBindingFields,
25
+ syncChildren,
26
+ updateSyncedProps
27
+ } from './instances/sync'
28
+ import { detachOwnedSlotContent, restoreOwnedSlotContent } from './slots/frames'
11
29
 
12
30
  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
- }
31
+ export {
32
+ INSTANCE_FOLLOWED_FIELDS,
33
+ INSTANCE_OVERRIDE_FIELDS,
34
+ INSTANCE_SYNC_FIELDS,
35
+ INSTANCE_SYNC_PROPS,
36
+ INSTANCE_SYNC_TEXT_PROPS
37
+ } from './instances/fields'
309
38
 
310
39
  export function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {
311
40
  const props: Partial<SceneNode> = {}
@@ -320,15 +49,16 @@ export function createInstance(
320
49
  overrides: Partial<SceneNode> = {}
321
50
  ): SceneNode | null {
322
51
  const component = graph.nodes.get(componentId)
323
- if (component?.type !== 'COMPONENT') return null
52
+ if (component?.type !== 'COMPONENT' || !canCreateInstance(graph, componentId, parentId))
53
+ return null
324
54
 
325
55
  const props: Partial<SceneNode> = {
326
56
  ...copyInstanceComponentProps(component),
327
- name: component.name,
328
- componentId
57
+ name: component.name
329
58
  }
330
59
 
331
- const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides })
60
+ // The component checked above is the one the instance shows, whatever `overrides` holds.
61
+ const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })
332
62
 
333
63
  cloneChildrenWithMapping(graph, component.id, instance.id)
334
64
 
@@ -347,33 +77,101 @@ export function populateInstanceChildren(
347
77
  cloneChildrenWithMapping(graph, componentId, instanceId, mode)
348
78
  }
349
79
 
80
+ /**
81
+ * A nested instance's link to the enclosing component's record is its `componentId` when it
82
+ * was populated by cloning. A swap replaces that field, so keep the correspondence as the
83
+ * owner's `sourceComponentId` override and record the swap itself; materialized documents
84
+ * already carry the correspondence and only gain the swap.
85
+ */
86
+ function recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: string): void {
87
+ const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined
88
+ if (!owner) return
89
+ const existing = getInstanceOverride(
90
+ owner.instanceOverrides,
91
+ owner.id,
92
+ instance.id,
93
+ 'sourceComponentId'
94
+ )
95
+ if (typeof existing !== 'string' && instance.componentId)
96
+ setInstanceOverride(
97
+ owner.instanceOverrides,
98
+ owner.id,
99
+ instance.id,
100
+ 'sourceComponentId',
101
+ instance.componentId
102
+ )
103
+ setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, 'componentId', componentId)
104
+ graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })
105
+ }
106
+
107
+ export interface SwapInstanceOptions {
108
+ /**
109
+ * Keep the instance's name even when it is its old component's. A swap otherwise renames such
110
+ * an instance after the new component, as Figma does; a view that only shows another variant,
111
+ * such as preview, keeps names so layer paths stay the same.
112
+ */
113
+ keepName?: boolean
114
+ }
115
+
350
116
  export function swapInstanceComponent(
351
117
  graph: SceneGraph,
352
118
  instanceId: string,
353
- componentId: string
119
+ componentId: string,
120
+ { keepName = false }: SwapInstanceOptions = {}
354
121
  ): void {
355
122
  const instance = graph.nodes.get(instanceId)
356
123
  const component = graph.nodes.get(componentId)
357
124
  if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return
125
+ if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return
358
126
 
359
127
  const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined
128
+ recordNestedSwap(graph, instance, componentId)
360
129
  const updates: Partial<SceneNode> = { componentId }
130
+ const source = sourceInTargetCoordinates(component, instance.componentScale)
361
131
  for (const key of INSTANCE_SYNC_PROPS) {
362
132
  if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key)) continue
363
- copyProp(updates, component, key)
133
+ copyProp(updates, source, key)
364
134
  }
365
135
 
366
- if (!previousComponent || instance.name === previousComponent.name) updates.name = component.name
136
+ if (!keepName && (!previousComponent || instance.name === previousComponent.name))
137
+ updates.name = component.name
367
138
 
368
139
  const childIds = Array.from(instance.childIds)
140
+ const slotContent = detachOwnedSlotContent(graph, instance)
369
141
  for (const childId of childIds) graph.deleteNode(childId)
370
142
  graph.updateNode(instanceId, updates)
371
143
  cloneChildrenWithMapping(graph, componentId, instanceId)
144
+ restoreOwnedSlotContent(graph, instance, slotContent)
372
145
  }
373
146
 
374
147
  const syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()
375
148
 
376
149
  export function syncInstances(graph: SceneGraph, componentId: string): void {
150
+ syncInstancesOf(graph, componentId, getInstances(graph, componentId))
151
+ }
152
+
153
+ /**
154
+ * Syncs each component's instances, in order, as one edit: the copies they remove stay
155
+ * restorable together for as long as undo keeps that edit.
156
+ */
157
+ export function syncInstancesTogether(graph: SceneGraph, componentIds: Iterable<string>): void {
158
+ groupCopyRemovals(graph, () => {
159
+ for (const id of componentIds) syncInstances(graph, id)
160
+ })
161
+ }
162
+
163
+ /** Syncs one instance from its component, as `syncInstances` does for every instance. */
164
+ export function syncInstance(graph: SceneGraph, instanceId: string): void {
165
+ const instance = graph.nodes.get(instanceId)
166
+ if (instance?.type !== 'INSTANCE' || !instance.componentId) return
167
+ syncInstancesOf(graph, instance.componentId, [instance])
168
+ }
169
+
170
+ function syncInstancesOf(
171
+ graph: SceneGraph,
172
+ componentId: string,
173
+ instances: Iterable<SceneNode>
174
+ ): void {
377
175
  const component = graph.nodes.get(componentId)
378
176
  if (component?.type !== 'COMPONENT') return
379
177
  let syncing = syncingComponentsByGraph.get(graph)
@@ -384,14 +182,27 @@ export function syncInstances(graph: SceneGraph, componentId: string): void {
384
182
  if (syncing.has(componentId)) return
385
183
  syncing.add(componentId)
386
184
  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)
185
+ groupCopyRemovals(graph, (removals) => {
186
+ for (const instance of instances) {
187
+ const enclosing = enclosingInstanceOverrideFields(graph, instance)
188
+ enclosing.push(new Set(instance.instanceOverrides.self.keys()))
189
+ const protectedField = bindingProtection(enclosing)
190
+ const source = sourceInTargetCoordinates(component, instance.componentScale)
191
+ const updates: Partial<SceneNode> = {}
192
+ syncBindingFields(instance, source, updates, protectedField)
193
+ for (const key of INSTANCE_SYNC_PROPS) {
194
+ if (key === 'boundVariables') continue
195
+ if (isProtectedSyncField(instance, key, protectedField)) continue
196
+ copyProp(updates, source, key)
197
+ }
198
+ // An instance that hugs its layers sizes to what it shows, not to the component.
199
+ keepOwnContentSize(graph, updates, instance, source)
200
+ updateSyncedProps(graph, instance, updates)
201
+ const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)
202
+ syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)
203
+ removeLeftoverCopies(graph, context, removals)
392
204
  }
393
- syncChildren(graph, component.id, instance.id, instance.instanceOverrides)
394
- }
205
+ })
395
206
  } finally {
396
207
  syncing.delete(componentId)
397
208
  }
@@ -444,22 +255,6 @@ export function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: st
444
255
  return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
445
256
  }
446
257
 
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
258
  export function recordInstanceOverride(
464
259
  graph: SceneGraph,
465
260
  nodeId: string,
@@ -469,7 +264,7 @@ export function recordInstanceOverride(
469
264
  if (!instance) return
470
265
 
471
266
  const relevant = [...fields].filter((field) =>
472
- (INSTANCE_SYNC_FIELDS as readonly string[]).includes(field)
267
+ (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field)
473
268
  )
474
269
 
475
270
  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'
@@ -7,10 +7,21 @@ export interface LayoutGuideLine {
7
7
 
8
8
  const MAX_LAYOUT_GUIDE_LINES = 10_000
9
9
 
10
- function normalizedCount(grid: LayoutGrid): number {
11
- const value = grid.count ?? grid.numSections ?? 1
12
- if (!Number.isFinite(value)) return 0
13
- return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor(value)))
10
+ /** Figma's Auto count, as its archive stores it: as many sections as fit. */
11
+ export const AUTO_LAYOUT_GRID_COUNT = 2_147_483_647
12
+
13
+ /** Whether a guide's count is Auto: the archive's value, or the plugin API's `Infinity` or `null`. */
14
+ export function isAutoGridCount(count: number | null | undefined): boolean {
15
+ return count === null || count === Infinity || (count ?? 0) >= AUTO_LAYOUT_GRID_COUNT
16
+ }
17
+
18
+ /**
19
+ * A guide's count, set in Figma's plugin shape (`count`) or read from a file (`numSections`); an
20
+ * edit's `count` wins over the count the file had. Auto is {@link AUTO_LAYOUT_GRID_COUNT}.
21
+ */
22
+ export function layoutGridCount(grid: LayoutGrid): number {
23
+ const count = grid.count === undefined ? grid.numSections : grid.count
24
+ return isAutoGridCount(count) ? AUTO_LAYOUT_GRID_COUNT : (count ?? 1)
14
25
  }
15
26
 
16
27
  function pattern(grid: LayoutGrid): 'COLUMNS' | 'ROWS' | 'GRID' {
@@ -25,17 +36,35 @@ function alignment(grid: LayoutGrid): 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' {
25
36
  return 'MIN'
26
37
  }
27
38
 
28
- function sectionSize(nodeSize: number, grid: LayoutGrid): number {
39
+ /**
40
+ * How many sections a guide draws. Auto fits as many fixed sections as the frame holds, counting
41
+ * the offset once from the aligned edge, as Figma desktop 126 draws them.
42
+ */
43
+ function sectionCount(nodeSize: number, grid: LayoutGrid): number {
44
+ const value = layoutGridCount(grid)
45
+ if (value === AUTO_LAYOUT_GRID_COUNT) {
46
+ const size = grid.sectionSize ?? 0
47
+ if (alignment(grid) === 'STRETCH' || size <= 0) return 0
48
+ const gutter = grid.gutterSize ?? 0
49
+ const offset = alignment(grid) === 'CENTER' ? 0 : (grid.offset ?? 0)
50
+ return Math.min(
51
+ MAX_LAYOUT_GUIDE_LINES,
52
+ Math.max(0, Math.floor((nodeSize - offset + gutter) / (size + gutter)))
53
+ )
54
+ }
55
+ if (!Number.isFinite(value)) return 0
56
+ return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor(value)))
57
+ }
58
+
59
+ function sectionSize(nodeSize: number, grid: LayoutGrid, count: number): number {
29
60
  const fixed = grid.sectionSize ?? 0
30
61
  if (alignment(grid) !== 'STRETCH') return fixed
31
- const count = normalizedCount(grid)
32
62
  const gutter = grid.gutterSize ?? 0
33
63
  const offset = grid.offset ?? 0
34
64
  return (nodeSize - offset * 2 - Math.max(0, count - 1) * gutter) / count
35
65
  }
36
66
 
37
- function start(nodeSize: number, grid: LayoutGrid, size: number): number {
38
- const count = normalizedCount(grid)
67
+ function start(nodeSize: number, grid: LayoutGrid, size: number, count: number): number {
39
68
  const gutter = grid.gutterSize ?? 0
40
69
  const offset = grid.offset ?? 0
41
70
  const span = count * size + Math.max(0, count - 1) * gutter
@@ -57,10 +86,10 @@ export function layoutGuideSections(
57
86
  if (grid.visible === false || pattern(grid) === 'GRID') return []
58
87
  const axis = pattern(grid) === 'ROWS' ? 'y' : 'x'
59
88
  const nodeSize = axis === 'x' ? node.width : node.height
60
- const size = sectionSize(nodeSize, grid)
61
- const count = normalizedCount(grid)
89
+ const count = sectionCount(nodeSize, grid)
90
+ const size = sectionSize(nodeSize, grid, count)
62
91
  if (count <= 0 || size <= 0) return []
63
- const first = start(nodeSize, grid, size)
92
+ const first = start(nodeSize, grid, size, count)
64
93
  const step = size + (grid.gutterSize ?? 0)
65
94
  return Array.from({ length: count }, (_, index) => {
66
95
  const sectionStart = first + index * step
@@ -0,0 +1,4 @@
1
+ export * from './aspect-ratio'
2
+ export * from './guides'
3
+ export * from './keywords'
4
+ export * from './sizing'