@open-pencil/scene-graph 0.14.0 → 0.15.0

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 (130) hide show
  1. package/dist/arrow-caps.d.ts +44 -0
  2. package/dist/arrow-caps.d.ts.map +1 -0
  3. package/dist/arrow-caps.js +131 -0
  4. package/dist/arrow-caps.js.map +1 -0
  5. package/dist/chunks/checkpoint.js +78 -0
  6. package/dist/chunks/checkpoint.js.map +1 -0
  7. package/dist/chunks/components/properties.js +1571 -0
  8. package/dist/chunks/components/properties.js.map +1 -0
  9. package/dist/chunks/coordinate.js +87 -33
  10. package/dist/chunks/coordinate.js.map +1 -1
  11. package/dist/chunks/font-style.js +2 -1
  12. package/dist/chunks/font-style.js.map +1 -1
  13. package/dist/chunks/index.js +1283 -0
  14. package/dist/chunks/index.js.map +1 -0
  15. package/dist/constants.js +1 -18
  16. package/dist/constants2.d.ts +0 -1
  17. package/dist/constants2.d.ts.map +1 -1
  18. package/dist/coordinate.d.ts +107 -11
  19. package/dist/coordinate.d.ts.map +1 -1
  20. package/dist/coordinate.js +2 -2
  21. package/dist/coordinate2.d.ts +2 -2
  22. package/dist/copy.d.ts +2 -2
  23. package/dist/copy.js +2 -2
  24. package/dist/geometry.d.ts +2 -2
  25. package/dist/geometry.js +2 -431
  26. package/dist/guides.d.ts +2 -0
  27. package/dist/guides.js +0 -0
  28. package/dist/guides2.d.ts +11 -0
  29. package/dist/guides2.d.ts.map +1 -0
  30. package/dist/hit-test.d.ts +1 -2
  31. package/dist/hit-test.d.ts.map +1 -1
  32. package/dist/hit-test.js +26 -14
  33. package/dist/hit-test.js.map +1 -1
  34. package/dist/images.js +0 -1
  35. package/dist/images.js.map +1 -1
  36. package/dist/images2.d.ts.map +1 -1
  37. package/dist/index.d.ts +5 -3
  38. package/dist/index.js +5 -6
  39. package/dist/instances.d.ts +2 -2
  40. package/dist/instances.js +2 -2
  41. package/dist/layout-guides.d.ts +2 -0
  42. package/dist/layout-guides.js +2 -0
  43. package/dist/layout-guides2.d.ts +16 -0
  44. package/dist/layout-guides2.d.ts.map +1 -0
  45. package/dist/matrix2.d.ts +0 -1
  46. package/dist/matrix2.d.ts.map +1 -1
  47. package/dist/node-defaults.d.ts +1 -2
  48. package/dist/node-defaults.d.ts.map +1 -1
  49. package/dist/node-defaults.js +1 -1
  50. package/dist/parse-path.d.ts +1 -2
  51. package/dist/parse-path.d.ts.map +1 -1
  52. package/dist/parse-path.js.map +1 -1
  53. package/dist/preview.d.ts +2 -12
  54. package/dist/preview.js +1 -1
  55. package/dist/preview2.d.ts +12 -0
  56. package/dist/preview2.d.ts.map +1 -0
  57. package/dist/primitives2.d.ts.map +1 -1
  58. package/dist/resize.d.ts +18 -4
  59. package/dist/resize.d.ts.map +1 -1
  60. package/dist/resize.js +70 -22
  61. package/dist/resize.js.map +1 -1
  62. package/dist/snap.js +1 -1
  63. package/dist/source-metadata.d.ts +1 -2
  64. package/dist/source-metadata.d.ts.map +1 -1
  65. package/dist/source-metadata.js +1 -1
  66. package/dist/text-picture.d.ts +13 -2
  67. package/dist/text-picture.d.ts.map +1 -1
  68. package/dist/text-picture.js +2 -2
  69. package/dist/types.d.ts +499 -2
  70. package/dist/types.d.ts.map +1 -0
  71. package/dist/types.js +1 -1296
  72. package/dist/types2.d.ts +2 -430
  73. package/dist/undo.js +1 -1
  74. package/dist/undo2.d.ts +5 -0
  75. package/dist/undo2.d.ts.map +1 -1
  76. package/dist/variables.d.ts +1 -2
  77. package/dist/variables.d.ts.map +1 -1
  78. package/dist/variables.js +1 -1
  79. package/dist/variant-name.d.ts.map +1 -1
  80. package/dist/variant-properties.d.ts +10 -0
  81. package/dist/variant-properties.d.ts.map +1 -0
  82. package/dist/variant-properties.js +39 -0
  83. package/dist/variant-properties.js.map +1 -0
  84. package/dist/vector-network.js +1 -1
  85. package/dist/vector-network2.d.ts +1 -2
  86. package/dist/vector-network2.d.ts.map +1 -1
  87. package/package.json +40 -15
  88. package/src/arrow-caps.ts +146 -0
  89. package/src/bindings.ts +20 -0
  90. package/src/checkpoint.ts +123 -0
  91. package/src/components/properties.ts +238 -0
  92. package/src/constants.ts +6 -0
  93. package/src/coordinate.ts +226 -0
  94. package/src/copy.ts +294 -0
  95. package/src/events.ts +21 -0
  96. package/src/export-scale.ts +16 -0
  97. package/src/font-style.ts +77 -0
  98. package/src/geometry.ts +530 -0
  99. package/src/guides.ts +8 -0
  100. package/src/hit-test.ts +205 -0
  101. package/src/images.ts +34 -0
  102. package/src/index.ts +686 -0
  103. package/src/instance-overrides.test.ts +67 -0
  104. package/src/instance-overrides.ts +152 -0
  105. package/src/instances.ts +480 -0
  106. package/src/layout-guides.ts +103 -0
  107. package/src/matrix.ts +116 -0
  108. package/src/mutation-impact.ts +70 -0
  109. package/src/node-defaults.ts +186 -0
  110. package/src/parse-path.ts +191 -0
  111. package/src/preview.ts +80 -0
  112. package/src/primitives.ts +42 -0
  113. package/src/resize.ts +302 -0
  114. package/src/shared-styles.ts +73 -0
  115. package/src/snap.ts +129 -0
  116. package/src/source-metadata.ts +8 -0
  117. package/src/text-picture.ts +65 -0
  118. package/src/types.ts +635 -0
  119. package/src/undo.ts +171 -0
  120. package/src/variables.ts +399 -0
  121. package/src/variant-name.ts +15 -0
  122. package/src/variant-properties.ts +48 -0
  123. package/src/vector-network.ts +293 -0
  124. package/dist/chunks/copy.js +0 -576
  125. package/dist/chunks/copy.js.map +0 -1
  126. package/dist/constants.js.map +0 -1
  127. package/dist/geometry.js.map +0 -1
  128. package/dist/preview.d.ts.map +0 -1
  129. package/dist/types.js.map +0 -1
  130. package/dist/types2.d.ts.map +0 -1
