@pairdraw/scene-graph 0.18.0 → 0.19.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 (181) hide show
  1. package/dist/components/index.d.ts +2 -2
  2. package/dist/components/index.js +2 -2
  3. package/dist/components/properties.d.ts +6 -1
  4. package/dist/components/properties.d.ts.map +1 -1
  5. package/dist/components/properties.js +14 -3
  6. package/dist/components/properties.js.map +1 -1
  7. package/dist/copy.d.ts.map +1 -1
  8. package/dist/copy.js +1 -0
  9. package/dist/copy.js.map +1 -1
  10. package/dist/css/gradient.d.ts +23 -0
  11. package/dist/css/gradient.d.ts.map +1 -0
  12. package/dist/css/gradient.js +404 -0
  13. package/dist/css/gradient.js.map +1 -0
  14. package/dist/css/index.d.ts +2 -1
  15. package/dist/css/index.js +2 -1
  16. package/dist/css/shadows.d.ts.map +1 -1
  17. package/dist/css/shadows.js +2 -13
  18. package/dist/css/shadows.js.map +1 -1
  19. package/dist/css/values.js +24 -1
  20. package/dist/css/values.js.map +1 -1
  21. package/dist/font-style.d.ts +2 -1
  22. package/dist/font-style.d.ts.map +1 -1
  23. package/dist/font-style.js +31 -6
  24. package/dist/font-style.js.map +1 -1
  25. package/dist/geometry.d.ts +10 -1
  26. package/dist/geometry.d.ts.map +1 -1
  27. package/dist/geometry.js +21 -6
  28. package/dist/geometry.js.map +1 -1
  29. package/dist/graph.d.ts +49 -3
  30. package/dist/graph.d.ts.map +1 -1
  31. package/dist/graph.js +179 -17
  32. package/dist/graph.js.map +1 -1
  33. package/dist/hit-test.d.ts +3 -1
  34. package/dist/hit-test.d.ts.map +1 -1
  35. package/dist/hit-test.js +38 -23
  36. package/dist/hit-test.js.map +1 -1
  37. package/dist/icons/index.d.ts +2 -2
  38. package/dist/icons/index.js +2 -2
  39. package/dist/icons/model.d.ts +8 -2
  40. package/dist/icons/model.d.ts.map +1 -1
  41. package/dist/icons/model.js +10 -1
  42. package/dist/icons/model.js.map +1 -1
  43. package/dist/index.d.ts +2 -2
  44. package/dist/instances/assignments.js +40 -6
  45. package/dist/instances/assignments.js.map +1 -1
  46. package/dist/instances/fields.d.ts +2 -2
  47. package/dist/instances/fields.d.ts.map +1 -1
  48. package/dist/instances/fields.js +18 -1
  49. package/dist/instances/fields.js.map +1 -1
  50. package/dist/instances/index.d.ts +38 -2
  51. package/dist/instances/index.d.ts.map +1 -1
  52. package/dist/instances/index.js +134 -15
  53. package/dist/instances/index.js.map +1 -1
  54. package/dist/instances/overrides.d.ts +10 -1
  55. package/dist/instances/overrides.d.ts.map +1 -1
  56. package/dist/instances/overrides.js +28 -2
  57. package/dist/instances/overrides.js.map +1 -1
  58. package/dist/instances/placement.js +1 -1
  59. package/dist/instances/placement.js.map +1 -1
  60. package/dist/instances/swap-overrides.js +94 -0
  61. package/dist/instances/swap-overrides.js.map +1 -0
  62. package/dist/instances/sync.js +90 -12
  63. package/dist/instances/sync.js.map +1 -1
  64. package/dist/layout/draw-order.d.ts +11 -0
  65. package/dist/layout/draw-order.d.ts.map +1 -0
  66. package/dist/layout/draw-order.js +14 -0
  67. package/dist/layout/draw-order.js.map +1 -0
  68. package/dist/layout/index.d.ts +2 -1
  69. package/dist/layout/index.js +2 -1
  70. package/dist/node-defaults.d.ts +11 -1
  71. package/dist/node-defaults.d.ts.map +1 -1
  72. package/dist/node-defaults.js +16 -1
  73. package/dist/node-defaults.js.map +1 -1
  74. package/dist/order-keys.d.ts +3 -1
  75. package/dist/order-keys.d.ts.map +1 -1
  76. package/dist/order-keys.js +6 -1
  77. package/dist/order-keys.js.map +1 -1
  78. package/dist/resize.d.ts +29 -9
  79. package/dist/resize.d.ts.map +1 -1
  80. package/dist/resize.js +95 -62
  81. package/dist/resize.js.map +1 -1
  82. package/dist/shared-styles.d.ts.map +1 -1
  83. package/dist/shared-styles.js +1 -8
  84. package/dist/shared-styles.js.map +1 -1
  85. package/dist/slots/authoring.d.ts +3 -2
  86. package/dist/slots/authoring.d.ts.map +1 -1
  87. package/dist/slots/authoring.js +5 -3
  88. package/dist/slots/authoring.js.map +1 -1
  89. package/dist/slots/content.d.ts.map +1 -1
  90. package/dist/slots/content.js +4 -1
  91. package/dist/slots/content.js.map +1 -1
  92. package/dist/source-metadata.d.ts +4 -2
  93. package/dist/source-metadata.d.ts.map +1 -1
  94. package/dist/source-metadata.js +10 -3
  95. package/dist/source-metadata.js.map +1 -1
  96. package/dist/strokes.d.ts +39 -0
  97. package/dist/strokes.d.ts.map +1 -0
  98. package/dist/strokes.js +104 -0
  99. package/dist/strokes.js.map +1 -0
  100. package/dist/text/direction.d.ts +6 -2
  101. package/dist/text/direction.d.ts.map +1 -1
  102. package/dist/text/direction.js +2 -1
  103. package/dist/text/direction.js.map +1 -1
  104. package/dist/text/index.d.ts +3 -3
  105. package/dist/text/index.js +3 -3
  106. package/dist/text/lengths.d.ts +6 -1
  107. package/dist/text/lengths.d.ts.map +1 -1
  108. package/dist/text/lengths.js +10 -1
  109. package/dist/text/lengths.js.map +1 -1
  110. package/dist/text/overflow.d.ts +22 -6
  111. package/dist/text/overflow.d.ts.map +1 -1
  112. package/dist/text/overflow.js +24 -6
  113. package/dist/text/overflow.js.map +1 -1
  114. package/dist/transfer/nodes.js +9 -5
  115. package/dist/transfer/nodes.js.map +1 -1
  116. package/dist/types.d.ts +18 -2
  117. package/dist/types.d.ts.map +1 -1
  118. package/dist/types.js.map +1 -1
  119. package/dist/undo.d.ts +36 -1
  120. package/dist/undo.d.ts.map +1 -1
  121. package/dist/undo.js +52 -2
  122. package/dist/undo.js.map +1 -1
  123. package/dist/variables/bindings.d.ts +14 -6
  124. package/dist/variables/bindings.d.ts.map +1 -1
  125. package/dist/variables/bindings.js +42 -67
  126. package/dist/variables/bindings.js.map +1 -1
  127. package/dist/variables/formula/signatures.js +1 -1
  128. package/dist/variables/index.d.ts +10 -4
  129. package/dist/variables/index.d.ts.map +1 -1
  130. package/dist/variables/index.js +58 -15
  131. package/dist/variables/index.js.map +1 -1
  132. package/dist/variables/paints.d.ts +101 -0
  133. package/dist/variables/paints.d.ts.map +1 -0
  134. package/dist/variables/paints.js +313 -0
  135. package/dist/variables/paints.js.map +1 -0
  136. package/dist/variables/resolution.d.ts +14 -1
  137. package/dist/variables/resolution.d.ts.map +1 -1
  138. package/dist/variables/resolution.js +44 -4
  139. package/dist/variables/resolution.js.map +1 -1
  140. package/dist/variables/subtree.js +17 -0
  141. package/dist/variables/subtree.js.map +1 -0
  142. package/package.json +6 -1
  143. package/src/components/properties.ts +17 -2
  144. package/src/copy.ts +1 -0
  145. package/src/css/gradient.ts +438 -0
  146. package/src/css/index.ts +1 -0
  147. package/src/css/shadows.ts +2 -18
  148. package/src/css/values.ts +27 -1
  149. package/src/font-style.ts +38 -4
  150. package/src/geometry.ts +25 -6
  151. package/src/graph.ts +207 -17
  152. package/src/hit-test.ts +67 -24
  153. package/src/icons/model.ts +11 -1
  154. package/src/instances/assignments.ts +65 -7
  155. package/src/instances/fields.ts +21 -0
  156. package/src/instances/index.ts +237 -14
  157. package/src/instances/overrides.ts +36 -1
  158. package/src/instances/placement.ts +5 -1
  159. package/src/instances/swap-overrides.ts +123 -0
  160. package/src/instances/sync.ts +139 -12
  161. package/src/layout/draw-order.ts +13 -0
  162. package/src/layout/index.ts +1 -0
  163. package/src/node-defaults.ts +21 -0
  164. package/src/order-keys.ts +6 -0
  165. package/src/resize.ts +133 -69
  166. package/src/shared-styles.ts +1 -3
  167. package/src/slots/authoring.ts +5 -3
  168. package/src/slots/content.ts +4 -1
  169. package/src/source-metadata.ts +18 -3
  170. package/src/strokes.ts +121 -0
  171. package/src/text/direction.ts +7 -5
  172. package/src/text/lengths.ts +10 -0
  173. package/src/text/overflow.ts +30 -7
  174. package/src/transfer/nodes.ts +7 -5
  175. package/src/types.ts +17 -0
  176. package/src/undo.ts +79 -2
  177. package/src/variables/bindings.ts +52 -74
  178. package/src/variables/index.ts +80 -14
  179. package/src/variables/paints.ts +413 -0
  180. package/src/variables/resolution.ts +56 -5
  181. package/src/variables/subtree.ts +15 -0
