@pairdraw/scene-graph 0.21.1 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/constants.d.ts +10 -4
  2. package/dist/constants.d.ts.map +1 -1
  3. package/dist/constants.js +60 -2
  4. package/dist/constants.js.map +1 -1
  5. package/dist/copy.js +7 -0
  6. package/dist/copy.js.map +1 -1
  7. package/dist/effects.d.ts +9 -1
  8. package/dist/effects.d.ts.map +1 -1
  9. package/dist/effects.js +10 -1
  10. package/dist/effects.js.map +1 -1
  11. package/dist/fields/layout.d.ts +1 -1
  12. package/dist/fields/layout.d.ts.map +1 -1
  13. package/dist/fields/layout.js +3 -1
  14. package/dist/fields/layout.js.map +1 -1
  15. package/dist/geometry.d.ts.map +1 -1
  16. package/dist/geometry.js +3 -3
  17. package/dist/geometry.js.map +1 -1
  18. package/dist/graph.d.ts +4 -1
  19. package/dist/graph.d.ts.map +1 -1
  20. package/dist/graph.js +9 -0
  21. package/dist/graph.js.map +1 -1
  22. package/dist/hit-test.d.ts.map +1 -1
  23. package/dist/hit-test.js +1 -1
  24. package/dist/hit-test.js.map +1 -1
  25. package/dist/images.d.ts +17 -1
  26. package/dist/images.d.ts.map +1 -1
  27. package/dist/images.js +41 -1
  28. package/dist/images.js.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/instances/fields.d.ts +5 -3
  31. package/dist/instances/fields.d.ts.map +1 -1
  32. package/dist/instances/fields.js +5 -0
  33. package/dist/instances/fields.js.map +1 -1
  34. package/dist/instances/index.d.ts +2 -2
  35. package/dist/instances/index.d.ts.map +1 -1
  36. package/dist/instances/index.js +8 -3
  37. package/dist/instances/index.js.map +1 -1
  38. package/dist/instances/placement.js +1 -1
  39. package/dist/instances/placement.js.map +1 -1
  40. package/dist/instances/sync.js +24 -5
  41. package/dist/instances/sync.js.map +1 -1
  42. package/dist/node-defaults.d.ts.map +1 -1
  43. package/dist/node-defaults.js +4 -0
  44. package/dist/node-defaults.js.map +1 -1
  45. package/dist/resize.d.ts +9 -2
  46. package/dist/resize.d.ts.map +1 -1
  47. package/dist/resize.js +20 -8
  48. package/dist/resize.js.map +1 -1
  49. package/dist/slots/content.d.ts +46 -1
  50. package/dist/slots/content.d.ts.map +1 -1
  51. package/dist/slots/content.js +146 -2
  52. package/dist/slots/content.js.map +1 -1
  53. package/dist/slots/index.d.ts +3 -2
  54. package/dist/slots/index.js +3 -2
  55. package/dist/slots/owners.d.ts +17 -0
  56. package/dist/slots/owners.d.ts.map +1 -0
  57. package/dist/slots/owners.js +39 -0
  58. package/dist/slots/owners.js.map +1 -0
  59. package/dist/types.d.ts +115 -5
  60. package/dist/types.d.ts.map +1 -1
  61. package/dist/types.js.map +1 -1
  62. package/dist/variables/bindings.d.ts +9 -3
  63. package/dist/variables/bindings.d.ts.map +1 -1
  64. package/dist/variables/bindings.js +128 -26
  65. package/dist/variables/bindings.js.map +1 -1
  66. package/dist/variables/fields.d.ts +20 -1
  67. package/dist/variables/fields.d.ts.map +1 -1
  68. package/dist/variables/fields.js +29 -3
  69. package/dist/variables/fields.js.map +1 -1
  70. package/dist/variables/index.d.ts +3 -3
  71. package/dist/variables/index.d.ts.map +1 -1
  72. package/dist/variables/index.js +25 -4
  73. package/dist/variables/index.js.map +1 -1
  74. package/dist/variant-properties.d.ts +7 -2
  75. package/dist/variant-properties.d.ts.map +1 -1
  76. package/dist/variant-properties.js +35 -3
  77. package/dist/variant-properties.js.map +1 -1
  78. package/package.json +1 -1
  79. package/src/constants.ts +32 -3
  80. package/src/copy.ts +7 -0
  81. package/src/effects.ts +21 -0
  82. package/src/fields/layout.ts +3 -1
  83. package/src/geometry.ts +5 -3
  84. package/src/graph.ts +13 -0
  85. package/src/hit-test.ts +7 -1
  86. package/src/images.ts +61 -2
  87. package/src/instances/fields.ts +5 -0
  88. package/src/instances/index.ts +10 -1
  89. package/src/instances/placement.ts +2 -1
  90. package/src/instances/sync.ts +38 -5
  91. package/src/node-defaults.ts +4 -0
  92. package/src/resize.ts +44 -6
  93. package/src/slots/content.ts +208 -1
  94. package/src/slots/index.ts +1 -0
  95. package/src/slots/owners.ts +45 -0
  96. package/src/types.ts +207 -3
  97. package/src/variables/bindings.ts +155 -33
  98. package/src/variables/fields.ts +41 -2
  99. package/src/variables/index.ts +40 -1
  100. package/src/variant-properties.ts +36 -2