@@ -0,0 +1,67 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+
3
+ import {
4
+ clearInstanceOverrides,
5
+ cloneInstanceOverrideState,
6
+ createInstanceOverrideState,
7
+ deleteInstanceOverride,
8
+ deserializeInstanceOverrideState,
9
+ getInstanceOverride,
10
+ hasInstanceOverride,
11
+ serializeInstanceOverrideState,
12
+ setInstanceOverride
13
+ } from './instance-overrides'
14
+
15
+ describe('instance override state', () => {
16
+ test('stores self and descendant values structurally', () => {
17
+ const state = createInstanceOverrideState()
18
+ setInstanceOverride(state, 'instance', 'instance', 'visible', false)
19
+ setInstanceOverride(state, 'instance', 'child', 'text', 'Custom')
20
+ expect(getInstanceOverride(state, 'instance', 'instance', 'visible')).toBe(false)
21
+ expect(getInstanceOverride(state, 'instance', 'child', 'text')).toBe('Custom')
22
+ expect(hasInstanceOverride(state, 'instance', 'child', 'text')).toBe(true)
23
+ })
24
+
25
+ test('reports presence for an explicit undefined override', () => {
26
+ const state = createInstanceOverrideState()
27
+ setInstanceOverride(state, 'instance', 'child', 'visible', undefined)
28
+ expect(hasInstanceOverride(state, 'instance', 'child', 'visible')).toBe(true)
29
+ })
30
+
31
+ test('round-trips explicit undefined values through JSON', () => {
32
+ const state = createInstanceOverrideState()
33
+ state.self.set('opacity', undefined)
34
+ state.descendants.set('child', new Map([['visible', undefined]]))
35
+ // eslint-disable-next-line unicorn/prefer-structured-clone -- exercise the JSON boundary
36
+ const serialized: unknown = JSON.parse(JSON.stringify(serializeInstanceOverrideState(state)))
37
+ const restored = deserializeInstanceOverrideState(serialized)
38
+
39
+ expect(hasInstanceOverride(restored, 'instance', 'instance', 'opacity')).toBe(true)
40
+ expect(getInstanceOverride(restored, 'instance', 'instance', 'opacity')).toBeUndefined()
41
+ expect(hasInstanceOverride(restored, 'instance', 'child', 'visible')).toBe(true)
42
+ expect(getInstanceOverride(restored, 'instance', 'child', 'visible')).toBeUndefined()
43
+ })
44
+
45
+ test('ignores malformed serialized entries', () => {
46
+ const state = deserializeInstanceOverrideState({ self: [null], descendants: [] })
47
+ expect(state.self.size).toBe(0)
48
+ expect(state.descendants.size).toBe(0)
49
+ })
50
+
51
+ test('deletes empty descendant buckets', () => {
52
+ const state = createInstanceOverrideState()
53
+ setInstanceOverride(state, 'instance', 'child', 'text')
54
+ expect(deleteInstanceOverride(state, 'instance', 'child', 'text')).toBe(true)
55
+ expect(state.descendants.has('child')).toBe(false)
56
+ })
57
+
58
+ test('clones independently and clears', () => {
59
+ const state = createInstanceOverrideState()
60
+ setInstanceOverride(state, 'instance', 'child', 'text', 'Custom')
61
+ const clone = cloneInstanceOverrideState(state)
62
+ setInstanceOverride(clone, 'instance', 'child', 'text', 'Other')
63
+ expect(getInstanceOverride(state, 'instance', 'child', 'text')).toBe('Custom')
64
+ clearInstanceOverrides(state)
65
+ expect(state.descendants.size).toBe(0)
66
+ })
67
+ })
@@ -0,0 +1,152 @@
1
+ export type InstanceOverrideField = string
2
+
3
+ export interface InstanceOverrideState {
4
+ self: Map<InstanceOverrideField, unknown>
5
+ descendants: Map<string, Map<InstanceOverrideField, unknown>>
6
+ }
7
+
8
+ export function createInstanceOverrideState(): InstanceOverrideState {
9
+ return { self: new Map(), descendants: new Map() }
10
+ }
11
+
12
+ export interface SerializedOverrideValue {
13
+ defined: boolean
14
+ value?: unknown
15
+ }
16
+
17
+ export interface SerializedInstanceOverrideState {
18
+ self: Array<[InstanceOverrideField, SerializedOverrideValue]>
19
+ descendants: Array<[string, Array<[InstanceOverrideField, SerializedOverrideValue]>]>
20
+ }
21
+
22
+ function serializeOverrideValue(value: unknown): SerializedOverrideValue {
23
+ return value === undefined ? { defined: false } : { defined: true, value }
24
+ }
25
+
26
+ function deserializeOverrideValue(value: unknown): { valid: boolean; value: unknown } {
27
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
28
+ return { valid: false, value: undefined }
29
+ }
30
+ if (!('defined' in value) || typeof value.defined !== 'boolean') {
31
+ return { valid: false, value: undefined }
32
+ }
33
+ if (value.defined) {
34
+ return 'value' in value
35
+ ? { valid: true, value: value['value'] }
36
+ : { valid: false, value: undefined }
37
+ }
38
+ return { valid: true, value: undefined }
39
+ }
40
+
41
+ function deserializeEntries(value: unknown): Map<InstanceOverrideField, unknown> {
42
+ const result = new Map<InstanceOverrideField, unknown>()
43
+ if (!Array.isArray(value)) return result
44
+ for (const entry of value) {
45
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue
46
+ const decoded = deserializeOverrideValue(entry[1])
47
+ if (decoded.valid) result.set(entry[0], decoded.value)
48
+ }
49
+ return result
50
+ }
51
+
52
+ export function serializeInstanceOverrideState(
53
+ state: InstanceOverrideState
54
+ ): SerializedInstanceOverrideState {
55
+ return {
56
+ self: [...state.self].map(([field, value]) => [field, serializeOverrideValue(value)]),
57
+ descendants: [...state.descendants].map(([nodeId, fields]) => [
58
+ nodeId,
59
+ [...fields].map(([field, value]) => [field, serializeOverrideValue(value)])
60
+ ])
61
+ }
62
+ }
63
+
64
+ export function deserializeInstanceOverrideState(state: unknown): InstanceOverrideState {
65
+ if (!state || typeof state !== 'object' || Array.isArray(state)) {
66
+ return createInstanceOverrideState()
67
+ }
68
+ const self =
69
+ 'self' in state ? deserializeEntries(state.self) : new Map<InstanceOverrideField, unknown>()
70
+ const descendants = new Map<string, Map<InstanceOverrideField, unknown>>()
71
+ if ('descendants' in state && Array.isArray(state.descendants)) {
72
+ for (const entry of state.descendants) {
73
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue
74
+ descendants.set(entry[0], deserializeEntries(entry[1]))
75
+ }
76
+ }
77
+ return { self, descendants }
78
+ }
79
+
80
+ export function cloneInstanceOverrideState(state: InstanceOverrideState): InstanceOverrideState {
81
+ return {
82
+ self: new Map([...state.self].map(([field, value]) => [field, structuredClone(value)])),
83
+ descendants: new Map(
84
+ [...state.descendants].map(([id, fields]) => [
85
+ id,
86
+ new Map([...fields].map(([field, value]) => [field, structuredClone(value)]))
87
+ ])
88
+ )
89
+ }
90
+ }
91
+
92
+ export function getInstanceOverride(
93
+ state: InstanceOverrideState,
94
+ instanceId: string,
95
+ nodeId: string,
96
+ field: InstanceOverrideField
97
+ ): unknown {
98
+ return nodeId === instanceId ? state.self.get(field) : state.descendants.get(nodeId)?.get(field)
99
+ }
100
+
101
+ export function hasInstanceOverride(
102
+ state: InstanceOverrideState,
103
+ instanceId: string,
104
+ nodeId: string,
105
+ field: InstanceOverrideField
106
+ ): boolean {
107
+ const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)
108
+ return fields?.has(field) ?? false
109
+ }
110
+
111
+ export function setInstanceOverride(
112
+ state: InstanceOverrideState,
113
+ instanceId: string,
114
+ nodeId: string,
115
+ field: InstanceOverrideField,
116
+ value: unknown = true
117
+ ): void {
118
+ if (nodeId === instanceId) {
119
+ state.self.set(field, value)
120
+ return
121
+ }
122
+ const fields = state.descendants.get(nodeId) ?? new Map<string, unknown>()
123
+ fields.set(field, value)
124
+ state.descendants.set(nodeId, fields)
125
+ }
126
+
127
+ export function deleteInstanceOverride(
128
+ state: InstanceOverrideState,
129
+ instanceId: string,
130
+ nodeId: string,
131
+ field: InstanceOverrideField
132
+ ): boolean {
133
+ const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)
134
+ if (!fields?.delete(field)) return false
135
+ if (nodeId !== instanceId && fields.size === 0) state.descendants.delete(nodeId)
136
+ return true
137
+ }
138
+
139
+ export function clearInstanceOverrides(state: InstanceOverrideState): void {
140
+ state.self.clear()
141
+ state.descendants.clear()
142
+ }
143
+
144
+ export function forEachInstanceOverride(
145
+ state: InstanceOverrideState,
146
+ callback: (nodeId: string, field: InstanceOverrideField, value: unknown) => void
147
+ ): void {
148
+ for (const [field, value] of state.self) callback('', field, value)
149
+ for (const [nodeId, fields] of state.descendants) {
150
+ for (const [field, value] of fields) callback(nodeId, field, value)
151
+ }
152
+ }
@@ -0,0 +1,480 @@
1
+ import type { SceneGraph, SceneNode } from './'
2
+ import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from './copy'
3
+ import type { NodeCloneMode } from './copy'
4
+ import {
5
+ clearInstanceOverrides,
6
+ getInstanceOverride,
7
+ hasInstanceOverride as hasNodeInstanceOverride,
8
+ setInstanceOverride,
9
+ type InstanceOverrideState
10
+ } from './instance-overrides'
11
+
12
+ 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
+ }
309
+
310
+ export function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {
311
+ const props: Partial<SceneNode> = {}
312
+ for (const key of INSTANCE_SYNC_PROPS) copyProp(props, component, key)
313
+ return props
314
+ }
315
+
316
+ export function createInstance(
317
+ graph: SceneGraph,
318
+ componentId: string,
319
+ parentId: string,
320
+ overrides: Partial<SceneNode> = {}
321
+ ): SceneNode | null {
322
+ const component = graph.nodes.get(componentId)
323
+ if (component?.type !== 'COMPONENT') return null
324
+
325
+ const props: Partial<SceneNode> = {
326
+ ...copyInstanceComponentProps(component),
327
+ name: component.name,
328
+ componentId
329
+ }
330
+
331
+ const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides })
332
+
333
+ cloneChildrenWithMapping(graph, component.id, instance.id)
334
+
335
+ return instance
336
+ }
337
+
338
+ export function populateInstanceChildren(
339
+ graph: SceneGraph,
340
+ instanceId: string,
341
+ componentId: string,
342
+ mode: NodeCloneMode = 'deep'
343
+ ): void {
344
+ const instance = graph.nodes.get(instanceId)
345
+ const component = graph.nodes.get(componentId)
346
+ if (!instance || !component || instance.type !== 'INSTANCE') return
347
+ cloneChildrenWithMapping(graph, componentId, instanceId, mode)
348
+ }
349
+
350
+ export function swapInstanceComponent(
351
+ graph: SceneGraph,
352
+ instanceId: string,
353
+ componentId: string
354
+ ): void {
355
+ const instance = graph.nodes.get(instanceId)
356
+ const component = graph.nodes.get(componentId)
357
+ if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return
358
+
359
+ const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined
360
+ const updates: Partial<SceneNode> = { componentId }
361
+ for (const key of INSTANCE_SYNC_PROPS) {
362
+ if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key)) continue
363
+ copyProp(updates, component, key)
364
+ }
365
+
366
+ if (!previousComponent || instance.name === previousComponent.name) updates.name = component.name
367
+
368
+ const childIds = Array.from(instance.childIds)
369
+ for (const childId of childIds) graph.deleteNode(childId)
370
+ graph.updateNode(instanceId, updates)
371
+ cloneChildrenWithMapping(graph, componentId, instanceId)
372
+ }
373
+
374
+ const syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()
375
+
376
+ export function syncInstances(graph: SceneGraph, componentId: string): void {
377
+ const component = graph.nodes.get(componentId)
378
+ if (component?.type !== 'COMPONENT') return
379
+ let syncing = syncingComponentsByGraph.get(graph)
380
+ if (!syncing) {
381
+ syncing = new Set()
382
+ syncingComponentsByGraph.set(graph, syncing)
383
+ }
384
+ if (syncing.has(componentId)) return
385
+ syncing.add(componentId)
386
+ 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)
392
+ }
393
+ syncChildren(graph, component.id, instance.id, instance.instanceOverrides)
394
+ }
395
+ } finally {
396
+ syncing.delete(componentId)
397
+ }
398
+ }
399
+
400
+ export function detachInstance(graph: SceneGraph, instanceId: string): void {
401
+ const node = graph.nodes.get(instanceId)
402
+ if (node?.type !== 'INSTANCE') return
403
+ if (node.componentId) {
404
+ graph.instanceIndex.get(node.componentId)?.delete(instanceId)
405
+ }
406
+ node.type = 'FRAME'
407
+ node.componentId = null
408
+ clearInstanceOverrides(node.instanceOverrides)
409
+ }
410
+
411
+ export function getMainComponent(graph: SceneGraph, instanceId: string): SceneNode | undefined {
412
+ const node = graph.nodes.get(instanceId)
413
+ if (!node?.componentId) return undefined
414
+ return graph.nodes.get(node.componentId)
415
+ }
416
+
417
+ export function getInstances(graph: SceneGraph, componentId: string): SceneNode[] {
418
+ const ids = graph.instanceIndex.get(componentId)
419
+ if (!ids) return []
420
+ const instances: SceneNode[] = []
421
+ for (const id of ids) {
422
+ const node = graph.nodes.get(id)
423
+ if (node) instances.push(node)
424
+ }
425
+ return instances
426
+ }
427
+
428
+ /** Nearest INSTANCE at or above `nodeId` — self, parent, grandparent, etc. */
429
+ export function findInstanceAncestor(graph: SceneGraph, nodeId: string): SceneNode | undefined {
430
+ let current = graph.nodes.get(nodeId)
431
+ while (current) {
432
+ if (current.type === 'INSTANCE') return current
433
+ current = current.parentId ? graph.nodes.get(current.parentId) : undefined
434
+ }
435
+ return undefined
436
+ }
437
+
438
+ /**
439
+ * True when a node field is protected from instance synchronization.
440
+ */
441
+ export function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: string): boolean {
442
+ const instance = findInstanceAncestor(graph, nodeId)
443
+ if (!instance) return false
444
+ return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
445
+ }
446
+
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
+ export function recordInstanceOverride(
464
+ graph: SceneGraph,
465
+ nodeId: string,
466
+ fields: Iterable<string>
467
+ ): void {
468
+ const instance = findInstanceAncestor(graph, nodeId)
469
+ if (!instance) return
470
+
471
+ const relevant = [...fields].filter((field) =>
472
+ (INSTANCE_SYNC_FIELDS as readonly string[]).includes(field)
473
+ )
474
+
475
+ if (relevant.length === 0) return
476
+
477
+ for (const field of relevant)
478
+ setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
479
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
480
+ }