@@ -1,6 +1,7 @@
1
1
  // What enclosing instances assign the component properties that drive a copy's layers.
2
2
  import type { SceneGraph } from '../graph'
3
3
  import type { ComponentPropertyReferenceField, SceneNode } from '../types'
4
+ import { assignmentOverrideField } from './overrides'
4
5
 
5
6
  /** SLOT_CONTENT is absent because it drives children, which `ownsSlotContent` keeps instead. */
6
7
  const PROPERTY_REFERENCE_FIELDS: Partial<Record<ComponentPropertyReferenceField, string>> = {
@@ -30,22 +31,28 @@ function definesProperty(graph: SceneGraph, instance: SceneNode, propertyId: str
30
31
  .some((definition) => definition.id === propertyId)
31
32
  }
32
33
 
34
+ interface Assignment {
35
+ /** The instance whose assignment it is. */
36
+ instance: SceneNode
37
+ value: string
38
+ }
39
+
33
40
  /**
34
41
  * What the nearest enclosing instance assigns `propertyId`, if any does. An instance assigns its
35
42
  * children, not itself, so the walk starts at the parent. A property id belongs to the component
36
43
  * that defines it, so the walk stops at an instance of that component even when it assigns
37
44
  * nothing; otherwise an outer instance's unrelated property of the same id wins.
38
45
  */
39
- function enclosingAssignment(
46
+ function findEnclosingAssignment(
40
47
  graph: SceneGraph,
41
48
  node: SceneNode,
42
49
  propertyId: string
43
- ): string | undefined {
50
+ ): Assignment | undefined {
44
51
  let current = node.parentId ? graph.nodes.get(node.parentId) : undefined
45
52
  while (current) {
46
53
  if (current.type === 'INSTANCE') {
47
54
  if (Object.hasOwn(current.componentPropertyAssignments, propertyId))
48
- return current.componentPropertyAssignments[propertyId]
55
+ return { instance: current, value: current.componentPropertyAssignments[propertyId] }
49
56
  if (definesProperty(graph, current, propertyId)) return undefined
50
57
  }
51
58
  current = current.parentId ? graph.nodes.get(current.parentId) : undefined
@@ -53,6 +60,55 @@ function enclosingAssignment(
53
60
  return undefined
54
61
  }
55
62
 
63
+ function enclosingAssignment(
64
+ graph: SceneGraph,
65
+ node: SceneNode,
66
+ propertyId: string
67
+ ): string | undefined {
68
+ return findEnclosingAssignment(graph, node, propertyId)?.value
69
+ }
70
+
71
+ /** The instances around `node`, nearest first. */
72
+ function enclosingInstances(graph: SceneGraph, node: SceneNode): SceneNode[] {
73
+ const instances: SceneNode[] = []
74
+ let parent = node.parentId ? graph.nodes.get(node.parentId) : undefined
75
+ while (parent) {
76
+ if (parent.type === 'INSTANCE') instances.push(parent)
77
+ parent = parent.parentId ? graph.nodes.get(parent.parentId) : undefined
78
+ }
79
+ return instances
80
+ }
81
+
82
+ /** The outermost of `instances` that records `field` as an edit of `node`, or -1. */
83
+ function outermostEdit(instances: SceneNode[], node: SceneNode, field: string): number {
84
+ return instances.findLastIndex((instance) =>
85
+ instance.instanceOverrides.descendants.get(node.id)?.has(field)
86
+ )
87
+ }
88
+
89
+ /**
90
+ * Whether a text edit of `layer` outranks the assignment that drives it. As in Figma, the edit
91
+ * made in the outer instance wins, and at the same level the assignment does. An assignment is
92
+ * made where an override of it is recorded, or else by the instance that holds it.
93
+ */
94
+ function textEditOutranks(
95
+ graph: SceneGraph,
96
+ layer: SceneNode,
97
+ propertyId: string,
98
+ assignment: Assignment
99
+ ): boolean {
100
+ const instances = enclosingInstances(graph, layer)
101
+ const textLevel = outermostEdit(instances, layer, 'text')
102
+ if (textLevel < 0) return false
103
+ const overridden = outermostEdit(
104
+ instances,
105
+ assignment.instance,
106
+ assignmentOverrideField(propertyId)
107
+ )
108
+ const assignmentLevel = overridden < 0 ? instances.indexOf(assignment.instance) : overridden
109
+ return textLevel > assignmentLevel
110
+ }
111
+
56
112
  function hasEnclosingAssignment(graph: SceneGraph, node: SceneNode, propertyId: string): boolean {
57
113
  return enclosingAssignment(graph, node, propertyId) !== undefined
58
114
  }
@@ -107,10 +163,12 @@ export function assignedFieldValues(
107
163
  ): Partial<SceneNode> {
108
164
  const values: Partial<SceneNode> = {}
109
165
  for (const reference of compChild.componentPropertyReferences) {
110
- const value = enclosingAssignment(graph, instChild, reference.propertyId)
111
- if (value === undefined) continue
112
- if (reference.field === 'TEXT' && instChild.type === 'TEXT') values.text = value
113
- else if (reference.field === 'VISIBLE') values.visible = value === 'true'
166
+ const assignment = findEnclosingAssignment(graph, instChild, reference.propertyId)
167
+ if (!assignment) continue
168
+ if (reference.field === 'TEXT' && instChild.type === 'TEXT') {
169
+ if (!textEditOutranks(graph, instChild, reference.propertyId, assignment))
170
+ values.text = assignment.value
171
+ } else if (reference.field === 'VISIBLE') values.visible = assignment.value === 'true'
114
172
  }
115
173
  return values
116
174
  }
@@ -37,6 +37,11 @@ export const INSTANCE_SYNC_FIELD_OWNERS: Readonly<Partial<Record<string, string>
37
37
  */
38
38
  export const INSTANCE_FOLLOWED_FIELDS = [
39
39
  ...TRANSFORM_FIELDS,
40
+ // A size limit has no field of its own in the file, so an instance cannot keep one of its own.
41
+ 'minWidth',
42
+ 'maxWidth',
43
+ 'minHeight',
44
+ 'maxHeight',
40
45
  'horizontalConstraint',
41
46
  'verticalConstraint',
42
47
  'layoutPositioning',
@@ -60,6 +65,9 @@ export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = difference(
60
65
  ...STROKE_FIELDS,
61
66
  ...CORNER_FIELDS,
62
67
  ...AUTO_LAYOUT_FIELDS,
68
+ // An instance frame and its component share one alignment in the file, so the instance
69
+ // follows the component's instead of keeping its own.
70
+ 'layoutAlignSelf',
63
71
  'itemReverseZIndex',
64
72
  'gridPosition',
65
73
  'clipsContent',
@@ -88,3 +96,16 @@ export const INSTANCE_SYNC_FIELDS = [
88
96
  ...INSTANCE_OVERRIDE_FIELDS,
89
97
  ...INSTANCE_FOLLOWED_FIELDS
90
98
  ] as const
99
+
100
+ /**
101
+ * Fields an instance frame takes from its component frame, where the file keeps one value for
102
+ * both: a layer inside an instance has no field of its own for them.
103
+ */
104
+ export const INSTANCE_FRAME_FOLLOWED_FIELDS: (keyof SceneNode)[] = [
105
+ 'layoutPositioning',
106
+ 'layoutGrow',
107
+ 'minWidth',
108
+ 'maxWidth',
109
+ 'minHeight',
110
+ 'maxHeight'
111
+ ]
@@ -1,24 +1,38 @@
1
1
  import type { NodeCloneMode } from '../copy'
2
2
  import type { SceneGraph } from '../graph'
3
+ import { shapeGeometryChanges } from '../resize'
3
4
  import { slotScope } from '../slots/content'
4
5
  import { detachOwnedSlotContent, restoreOwnedSlotContent } from '../slots/frames'
6
+ import { changesMoreThanStrokeLines } from '../strokes'
5
7
  import type { SceneNode } from '../types'
8
+ import { applyBoundPaintColorsIn, keepCopyBoundPaints } from '../variables/paints'
6
9
  import { keepOwnContentSize } from './content-size'
7
10
  import { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from './copies'
8
11
  import { canCreateInstance, createsComponentCycle } from './cycles'
9
- import { INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_PROPS } from './fields'
12
+ import {
13
+ INSTANCE_FRAME_FOLLOWED_FIELDS,
14
+ INSTANCE_OVERRIDE_FIELDS,
15
+ INSTANCE_SYNC_PROPS
16
+ } from './fields'
10
17
  import { differingVariableModeCollections } from './modes'
11
18
  import {
19
+ assignmentOverrideField,
20
+ cloneInstanceOverrideState,
12
21
  copiedComponentLayerId,
13
22
  createInstanceOverrideState,
14
23
  getInstanceOverride,
15
24
  hasInstanceOverride as hasNodeInstanceOverride,
25
+ type InstanceOverrideState,
26
+ overriddenAssignmentId,
16
27
  REPLACED_LAYER_OVERRIDE,
17
28
  setInstanceOverride,
18
29
  variableModeOverrideField
19
30
  } from './overrides'
20
31
  import { owningInstance, replacedLayerIn } from './replacements'
32
+ import { walkInstanceSources } from './source-walk'
33
+ import { captureInstanceOverrides, restoreInstanceOverrides } from './swap-overrides'
21
34
  import {
35
+ applySyncedStrokeLines,
22
36
  bindingProtection,
23
37
  cloneChildrenWithMapping,
24
38
  copyProp,
@@ -50,10 +64,21 @@ export {
50
64
 
51
65
  export function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {
52
66
  const props: Partial<SceneNode> = {}
53
- for (const key of INSTANCE_SYNC_PROPS) copyProp(props, component, key)
67
+ // A new instance starts with the fields its component frame lends it, as resyncing one does.
68
+ for (const key of [...INSTANCE_SYNC_PROPS, ...INSTANCE_FRAME_FOLLOWED_FIELDS])
69
+ copyProp(props, component, key)
54
70
  return props
55
71
  }
56
72
 
73
+ /**
74
+ * The name Figma gives a new instance of `component`: its component set's name for a variant,
75
+ * whose own name only says which variant it is, and the component's own name otherwise.
76
+ */
77
+ function instanceComponentName(graph: SceneGraph, component: SceneNode): string {
78
+ const parent = component.parentId ? graph.nodes.get(component.parentId) : undefined
79
+ return parent?.type === 'COMPONENT_SET' ? parent.name : component.name
80
+ }
81
+
57
82
  export function createInstance(
58
83
  graph: SceneGraph,
59
84
  componentId: string,
@@ -66,13 +91,15 @@ export function createInstance(
66
91
 
67
92
  const props: Partial<SceneNode> = {
68
93
  ...copyInstanceComponentProps(component),
69
- name: component.name
94
+ name: instanceComponentName(graph, component)
70
95
  }
71
96
 
72
97
  // The component checked above is the one the instance shows, whatever `overrides` holds.
73
98
  const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })
74
99
 
75
100
  cloneChildrenWithMapping(graph, component.id, instance.id)
101
+ // A copy shows its bound paints in its own context, not as its component's paints hold them.
102
+ applyBoundPaintColorsIn(graph, instance.id)
76
103
 
77
104
  return instance
78
105
  }
@@ -123,13 +150,20 @@ export interface SwapInstanceOptions {
123
150
  * such as preview, keeps names so layer paths stay the same.
124
151
  */
125
152
  keepName?: boolean
153
+ /**
154
+ * Keep the overrides the instance's layers record, matched to the layers of the new component
155
+ * that take their places, as Figma keeps them when a variant changes. A swap that only
156
+ * materializes a layer the caller re-applies itself, such as a pen icon's glyph, skips this:
157
+ * what the placeholder recorded is scaffolding, not a user's edit.
158
+ */
159
+ restoreOverrides?: boolean
126
160
  }
127
161
 
128
162
  export function swapInstanceComponent(
129
163
  graph: SceneGraph,
130
164
  instanceId: string,
131
165
  componentId: string,
132
- { keepName = false }: SwapInstanceOptions = {}
166
+ { keepName = false, restoreOverrides = true }: SwapInstanceOptions = {}
133
167
  ): void {
134
168
  const instance = graph.nodes.get(instanceId)
135
169
  const component = graph.nodes.get(componentId)
@@ -147,20 +181,47 @@ export function swapInstanceComponent(
147
181
  copyProp(updates, source, key)
148
182
  }
149
183
  syncVariableModeFields(instance, source, updates, overridden)
184
+ applySyncedStrokeLines(graph, instance, updates, overridden)
150
185
 
151
- if (!keepName && (!previousComponent || instance.name === previousComponent.name))
152
- updates.name = component.name
186
+ if (
187
+ !keepName &&
188
+ (!previousComponent || instance.name === instanceComponentName(graph, previousComponent))
189
+ )
190
+ updates.name = instanceComponentName(graph, component)
153
191
 
192
+ keepCopyBoundPaints(graph, instance, updates)
154
193
  const childIds = Array.from(instance.childIds)
155
194
  const slotContent = detachOwnedSlotContent(graph, instance)
195
+ swapInstanceLayers(graph, instanceId, componentId, updates, childIds, restoreOverrides)
196
+ restoreOwnedSlotContent(graph, instance, slotContent)
197
+ }
198
+
199
+ /**
200
+ * Replaces the instance's layers with clones of its new component's and gives the recorded
201
+ * overrides back to the layers that take the old ones' places, matched by name path.
202
+ */
203
+ function swapInstanceLayers(
204
+ graph: SceneGraph,
205
+ instanceId: string,
206
+ componentId: string,
207
+ updates: Partial<SceneNode>,
208
+ childIds: string[],
209
+ restoreOverrides: boolean
210
+ ): void {
211
+ // The clones take new IDs, so what was recorded for the removed layers only applies again once
212
+ // it is matched to the layers of the new component that take their places.
213
+ const capturedOverrides = restoreOverrides
214
+ ? captureInstanceOverrides(graph, graph.nodes.get(instanceId) as SceneNode)
215
+ : undefined
156
216
  for (const childId of childIds) {
157
- // The clones take new IDs, so what was recorded for the removed layers would never apply.
158
217
  forgetOverridesOf(graph, childId)
159
218
  graph.deleteNode(childId)
160
219
  }
161
220
  graph.updateNode(instanceId, updates)
162
221
  cloneChildrenWithMapping(graph, componentId, instanceId)
163
- restoreOwnedSlotContent(graph, instance, slotContent)
222
+ applyBoundPaintColorsIn(graph, instanceId)
223
+ const swapped = graph.nodes.get(instanceId)
224
+ if (swapped && capturedOverrides) restoreInstanceOverrides(graph, swapped, capturedOverrides)
164
225
  }
165
226
 
166
227
  const syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()
@@ -215,9 +276,28 @@ function syncInstancesOf(
215
276
  if (isProtectedSyncField(instance, key, protectedField)) continue
216
277
  copyProp(updates, source, key)
217
278
  }
279
+ // The file keeps one value for the instance frame and its component, so the frame takes
280
+ // those the layers inside an instance may not set.
281
+ for (const key of INSTANCE_FRAME_FOLLOWED_FIELDS) {
282
+ if (!isProtectedSyncField(instance, key, protectedField)) copyProp(updates, source, key)
283
+ }
218
284
  // An instance that hugs its layers sizes to what it shows, not to the component.
219
285
  keepOwnContentSize(graph, updates, instance, source)
220
- updateSyncedProps(graph, instance, updates)
286
+ // A size that follows the component invalidates outlines the file saved on the instance;
287
+ // its live box draws them again.
288
+ if (updates.width !== undefined || updates.height !== undefined) {
289
+ Object.assign(
290
+ updates,
291
+ shapeGeometryChanges(
292
+ instance,
293
+ updates.width ?? instance.width,
294
+ updates.height ?? instance.height
295
+ )
296
+ )
297
+ }
298
+ updateSyncedProps(graph, instance, updates, (key) =>
299
+ isProtectedSyncField(instance, key, protectedField)
300
+ )
221
301
  const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)
222
302
  syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)
223
303
  removeLeftoverCopies(graph, context, removals)
@@ -253,12 +333,68 @@ export function retargetCopiedOverrides(
253
333
  export function detachInstance(graph: SceneGraph, instanceId: string): void {
254
334
  const node = graph.nodes.get(instanceId)
255
335
  if (node?.type !== 'INSTANCE') return
336
+ for (const nested of outermostNestedInstances(graph, node))
337
+ adoptNestedOverrides(graph, node, nested)
256
338
  // Through `updateNode`, so the instance index, change observers, and undo recorders see it.
257
339
  graph.updateNode(instanceId, {
258
340
  type: 'FRAME',
259
341
  componentId: null,
260
342
  instanceOverrides: createInstanceOverrideState()
261
343
  })
344
+ // Its mirrored layers stand on their own: a component child id would name a layer of another
345
+ // node, which the format never stores and a later sync would read as a link back. A nested
346
+ // instance is not a mirror and keeps its own links, which its overrides are written through.
347
+ const detachLinks = (parentId: string): void => {
348
+ for (const child of graph.getChildren(parentId)) {
349
+ if (child.type === 'INSTANCE') continue
350
+ if (child.componentId) graph.updateNode(child.id, { componentId: null })
351
+ detachLinks(child.id)
352
+ }
353
+ }
354
+ detachLinks(instanceId)
355
+ }
356
+
357
+ // A swap's bookkeeping belongs to the instance enclosing the swapped one, never to the swapped one.
358
+ const OWNER_ONLY_FIELDS = new Set(['componentId', 'sourceComponentId'])
359
+
360
+ function outermostNestedInstances(graph: SceneGraph, instance: SceneNode): SceneNode[] {
361
+ return graph
362
+ .getChildren(instance.id)
363
+ .flatMap((child) =>
364
+ child.type === 'INSTANCE' ? [child] : outermostNestedInstances(graph, child)
365
+ )
366
+ }
367
+
368
+ /**
369
+ * An instance a detached one holds stands on its own once that one is a frame, and so must what
370
+ * makes it differ from its component. Cloned in, it kept the overrides of the instance it copies,
371
+ * under that instance's layers; those, and the ones the detached instance recorded on its layers,
372
+ * now go under its own.
373
+ */
374
+ function adoptNestedOverrides(graph: SceneGraph, detached: SceneNode, nested: SceneNode): void {
375
+ const ownLayer = new Map<string, string>()
376
+ walkInstanceSources(graph, nested, (source, target) => {
377
+ ownLayer.set(source.id, target.id)
378
+ return true
379
+ })
380
+ const { self, descendants: kept } = cloneInstanceOverrideState(nested.instanceOverrides)
381
+ const outer = cloneInstanceOverrideState(detached.instanceOverrides).descendants
382
+ const descendants = new Map<string, Map<string, unknown>>()
383
+ const claim = (layerId: string, fields: Map<string, unknown>): void => {
384
+ const merged = descendants.get(layerId)
385
+ if (!merged) descendants.set(layerId, fields)
386
+ else for (const [field, value] of fields) merged.set(field, value)
387
+ }
388
+ // What was recorded on its own layers is more recent than what it copied, so it is laid on top.
389
+ for (const [layerId, fields] of kept)
390
+ if (ownLayer.has(layerId)) claim(ownLayer.get(layerId) ?? layerId, fields)
391
+ for (const [layerId, fields] of kept) if (!ownLayer.has(layerId)) claim(layerId, fields)
392
+ for (const [layerId, fields] of outer) {
393
+ if (layerId === nested.id) {
394
+ for (const [field, value] of fields) if (!OWNER_ONLY_FIELDS.has(field)) self.set(field, value)
395
+ } else if (graph.isDescendant(layerId, nested.id)) claim(layerId, fields)
396
+ }
397
+ graph.updateNode(nested.id, { instanceOverrides: { self, descendants } })
262
398
  }
263
399
 
264
400
  export function getMainComponent(graph: SceneGraph, instanceId: string): SceneNode | undefined {
@@ -288,6 +424,14 @@ export function findInstanceAncestor(graph: SceneGraph, nodeId: string): SceneNo
288
424
  return undefined
289
425
  }
290
426
 
427
+ /**
428
+ * Whether Figma lets this layer take a size of its own: a layer inside an instance shows its
429
+ * component's size and cannot be resized, while an instance nested in another may be.
430
+ */
431
+ export function takesOwnSize(graph: SceneGraph, node: SceneNode): boolean {
432
+ return node.type === 'INSTANCE' || !node.parentId || !findInstanceAncestor(graph, node.parentId)
433
+ }
434
+
291
435
  /**
292
436
  * True when a node field is protected from instance synchronization.
293
437
  */
@@ -330,6 +474,76 @@ function overrideFieldsOf(
330
474
  ]
331
475
  }
332
476
 
477
+ /**
478
+ * The instance above `instanceId` that records an assignment made through it: an assignment of a
479
+ * nested instance's property is an edit of the instance it sits in, not of the nested instance.
480
+ */
481
+ export function assignmentOverrideOwner(
482
+ graph: SceneGraph,
483
+ instanceId: string
484
+ ): SceneNode | undefined {
485
+ const parentId = graph.nodes.get(instanceId)?.parentId
486
+ return parentId ? findInstanceAncestor(graph, parentId) : undefined
487
+ }
488
+
489
+ /** The overrides an assignment edit writes on the instance above it, for undo to restore. */
490
+ export interface AssignmentOverrideState {
491
+ ownerId: string
492
+ overrides: InstanceOverrideState
493
+ }
494
+
495
+ export function takeAssignmentOverrideState(
496
+ graph: SceneGraph,
497
+ instanceId: string
498
+ ): AssignmentOverrideState | undefined {
499
+ const owner = assignmentOverrideOwner(graph, instanceId)
500
+ return owner
501
+ ? { ownerId: owner.id, overrides: cloneInstanceOverrideState(owner.instanceOverrides) }
502
+ : undefined
503
+ }
504
+
505
+ export function restoreAssignmentOverrideState(
506
+ graph: SceneGraph,
507
+ state: AssignmentOverrideState
508
+ ): void {
509
+ graph.updateNode(state.ownerId, {
510
+ instanceOverrides: cloneInstanceOverrideState(state.overrides)
511
+ })
512
+ }
513
+
514
+ /**
515
+ * Records that an instance assigned one of its component properties, as an edit of the instance
516
+ * above it: the assignment is made through the outer instance, so a text override of the same
517
+ * level does not outrank it. A top-level instance has no outer instance to record it on.
518
+ */
519
+ export function recordAssignmentOverride(
520
+ graph: SceneGraph,
521
+ instanceId: string,
522
+ propertyId: string,
523
+ value: string
524
+ ): void {
525
+ const outer = assignmentOverrideOwner(graph, instanceId)
526
+ if (!outer) return
527
+ setInstanceOverride(
528
+ outer.instanceOverrides,
529
+ outer.id,
530
+ instanceId,
531
+ assignmentOverrideField(propertyId),
532
+ value
533
+ )
534
+ graph.updateNode(outer.id, { instanceOverrides: outer.instanceOverrides })
535
+ }
536
+
537
+ /**
538
+ * The fields `changes` overrides on an instance layer. New strokes that change only what the
539
+ * layer's line fields say override those fields, not the paints (`changesMoreThanStrokeLines`).
540
+ */
541
+ export function instanceOverrideFields(node: SceneNode, changes: Partial<SceneNode>): string[] {
542
+ const fields = Object.keys(changes)
543
+ if (!changes.strokes || changesMoreThanStrokeLines(node, changes)) return fields
544
+ return fields.filter((field) => field !== 'strokes')
545
+ }
546
+
333
547
  export function recordInstanceOverride(
334
548
  graph: SceneGraph,
335
549
  nodeId: string,
@@ -342,14 +556,23 @@ export function recordInstanceOverride(
342
556
  graph,
343
557
  instance,
344
558
  nodeId,
345
- [...fields].filter((field) => (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field))
559
+ [...fields].filter(
560
+ (field) =>
561
+ (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field) ||
562
+ overriddenAssignmentId(field) !== null
563
+ )
346
564
  )
347
565
 
348
- if (relevant.length === 0) return
566
+ const added = relevant.filter(
567
+ (field) => !hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
568
+ )
569
+ if (added.length === 0) return
349
570
 
350
- for (const field of relevant)
351
- setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
352
- graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
571
+ // A new state rather than an edit of the old one, so a preview that captured the old state
572
+ // puts it back on cancel.
573
+ const overrides = cloneInstanceOverrideState(instance.instanceOverrides)
574
+ for (const field of added) setInstanceOverride(overrides, instance.id, nodeId, field)
575
+ graph.updateNode(instance.id, { instanceOverrides: overrides })
353
576
  }
354
577
 
355
578
  /** Every layer at or below `rootId`. */
@@ -39,6 +39,23 @@ export function overriddenVariableModeCollection(field: InstanceOverrideField):
39
39
  : null
40
40
  }
41
41
 
42
+ const ASSIGNMENT_OVERRIDE_PREFIX = 'componentPropertyAssignments/'
43
+
44
+ /**
45
+ * The override field that claims a nested instance's assignment of `propertyId`, which keeps
46
+ * that assignment through a sync of the instance that makes it.
47
+ */
48
+ export function assignmentOverrideField(propertyId: string): InstanceOverrideField {
49
+ return `${ASSIGNMENT_OVERRIDE_PREFIX}${propertyId}`
50
+ }
51
+
52
+ /** The property an assignment override field claims, or null for an override of anything else. */
53
+ export function overriddenAssignmentId(field: InstanceOverrideField): string | null {
54
+ return field.startsWith(ASSIGNMENT_OVERRIDE_PREFIX)
55
+ ? field.slice(ASSIGNMENT_OVERRIDE_PREFIX.length)
56
+ : null
57
+ }
58
+
42
59
  /**
43
60
  * The override field that marks a layer of an instance as one put in place of a component's
44
61
  * layer, recorded by the nearest instance above it. Its value is the layer it replaces, which
@@ -140,6 +157,8 @@ export function cloneInstanceOverrideState(state: InstanceOverrideState): Instan
140
157
  export interface InstanceOverrideReferenceMapper {
141
158
  node: (id: string) => string
142
159
  variable: (id: string) => string
160
+ collection?: (id: string) => string | undefined
161
+ property?: (id: string) => string | undefined
143
162
  }
144
163
 
145
164
  /** Remap runtime identities only; ordinary strings and source-format payloads stay opaque. */
@@ -153,8 +172,24 @@ export function remapInstanceOverrideState(
153
172
  if (overriddenBindingField(field) !== null) return references.variable(value)
154
173
  return value
155
174
  }
175
+ const remapField = (field: string): string | undefined => {
176
+ const property = overriddenAssignmentId(field)
177
+ if (property !== null && references.property) {
178
+ const mapped = references.property(property)
179
+ return mapped === undefined ? undefined : assignmentOverrideField(mapped)
180
+ }
181
+ const collection = overriddenVariableModeCollection(field)
182
+ if (collection === null || !references.collection) return field
183
+ const mapped = references.collection(collection)
184
+ return mapped === undefined ? undefined : variableModeOverrideField(mapped)
185
+ }
156
186
  const fields = (entries: ReadonlyMap<string, unknown>) =>
157
- new Map([...entries].map(([field, value]) => [field, remapValue(field, value)]))
187
+ new Map(
188
+ [...entries].flatMap(([field, value]) => {
189
+ const mapped = remapField(field)
190
+ return mapped === undefined ? [] : [[mapped, remapValue(field, value)] as const]
191
+ })
192
+ )
158
193
  const descendants = new Map<string, Map<string, unknown>>()
159
194
  for (const [id, entries] of state.descendants) {
160
195
  const mapped = references.node(id)
@@ -17,7 +17,11 @@ export function placedByConstraints(
17
17
  ): SceneNode {
18
18
  const before = { width: compParent.width * factor, height: compParent.height * factor }
19
19
  if (before.width === instParent.width && before.height === instParent.height) return source
20
- const rect = layoutConstrainedChildRect(
20
+ const {
21
+ flipsX: _flipsX,
22
+ flipsY: _flipsY,
23
+ ...rect
24
+ } = layoutConstrainedChildRect(
21
25
  source,
22
26
  before,
23
27
  instParent,