@@ -31,7 +31,9 @@ export const PARENT_LAYOUT_FIELDS = [
31
31
  'layoutPositioning',
32
32
  'layoutGrow',
33
33
  'layoutAlignSelf',
34
- 'gridPosition'
34
+ 'gridPosition',
35
+ 'gridChildHorizontalAlign',
36
+ 'gridChildVerticalAlign'
35
37
  ] as const satisfies readonly (keyof SceneNode)[]
36
38
 
37
39
  /** Size limits a layer keeps however it is resized. */
package/src/geometry.ts CHANGED
@@ -582,10 +582,12 @@ function collectDescendantVisualBounds(
582
582
  nodeId: string,
583
583
  getNode: (id: string) => VisualBoundsNode | undefined,
584
584
  getAbsolutePosition: (id: string) => Vector,
585
- clip: VisualBounds | null = null
585
+ clip: VisualBounds | null = null,
586
+ isRoot = false
586
587
  ): VisualBounds | null {
587
588
  const node = getNode(nodeId)
588
- if (!node?.visible) return null
589
+ // Slices define an export box only when targeted directly; as descendants they add no visuals.
590
+ if (!node?.visible || (!isRoot && node.type === 'SLICE')) return null
589
591
 
590
592
  const own = nodeVisualBounds(node, getAbsolutePosition)
591
593
  let bounds = clip ? intersectVisualBounds(own, clip) : own
@@ -625,7 +627,7 @@ export function computeDescendantVisualBounds(
625
627
  for (const nodeId of nodeIds) {
626
628
  bounds = unionVisualBounds(
627
629
  bounds,
628
- collectDescendantVisualBounds(nodeId, getNode, getAbsolutePosition)
630
+ collectDescendantVisualBounds(nodeId, getNode, getAbsolutePosition, null, true)
629
631
  )
630
632
  }
631
633
  return bounds
package/src/graph.ts CHANGED
@@ -37,6 +37,7 @@ import { markSourceFieldsEdited } from './source-metadata'
37
37
  import { strokeLineChanges } from './strokes'
38
38
  import { invalidateTextCaches } from './text/picture'
39
39
  import type {
40
+ AnnotationCategory,
40
41
  DocumentColorSpace,
41
42
  DocumentKind,
42
43
  EnabledLibraryBinding,
@@ -76,6 +77,8 @@ export class SceneGraph {
76
77
  documentColorSpace: DocumentColorSpace = 'srgb'
77
78
  documentKind: DocumentKind = 'design'
78
79
  enabledLibraries = new Map<string, EnabledLibraryBinding>()
80
+ /** Dev Mode annotation categories, keyed by their archive id. */
81
+ annotationCategories = new Map<string, AnnotationCategory>()
79
82
  readonly emitter = new BufferedSceneEmitter()
80
83
  private absPosCache = new Map<string, Vector>()
81
84
  private readonly scopeDepths: Record<GraphScope, number> = {
@@ -504,9 +507,16 @@ export class SceneGraph {
504
507
  return this.emitter.batch(action)
505
508
  }
506
509
 
510
+ private assertParentAcceptsChildren(parent: SceneNode): void {
511
+ if (parent.type === 'SLICE') {
512
+ throw new Error('Cannot add a layer to a slice: a slice is an export region.')
513
+ }
514
+ }
515
+
507
516
  createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {
508
517
  const parent = this.nodes.get(parentId)
509
518
  if (!parent) throw new Error(`Parent "${parentId}" does not exist`)
519
+ this.assertParentAcceptsChildren(parent)
510
520
  const node = createDefaultNode(
511
521
  () => this.generateEntityId(),
512
522
  type,
@@ -529,6 +539,7 @@ export class SceneGraph {
529
539
  if (parentId === id) throw new Error(`Node "${id}" cannot be its own parent`)
530
540
  const parent = parentId === null ? undefined : this.nodes.get(parentId)
531
541
  if (parentId !== null && !parent) throw new Error(`Parent "${parentId}" does not exist`)
542
+ if (parent) this.assertParentAcceptsChildren(parent)
532
543
  const node = createDefaultNode(
533
544
  () => id,
534
545
  type,
@@ -805,6 +816,7 @@ export class SceneGraph {
805
816
  const oldParent = node.parentId ? this.nodes.get(node.parentId) : undefined
806
817
  const newParent = this.nodes.get(newParentId)
807
818
  if (!newParent) return
819
+ this.assertParentAcceptsChildren(newParent)
808
820
  if (node.parentId === newParentId) return
809
821
 
810
822
  // An instance inside the component it draws would sync itself forever, so Figma keeps it
@@ -859,6 +871,7 @@ export class SceneGraph {
859
871
  const node = this.nodes.get(childId)
860
872
  const newParent = this.nodes.get(parentId)
861
873
  if (!node || !newParent || this.isDescendant(parentId, childId)) return
874
+ this.assertParentAcceptsChildren(newParent)
862
875
  const previousParentId = node.parentId
863
876
  const oldParent = previousParentId ? this.nodes.get(previousParentId) : undefined
864
877
  this.willChangeNode(node)
package/src/hit-test.ts CHANGED
@@ -28,7 +28,13 @@ const OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])
28
28
  * except a main component's, which always counts, and an instance's when the click is a plain one.
29
29
  */
30
30
  function takesEmptyArea(graph: SceneGraph, node: SceneNode, instanceBodies: boolean): boolean {
31
- if (node.type === 'COMPONENT' || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true
31
+ if (
32
+ node.type === 'COMPONENT' ||
33
+ node.type === 'SLICE' ||
34
+ showsPaint(node) ||
35
+ ownsItsEmptyArea(graph, node)
36
+ )
37
+ return true
32
38
  return instanceBodies && node.type === 'INSTANCE'
33
39
  }
34
40
 
package/src/images.ts CHANGED
@@ -2,7 +2,9 @@ import { sha1 } from '@noble/hashes/legacy.js'
2
2
  import { bytesToHex } from '@noble/hashes/utils.js'
3
3
  import { imageSize as readImageHeader } from 'image-size'
4
4
 
5
- import type { Matrix, Size } from './primitives'
5
+ import Matrix from './matrix'
6
+ import type { Matrix as MatrixType, Size } from './primitives'
7
+ import type { Fill, SceneNode } from './types'
6
8
 
7
9
  /**
8
10
  * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,
@@ -13,6 +15,63 @@ export function computeImageHash(data: Uint8Array): string {
13
15
  return bytesToHex(sha1(data))
14
16
  }
15
17
 
18
+ /**
19
+ * Maps `img`'s pixels onto `node` as `fill` places them. `size` is the image's own size when `img`
20
+ * is a downscaled preview, so a tile keeps its size. A crop places the image by its transform;
21
+ * Fill, Fit and Tile ignore it, as Figma does, and turn the image by `imageRotation` first.
22
+ */
23
+ export function makeImageFillLocalMatrix(
24
+ fill: Fill,
25
+ node: SceneNode,
26
+ imgW: number,
27
+ imgH: number,
28
+ size: { width: number; height: number } = { width: imgW, height: imgH }
29
+ ) {
30
+ const scaleMode = fill.imageScaleMode ?? 'FILL'
31
+ if (scaleMode === 'CROP') {
32
+ // Figma turns the crop by its transform alone: `rotation` is automatic for a crop, so an
33
+ // unset transform stretches the image to the layer however the paint's rotation reads.
34
+ const t = fill.imageTransform
35
+ const inverse = t && Matrix.invert([t.m00, t.m01, t.m02, t.m10, t.m11, t.m12, 0, 0, 1])
36
+ if (inverse)
37
+ return Matrix.multiply(
38
+ Matrix.scaled(node.width, node.height),
39
+ inverse,
40
+ Matrix.scaled(1 / imgW, 1 / imgH)
41
+ )
42
+ return Matrix.scaled(node.width / imgW, node.height / imgH)
43
+ }
44
+
45
+ const radians = ((fill.imageRotation ?? 0) * Math.PI) / 180
46
+ const cos = Math.abs(Math.cos(radians))
47
+ const sin = Math.abs(Math.sin(radians))
48
+ const turnedW = size.width * cos + size.height * sin
49
+ const turnedH = size.width * sin + size.height * cos
50
+ const turned = Matrix.multiply(
51
+ Matrix.translated(turnedW / 2, turnedH / 2),
52
+ Matrix.rotated(radians),
53
+ Matrix.translated(-size.width / 2, -size.height / 2),
54
+ Matrix.scaled(size.width / imgW, size.height / imgH)
55
+ )
56
+ if (scaleMode === 'TILE') {
57
+ const scale = fill.scale && fill.scale > 0 ? fill.scale : 1
58
+ return Matrix.multiply(Matrix.scaled(scale, scale), turned)
59
+ }
60
+ const fit = scaleMode === 'FIT'
61
+ const scale = (fit ? Math.min : Math.max)(node.width / turnedW, node.height / turnedH)
62
+ return Matrix.multiply(
63
+ Matrix.translated((node.width - turnedW * scale) / 2, (node.height - turnedH * scale) / 2),
64
+ Matrix.scaled(scale, scale),
65
+ turned
66
+ )
67
+ }
68
+
69
+ /** An image fill that CSS draws as a background: its data URL and how it repeats. */
70
+ export interface ImagePlacement {
71
+ url: string
72
+ mode: 'CROP' | 'TILE'
73
+ }
74
+
16
75
  export type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif'
17
76
 
18
77
  /** The image types documents store, by the name `image-size` gives each format. */
@@ -105,7 +164,7 @@ export function coverImageTransform(
105
164
  height: number,
106
165
  imageWidth: number,
107
166
  imageHeight: number
108
- ): Matrix {
167
+ ): MatrixType {
109
168
  const scale = Math.max(width / imageWidth, height / imageHeight)
110
169
  const m00 = width / scale / imageWidth
111
170
  const m11 = height / scale / imageHeight
@@ -26,6 +26,10 @@ export const INSTANCE_SYNC_TEXT_PROPS = [
26
26
  /** Fields that belong to another one: overriding the owner keeps them too. */
27
27
  export const INSTANCE_SYNC_FIELD_OWNERS: Readonly<Partial<Record<string, string>>> = {
28
28
  fillStyleId: 'fills',
29
+ strokeStyleId: 'strokes',
30
+ effectStyleId: 'effects',
31
+ textStyleId: 'text',
32
+ gridStyleId: 'layoutGrids',
29
33
  styleRuns: 'text',
30
34
  textParagraphs: 'text'
31
35
  }
@@ -51,6 +55,7 @@ export const INSTANCE_FOLLOWED_FIELDS = [
51
55
  'arcData',
52
56
  'pointCount',
53
57
  'starInnerRadius',
58
+ 'booleanOperation',
54
59
  'shapeWithTextType',
55
60
  'shapeUserHeight',
56
61
  'shapeTruncates'
@@ -1,7 +1,7 @@
1
1
  import type { NodeCloneMode } from '../copy'
2
2
  import type { SceneGraph } from '../graph'
3
3
  import { shapeGeometryChanges } from '../resize'
4
- import { slotScope } from '../slots/content'
4
+ import { claimSlotContent, enclosingSlotScope, slotScope } from '../slots/content'
5
5
  import { detachOwnedSlotContent, restoreOwnedSlotContent } from '../slots/frames'
6
6
  import { changesMoreThanStrokeLines } from '../strokes'
7
7
  import type { SceneNode } from '../types'
@@ -59,6 +59,7 @@ export {
59
59
  export {
60
60
  INSTANCE_FOLLOWED_FIELDS,
61
61
  INSTANCE_OVERRIDE_FIELDS,
62
+ INSTANCE_SYNC_FIELD_OWNERS,
62
63
  INSTANCE_SYNC_FIELDS,
63
64
  INSTANCE_SYNC_PROPS,
64
65
  INSTANCE_SYNC_TEXT_PROPS
@@ -560,6 +561,14 @@ export function recordInstanceOverride(
560
561
  ): void {
561
562
  const instance = findInstanceAncestor(graph, nodeId)
562
563
  if (!instance) return
564
+ // An edit inside a slot makes that frame the instance's own content, as Figma does: from then
565
+ // on the layers stop following the component, and the writer saves them as content instead of
566
+ // dropping an override with no component layer to address.
567
+ const parentId = graph.nodes.get(nodeId)?.parentId
568
+ if (parentId) {
569
+ const scope = enclosingSlotScope(graph, parentId)
570
+ if (scope) claimSlotContent(graph, scope)
571
+ }
563
572
 
564
573
  const relevant = overrideFieldsOf(
565
574
  graph,
@@ -27,7 +27,8 @@ export function placedByConstraints(
27
27
  instParent,
28
28
  source.horizontalConstraint,
29
29
  source.verticalConstraint,
30
- enforcedAspectRatio(source)
30
+ enforcedAspectRatio(source),
31
+ source
31
32
  )
32
33
  return { ...source, ...rect }
33
34
  }
@@ -16,8 +16,14 @@ import {
16
16
  withStrokeLines
17
17
  } from '../strokes'
18
18
  import type { SceneNode } from '../types'
19
- import { resolvedNumericBindings } from '../variables/bindings'
20
- import { isNumericVariableBindingField, paintBindingTarget } from '../variables/fields'
19
+ import { resolvedEffectColorBindings, resolvedNumericBindings } from '../variables/bindings'
20
+ import {
21
+ effectBindingTarget,
22
+ effectColorBindingTarget,
23
+ isNumericVariableBindingField,
24
+ layoutGridBindingTarget,
25
+ paintBindingTarget
26
+ } from '../variables/fields'
21
27
  import {
22
28
  applyBoundPaintColorsIn,
23
29
  copyAppliedBoundPaints,
@@ -257,13 +263,40 @@ function resolveBoundNumbersInPlace(
257
263
  const rebound = updates.boundVariables
258
264
  ? Object.keys(bound).filter((field) => bound[field] !== target.boundVariables[field])
259
265
  : []
260
- const synced = uniq([...Object.keys(updates), ...rebound]).filter(
261
- (field) => isNumericVariableBindingField(field) && bound[field] && !kept(field)
266
+ // A list binding (`effects/0/radius`) resolves into the whole list, so the list is what a sync
267
+ // copies when it writes that list and the resolved value would change.
268
+ const lists = Object.keys(bound).flatMap((field) => {
269
+ let list: 'effects' | 'layoutGrids' | null = null
270
+ if (effectBindingTarget(field) || effectColorBindingTarget(field)) list = 'effects'
271
+ else if (layoutGridBindingTarget(field)) list = 'layoutGrids'
272
+ return list && list in updates ? [list] : []
273
+ })
274
+ const hasBinding = (field: string) =>
275
+ field === 'effects' || field === 'layoutGrids'
276
+ ? Object.keys(bound).some((key) => key.startsWith(`${field}/`))
277
+ : Boolean(bound[field])
278
+ const synced = uniq([...Object.keys(updates), ...rebound, ...lists]).filter(
279
+ (field) =>
280
+ (isNumericVariableBindingField(field) || field === 'effects' || field === 'layoutGrids') &&
281
+ hasBinding(field) &&
282
+ !kept(field)
262
283
  )
263
284
  if (synced.length === 0) return
264
285
  applySyncedModes(graph, target, updates)
265
- const resolved = resolvedNumericBindings(graph, { ...target, ...updates }, 'active', resolver)
286
+ const merged = { ...target, ...updates }
287
+ const resolved = resolvedNumericBindings(graph, merged, 'active', resolver)
266
288
  Object.assign(updates, pick(resolved, synced as (keyof SceneNode)[]))
289
+ if (synced.includes('effects')) {
290
+ const colors = resolvedEffectColorBindings(
291
+ graph,
292
+ {
293
+ ...merged,
294
+ ...(updates.effects ? { effects: updates.effects } : {})
295
+ },
296
+ resolver
297
+ )
298
+ if (colors) updates.effects = colors
299
+ }
267
300
  }
268
301
 
269
302
  /** The modes the copy takes in this sync decide what its bindings resolve to. */
@@ -216,6 +216,8 @@ export function createDefaultNode(
216
216
  maskType: 'ALPHA',
217
217
  maskIsOutline: false,
218
218
  gridTemplateColumns: EMPTY_LIST,
219
+ gridChildHorizontalAlign: 'AUTO',
220
+ gridChildVerticalAlign: 'AUTO',
219
221
  gridTemplateRows: EMPTY_LIST,
220
222
  gridColumnGap: 0,
221
223
  gridRowGap: 0,
@@ -249,6 +251,8 @@ export function createDefaultNode(
249
251
  isExposedInstance: false,
250
252
  symbolDescription: '',
251
253
  symbolLinks: EMPTY_LIST,
254
+ annotations: EMPTY_LIST,
255
+ measurements: EMPTY_LIST,
252
256
  variantPropSpecs: EMPTY_LIST,
253
257
  boundVariables: EMPTY_RECORD,
254
258
  variableBindingScales: EMPTY_RECORD,
package/src/resize.ts CHANGED
@@ -137,18 +137,48 @@ function keepLockedRatio(
137
137
  : { x: resizedInPlace(x, y.size * aspectRatio, horizontal), y }
138
138
  }
139
139
 
140
+ /** The limits a layer's own size fields put on an automatic resize. */
141
+ export interface ConstraintLimits {
142
+ minWidth?: number | null
143
+ maxWidth?: number | null
144
+ minHeight?: number | null
145
+ maxHeight?: number | null
146
+ }
147
+
140
148
  type ChildRectPlacer = (
141
149
  child: Rect,
142
150
  parentBefore: Pick<Rect, 'width' | 'height'>,
143
151
  parentAfter: Pick<Rect, 'width' | 'height'>,
144
152
  horizontal: ConstraintType,
145
153
  vertical: ConstraintType,
146
- aspectRatio?: number | null
154
+ aspectRatio?: number | null,
155
+ limits?: ConstraintLimits
147
156
  ) => ConstrainedRect
148
157
 
158
+ /** A placed axis stopped at the layer's own min or max, its constraint's edge kept in place. */
159
+ function limitedAxis(
160
+ placed: AxisPlacement,
161
+ constraint: ConstraintType,
162
+ min: number | null | undefined,
163
+ max: number | null | undefined
164
+ ): AxisPlacement {
165
+ const size = Math.min(max ?? Infinity, Math.max(min ?? -Infinity, placed.size))
166
+ if (size === placed.size) return placed
167
+ const limited = resizedInPlace(placed, size, constraint)
168
+ return placed.flipped ? { ...limited, flipped: true } : limited
169
+ }
170
+
149
171
  /** Places a child by its constraints, snapping a scaled position to `scaleStep` when it is set. */
150
172
  function childRectPlacer(scaleStep: number, allowFlips = true): ChildRectPlacer {
151
- return (child, parentBefore, parentAfter, horizontal, vertical, aspectRatio = null) => {
173
+ return (
174
+ child,
175
+ parentBefore,
176
+ parentAfter,
177
+ horizontal,
178
+ vertical,
179
+ aspectRatio = null,
180
+ limits = {}
181
+ ) => {
152
182
  const { x, y } = keepLockedRatio(
153
183
  constrainedAxis(
154
184
  child.x,
@@ -172,9 +202,16 @@ function childRectPlacer(scaleStep: number, allowFlips = true): ChildRectPlacer
172
202
  vertical,
173
203
  aspectRatio
174
204
  )
175
- const rect: ConstrainedRect = { x: x.position, y: y.position, width: x.size, height: y.size }
176
- if (x.flipped) rect.flipsX = true
177
- if (y.flipped) rect.flipsY = true
205
+ const limitedX = limitedAxis(x, horizontal, limits.minWidth, limits.maxWidth)
206
+ const limitedY = limitedAxis(y, vertical, limits.minHeight, limits.maxHeight)
207
+ const rect: ConstrainedRect = {
208
+ x: limitedX.position,
209
+ y: limitedY.position,
210
+ width: limitedX.size,
211
+ height: limitedY.size
212
+ }
213
+ if (limitedX.flipped) rect.flipsX = true
214
+ if (limitedY.flipped) rect.flipsY = true
178
215
  return rect
179
216
  }
180
217
  }
@@ -469,7 +506,8 @@ export function computeConstrainedResizeChanges(
469
506
  parentAfter,
470
507
  child.horizontalConstraint,
471
508
  child.verticalConstraint,
472
- enforcedAspectRatio(child)
509
+ enforcedAspectRatio(child),
510
+ child
473
511
  )
474
512
  const { flipsX, flipsY, ...box } = rect
475
513
  const childChanges: Partial<SceneNode> = {
@@ -1,9 +1,11 @@
1
1
  import { isGeneratedFrame } from '../generated'
2
2
  import type { SceneGraph } from '../graph'
3
3
  import {
4
+ cloneInstanceOverrideState,
4
5
  getInstanceOverride,
5
6
  ownInstanceOverrides,
6
- setInstanceOverride
7
+ setInstanceOverride,
8
+ type InstanceOverrideState
7
9
  } from '../instances/overrides'
8
10
  import { cloneChildrenWithMapping } from '../instances/sync'
9
11
  import type { SceneNode } from '../types'
@@ -28,6 +30,15 @@ function nearestInstance(graph: SceneGraph, node: SceneNode): SceneNode | undefi
28
30
  : undefined
29
31
  }
30
32
 
33
+ /**
34
+ * Marks which component property an instance assigns, so a save writes the assignment rather than
35
+ * the one the file held before the slot's content became the instance's own or its component's.
36
+ */
37
+ function markAssignmentEdited(instance: SceneNode): void {
38
+ if (instance.source.editedFields.includes('componentPropertyAssignments')) return
39
+ instance.source.editedFields = [...instance.source.editedFields, 'componentPropertyAssignments']
40
+ }
41
+
31
42
  export function slotScope(graph: SceneGraph, parentId: string): SlotScope {
32
43
  const owner = graph.closest(
33
44
  parentId,
@@ -89,6 +100,200 @@ export function claimSlotContent(
89
100
  instanceOverrides: overrides,
90
101
  componentPropertyAssignments: { ...instance.componentPropertyAssignments, [propertyId]: '' }
91
102
  })
103
+ const claimed = graph.getNode(instance.id)
104
+ if (claimed) markAssignmentEdited(claimed)
105
+ }
106
+
107
+ /**
108
+ * What claiming a slot changes besides the edited layer, so one undo step can put it all back:
109
+ * the instance's assignment and override state, and the copies' component addresses.
110
+ */
111
+ export interface SlotClaimSnapshot {
112
+ instanceId: string
113
+ assignments: SceneNode['componentPropertyAssignments']
114
+ editedFields: string[]
115
+ overrides: InstanceOverrideState
116
+ componentIds: Map<string, string | null>
117
+ nestedOverrides: Map<string, InstanceOverrideState>
118
+ }
119
+
120
+ /** The state `claimSlotContent` would replace, or null when the instance already owns the slot. */
121
+ export function snapshotSlotClaim(
122
+ graph: SceneGraph,
123
+ scope: Extract<SlotScope, { kind: 'slot' }>
124
+ ): SlotClaimSnapshot | null {
125
+ if (ownsSlotContent(graph, scope.frame, scope.propertyId)) return null
126
+ const instance = graph.getNode(scope.instance.id)
127
+ if (!instance) return null
128
+ const componentIds = new Map<string, string | null>()
129
+ const nestedOverrides = new Map<string, InstanceOverrideState>()
130
+ for (const node of descendants(graph, scope.frame, false)) {
131
+ componentIds.set(node.id, node.componentId)
132
+ if (node.type === 'INSTANCE') {
133
+ nestedOverrides.set(node.id, cloneInstanceOverrideState(node.instanceOverrides))
134
+ }
135
+ }
136
+ return {
137
+ instanceId: instance.id,
138
+ assignments: { ...instance.componentPropertyAssignments },
139
+ editedFields: [...instance.source.editedFields],
140
+ overrides: cloneInstanceOverrideState(instance.instanceOverrides),
141
+ componentIds,
142
+ nestedOverrides
143
+ }
144
+ }
145
+
146
+ /** Undo a claim: the instance stops owning the slot and its copies follow the component again. */
147
+ export function restoreSlotClaim(graph: SceneGraph, snapshot: SlotClaimSnapshot): void {
148
+ for (const [id, componentId] of snapshot.componentIds) {
149
+ if (graph.nodes.has(id)) graph.updateNode(id, { componentId })
150
+ }
151
+ for (const [id, overrides] of snapshot.nestedOverrides) {
152
+ if (graph.nodes.has(id)) {
153
+ graph.updateNode(id, { instanceOverrides: cloneInstanceOverrideState(overrides) })
154
+ }
155
+ }
156
+ const instance = graph.getNode(snapshot.instanceId)
157
+ if (!instance) return
158
+ graph.updateNode(snapshot.instanceId, {
159
+ componentPropertyAssignments: { ...snapshot.assignments },
160
+ instanceOverrides: cloneInstanceOverrideState(snapshot.overrides),
161
+ source: { ...instance.source, editedFields: [...snapshot.editedFields] }
162
+ })
163
+ }
164
+
165
+ /**
166
+ * The instance guard's refusal. Commands catch this one class to explain the refusal; every other
167
+ * error keeps propagating as a real failure.
168
+ */
169
+ export class InstanceGuardError extends Error {
170
+ constructor(
171
+ readonly method: string,
172
+ refusal: string
173
+ ) {
174
+ super(refusal)
175
+ this.name = 'InstanceGuardError'
176
+ }
177
+ }
178
+
179
+ function lockedOwnerLabel(owner: SceneNode): string {
180
+ return owner.type === 'INSTANCE'
181
+ ? `Instance "${owner.name}" keeps its own layers; put content in one of its slots, or detach it first.`
182
+ : `"${owner.name}" keeps its own layers.`
183
+ }
184
+
185
+ /**
186
+ * Why a new child under `parentId` would be refused, or null when it is allowed. Pure: a caller
187
+ * that only asks (a menu greying a command) never claims a slot.
188
+ */
189
+ function sliceParentRefusal(graph: SceneGraph, parentId: string, method: string): string | null {
190
+ if (graph.getNode(parentId)?.type !== 'SLICE') return null
191
+ return `in ${method}: Cannot add a layer to a slice: a slice is an export region.`
192
+ }
193
+
194
+ export function childPlacementRefusal(
195
+ graph: SceneGraph,
196
+ parentId: string,
197
+ method: string
198
+ ): string | null {
199
+ const sliceRefusal = sliceParentRefusal(graph, parentId, method)
200
+ if (sliceRefusal) return sliceRefusal
201
+ const scope = slotScope(graph, parentId)
202
+ if (scope.kind !== 'locked') return null
203
+ return `in ${method}: Cannot move node. New parent is an instance or is inside of an instance. ${lockedOwnerLabel(scope.owner)}`
204
+ }
205
+
206
+ /** Refuse a new child under the locked part of an instance, as Figma's appendChild does. */
207
+ export function assertChildPlacement(graph: SceneGraph, parentId: string, method: string): void {
208
+ const refusal = childPlacementRefusal(graph, parentId, method)
209
+ if (refusal) throw new InstanceGuardError(method, refusal)
210
+ const scope = slotScope(graph, parentId)
211
+ if (scope.kind === 'slot') claimSlotContent(graph, scope)
212
+ }
213
+
214
+ /** Why grouping or moving these layers there would be refused, or null when it is allowed. */
215
+ export function groupPlacementRefusal(
216
+ graph: SceneGraph,
217
+ parentId: string,
218
+ memberIds: readonly string[],
219
+ method: string
220
+ ): string | null {
221
+ const sliceRefusal = sliceParentRefusal(graph, parentId, method)
222
+ if (sliceRefusal) return sliceRefusal
223
+ const destination = slotScope(graph, parentId)
224
+ if (destination.kind === 'locked')
225
+ return `in ${method}: Cannot move node. New parent is an instance or is inside of an instance. ${lockedOwnerLabel(destination.owner)}`
226
+ for (const id of memberIds) {
227
+ const parent = graph.getNode(id)?.parentId
228
+ if (!parent) continue
229
+ const source = slotScope(graph, parent)
230
+ if (source.kind === 'locked')
231
+ return `in ${method}: Cannot move node. Node is inside of an instance. ${lockedOwnerLabel(source.owner)}`
232
+ }
233
+ return null
234
+ }
235
+
236
+ /** Refuse grouping layers under the locked part, or pulling locked layers out of it. */
237
+ export function assertGroupPlacement(
238
+ graph: SceneGraph,
239
+ parentId: string,
240
+ memberIds: readonly string[],
241
+ method: string
242
+ ): void {
243
+ const refusal = groupPlacementRefusal(graph, parentId, memberIds, method)
244
+ if (refusal) throw new InstanceGuardError(method, refusal)
245
+ const destination = slotScope(graph, parentId)
246
+ if (destination.kind === 'slot') claimSlotContent(graph, destination)
247
+ for (const id of memberIds) {
248
+ const parent = graph.getNode(id)?.parentId
249
+ if (!parent) continue
250
+ const source = slotScope(graph, parent)
251
+ if (source.kind === 'slot') claimSlotContent(graph, source)
252
+ }
253
+ }
254
+
255
+ /** Why moving this layer out of its parent would be refused, or null when it is allowed. */
256
+ export function nodeMovementRefusal(
257
+ graph: SceneGraph,
258
+ nodeId: string,
259
+ method: string
260
+ ): string | null {
261
+ const parentId = graph.getNode(nodeId)?.parentId
262
+ if (!parentId) return null
263
+ const scope = slotScope(graph, parentId)
264
+ if (scope.kind !== 'locked') return null
265
+ return `in ${method}: Cannot move node. Node is inside of an instance. ${lockedOwnerLabel(scope.owner)}`
266
+ }
267
+
268
+ /** Refuse moving a layer out of the locked part of an instance, as Figma does. */
269
+ export function assertNodeMovable(graph: SceneGraph, nodeId: string, method: string): void {
270
+ const refusal = nodeMovementRefusal(graph, nodeId, method)
271
+ if (refusal) throw new InstanceGuardError(method, refusal)
272
+ const parentId = graph.getNode(nodeId)?.parentId
273
+ if (!parentId) return
274
+ const scope = slotScope(graph, parentId)
275
+ if (scope.kind === 'slot') claimSlotContent(graph, scope)
276
+ }
277
+
278
+ /**
279
+ * The slot scope a layer sits inside, walking out past a locked frame such as a nested instance:
280
+ * an edit anywhere below the slot is still content the instance put there.
281
+ */
282
+ export function enclosingSlotScope(
283
+ graph: SceneGraph,
284
+ fromId: string
285
+ ): Extract<SlotScope, { kind: 'slot' }> | null {
286
+ let currentId: string | undefined = fromId
287
+ while (currentId) {
288
+ const scope = slotScope(graph, currentId)
289
+ if (scope.kind === 'slot') return scope
290
+ if (scope.kind === 'free') return null
291
+ const node = graph.getNode(currentId)
292
+ // A locked frame of unknown kind (a generated frame) has no enclosing slot to claim.
293
+ if (node?.type !== 'INSTANCE') return null
294
+ currentId = node.parentId ?? undefined
295
+ }
296
+ return null
92
297
  }
93
298
 
94
299
  /** The component layer an instance layer was cloned from. */
@@ -112,6 +317,8 @@ export function resetSlotContent(
112
317
  const assignments = { ...instance.componentPropertyAssignments }
113
318
  Reflect.deleteProperty(assignments, propertyId)
114
319
  graph.updateNode(instance.id, { componentPropertyAssignments: assignments })
320
+ const released = graph.getNode(instance.id)
321
+ if (released) markAssignmentEdited(released)
115
322
  const source = componentSource(instance, frame)
116
323
  if (!source || !graph.nodes.has(source)) return
117
324
  cloneChildrenWithMapping(graph, source, frame.id)
@@ -2,3 +2,4 @@ export * from './authoring'
2
2
  export * from './content'
3
3
  export * from './frames'
4
4
  export * from './limits'
5
+ export * from './owners'