@pairdraw/scene-graph 0.20.0 → 0.21.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 (145) hide show
  1. package/dist/color/index.d.ts +28 -7
  2. package/dist/color/index.d.ts.map +1 -1
  3. package/dist/color/index.js +40 -15
  4. package/dist/color/index.js.map +1 -1
  5. package/dist/color/management.d.ts +19 -6
  6. package/dist/color/management.d.ts.map +1 -1
  7. package/dist/color/management.js +56 -1
  8. package/dist/color/management.js.map +1 -1
  9. package/dist/color/profile.d.ts +32 -0
  10. package/dist/color/profile.d.ts.map +1 -0
  11. package/dist/color/profile.js +140 -0
  12. package/dist/color/profile.js.map +1 -0
  13. package/dist/comments/index.d.ts +2 -2
  14. package/dist/comments/index.js +2 -2
  15. package/dist/comments/merge.d.ts.map +1 -1
  16. package/dist/comments/merge.js +1 -0
  17. package/dist/comments/merge.js.map +1 -1
  18. package/dist/comments/schema.d.ts +3 -1
  19. package/dist/comments/schema.d.ts.map +1 -1
  20. package/dist/comments/schema.js +19 -2
  21. package/dist/comments/schema.js.map +1 -1
  22. package/dist/comments/threads.d.ts +3 -1
  23. package/dist/comments/threads.d.ts.map +1 -1
  24. package/dist/comments/threads.js +2 -1
  25. package/dist/comments/threads.js.map +1 -1
  26. package/dist/components/properties.d.ts.map +1 -1
  27. package/dist/components/properties.js +7 -7
  28. package/dist/components/properties.js.map +1 -1
  29. package/dist/css/shadows.d.ts +2 -2
  30. package/dist/css/shadows.d.ts.map +1 -1
  31. package/dist/css/shadows.js +4 -4
  32. package/dist/css/shadows.js.map +1 -1
  33. package/dist/css/values.d.ts +7 -2
  34. package/dist/css/values.d.ts.map +1 -1
  35. package/dist/css/values.js +8 -4
  36. package/dist/css/values.js.map +1 -1
  37. package/dist/empty-values.js +9 -0
  38. package/dist/empty-values.js.map +1 -1
  39. package/dist/graph.d.ts +4 -0
  40. package/dist/graph.d.ts.map +1 -1
  41. package/dist/graph.js +11 -2
  42. package/dist/graph.js.map +1 -1
  43. package/dist/images.d.ts +3 -2
  44. package/dist/images.d.ts.map +1 -1
  45. package/dist/images.js +18 -2
  46. package/dist/images.js.map +1 -1
  47. package/dist/index.d.ts +2 -2
  48. package/dist/instances/copies.js +2 -1
  49. package/dist/instances/copies.js.map +1 -1
  50. package/dist/instances/index.d.ts.map +1 -1
  51. package/dist/instances/index.js +12 -11
  52. package/dist/instances/index.js.map +1 -1
  53. package/dist/instances/overrides.d.ts +15 -1
  54. package/dist/instances/overrides.d.ts.map +1 -1
  55. package/dist/instances/overrides.js +37 -1
  56. package/dist/instances/overrides.js.map +1 -1
  57. package/dist/instances/swap-overrides.js +3 -3
  58. package/dist/instances/swap-overrides.js.map +1 -1
  59. package/dist/instances/sync.js +9 -7
  60. package/dist/instances/sync.js.map +1 -1
  61. package/dist/node-defaults.js +2 -2
  62. package/dist/node-defaults.js.map +1 -1
  63. package/dist/plugin-data/fields.d.ts +15 -0
  64. package/dist/plugin-data/fields.d.ts.map +1 -1
  65. package/dist/plugin-data/fields.js +15 -23
  66. package/dist/plugin-data/fields.js.map +1 -1
  67. package/dist/plugin-data/index.d.ts +2 -2
  68. package/dist/plugin-data/index.js +2 -2
  69. package/dist/plugin-data/schema.d.ts +6 -1
  70. package/dist/plugin-data/schema.d.ts.map +1 -1
  71. package/dist/plugin-data/schema.js +24 -1
  72. package/dist/plugin-data/schema.js.map +1 -1
  73. package/dist/shaders/animation.d.ts +21 -0
  74. package/dist/shaders/animation.d.ts.map +1 -0
  75. package/dist/shaders/animation.js +25 -0
  76. package/dist/shaders/animation.js.map +1 -0
  77. package/dist/shaders/index.d.ts +2 -1
  78. package/dist/shaders/index.js +2 -1
  79. package/dist/slots/content.d.ts.map +1 -1
  80. package/dist/slots/content.js +4 -4
  81. package/dist/slots/content.js.map +1 -1
  82. package/dist/statuses/index.d.ts +2 -2
  83. package/dist/statuses/index.js +2 -2
  84. package/dist/statuses/workflow.d.ts +3 -1
  85. package/dist/statuses/workflow.d.ts.map +1 -1
  86. package/dist/statuses/workflow.js +6 -2
  87. package/dist/statuses/workflow.js.map +1 -1
  88. package/dist/transfer/variables.d.ts.map +1 -1
  89. package/dist/transfer/variables.js +1 -1
  90. package/dist/transfer/variables.js.map +1 -1
  91. package/dist/types.d.ts +34 -2
  92. package/dist/types.d.ts.map +1 -1
  93. package/dist/types.js.map +1 -1
  94. package/dist/variables/bindings.d.ts +6 -5
  95. package/dist/variables/bindings.d.ts.map +1 -1
  96. package/dist/variables/bindings.js +24 -16
  97. package/dist/variables/bindings.js.map +1 -1
  98. package/dist/variables/formula/index.d.ts.map +1 -1
  99. package/dist/variables/formula/index.js +12 -6
  100. package/dist/variables/formula/index.js.map +1 -1
  101. package/dist/variables/index.d.ts +14 -1
  102. package/dist/variables/index.d.ts.map +1 -1
  103. package/dist/variables/index.js +38 -10
  104. package/dist/variables/index.js.map +1 -1
  105. package/dist/variables/paints.d.ts +9 -8
  106. package/dist/variables/paints.d.ts.map +1 -1
  107. package/dist/variables/paints.js +35 -26
  108. package/dist/variables/paints.js.map +1 -1
  109. package/dist/variables/resolver.d.ts +45 -0
  110. package/dist/variables/resolver.d.ts.map +1 -0
  111. package/dist/variables/resolver.js +106 -0
  112. package/dist/variables/resolver.js.map +1 -0
  113. package/package.json +1 -1
  114. package/src/color/index.ts +43 -9
  115. package/src/color/management.ts +54 -1
  116. package/src/color/profile.ts +131 -0
  117. package/src/comments/merge.ts +3 -0
  118. package/src/comments/schema.ts +32 -2
  119. package/src/comments/threads.ts +5 -2
  120. package/src/components/properties.ts +13 -7
  121. package/src/css/shadows.ts +8 -5
  122. package/src/css/values.ts +12 -5
  123. package/src/empty-values.ts +16 -0
  124. package/src/graph.ts +13 -1
  125. package/src/images.ts +27 -3
  126. package/src/instances/copies.ts +2 -1
  127. package/src/instances/index.ts +19 -11
  128. package/src/instances/overrides.ts +49 -0
  129. package/src/instances/swap-overrides.ts +3 -2
  130. package/src/instances/sync.ts +11 -7
  131. package/src/node-defaults.ts +2 -2
  132. package/src/plugin-data/fields.ts +16 -31
  133. package/src/plugin-data/index.ts +1 -0
  134. package/src/plugin-data/schema.ts +30 -0
  135. package/src/shaders/animation.ts +39 -0
  136. package/src/shaders/index.ts +1 -0
  137. package/src/slots/content.ts +8 -4
  138. package/src/statuses/workflow.ts +6 -4
  139. package/src/transfer/variables.ts +2 -1
  140. package/src/types.ts +30 -1
  141. package/src/variables/bindings.ts +35 -18
  142. package/src/variables/formula/index.ts +19 -18
  143. package/src/variables/index.ts +49 -10
  144. package/src/variables/paints.ts +64 -29
  145. package/src/variables/resolver.ts +178 -0
@@ -1,7 +1,7 @@
1
1
  import type { SceneGraph } from '../graph'
2
2
  import type { Color, Vector } from '../primitives'
3
3
  import { randomHex } from '../random'
4
- import type { CommentReply, CommentThread, SceneNode } from '../types'
4
+ import type { CommentRegion, CommentReply, CommentThread, SceneNode } from '../types'
5
5
 
6
6
  /** Who writes a comment: their name and, in a collaboration room, their color. */
7
7
  export interface CommentAuthor {
@@ -87,12 +87,14 @@ export function createCommentThread(
87
87
  at: Vector
88
88
  /** Pin it on this layer's top-level layer rather than on whatever is at `at`. */
89
89
  node?: SceneNode
90
+ /** The area the person circled, when the comment was drawn rather than clicked. */
91
+ region?: CommentRegion | null
90
92
  author: CommentAuthor
91
93
  text: string
92
94
  now: string
93
95
  }
94
96
  ): CommentThread {
95
- const { pageId, at, node, author, text, now } = options
97
+ const { pageId, at, node, region, author, text, now } = options
96
98
  return {
97
99
  id: newCommentId('c'),
98
100
  pageId,
@@ -104,6 +106,7 @@ export function createCommentThread(
104
106
  createdAt: now,
105
107
  updatedAt: now,
106
108
  resolved: false,
109
+ ...(region ? { region } : {}),
107
110
  replies: []
108
111
  }
109
112
  }
@@ -1,7 +1,7 @@
1
1
  import type { SceneGraph } from '../graph'
2
2
  import { findInstanceAncestor, recordAssignmentOverride } from '../instances'
3
3
  import { instanceMainComponent } from '../instances/main-component'
4
- import { setInstanceOverride } from '../instances/overrides'
4
+ import { ownInstanceOverrides, setInstanceOverride } from '../instances/overrides'
5
5
  import { walkInstanceSources } from '../instances/source-walk'
6
6
  import { randomHex } from '../random'
7
7
  import type {
@@ -103,7 +103,7 @@ function applyTextProperty(
103
103
  if (item.field !== 'TEXT' || item.node.type !== 'TEXT') continue
104
104
  graph.updateNode(item.node.id, { text: value })
105
105
  if (findInstanceAncestor(graph, item.node.id)) {
106
- setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, 'text', value)
106
+ setInstanceOverride(ownInstanceOverrides(owner), owner.id, item.node.id, 'text', value)
107
107
  }
108
108
  }
109
109
  }
@@ -120,7 +120,7 @@ function applyBooleanProperty(
120
120
  graph.updateNode(item.node.id, { visible: value === 'true' })
121
121
  if (instance) {
122
122
  setInstanceOverride(
123
- owner.instanceOverrides,
123
+ ownInstanceOverrides(owner),
124
124
  owner.id,
125
125
  item.node.id,
126
126
  'visible',
@@ -139,16 +139,22 @@ function applyInstanceSwapProperty(
139
139
  for (const item of targets) {
140
140
  if (item.field !== 'INSTANCE_SWAP' || item.node.type !== 'INSTANCE') continue
141
141
  graph.swapInstanceComponent(item.node.id, target.id)
142
- setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, 'name', target.name)
143
- setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, 'componentId', target.id)
142
+ setInstanceOverride(ownInstanceOverrides(owner), owner.id, item.node.id, 'name', target.name)
144
143
  setInstanceOverride(
145
- owner.instanceOverrides,
144
+ ownInstanceOverrides(owner),
145
+ owner.id,
146
+ item.node.id,
147
+ 'componentId',
148
+ target.id
149
+ )
150
+ setInstanceOverride(
151
+ ownInstanceOverrides(owner),
146
152
  owner.id,
147
153
  item.node.id,
148
154
  'sourceComponentId',
149
155
  item.source.id
150
156
  )
151
- graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })
157
+ graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) })
152
158
  }
153
159
  }
154
160
 
@@ -3,14 +3,14 @@ import valueParser, { type Node } from 'postcss-value-parser'
3
3
  import { tryParseColor } from '../color'
4
4
  import { BLACK } from '../constants'
5
5
  import type { Color } from '../primitives'
6
- import type { Effect } from '../types'
6
+ import type { DocumentColorSpace, Effect } from '../types'
7
7
  import { cssLayers, parseCSSNumber } from './values'
8
8
 
9
9
  /**
10
10
  * One layer: `inset`, two to four lengths, and a color in any order. Without a color it is
11
11
  * black, as `currentColor` usually is; a layer with anything else, such as `none`, is dropped.
12
12
  */
13
- function shadowOf(nodes: Node[]): Effect[] {
13
+ function shadowOf(nodes: Node[], profile: DocumentColorSpace): Effect[] {
14
14
  let inset = false
15
15
  let color: Color | null = null
16
16
  const lengths: number[] = []
@@ -24,7 +24,7 @@ function shadowOf(nodes: Node[]): Effect[] {
24
24
  lengths.push(length)
25
25
  continue
26
26
  }
27
- const parsed = tryParseColor(valueParser.stringify(node))
27
+ const parsed = tryParseColor(valueParser.stringify(node), profile)
28
28
  if (!parsed || color) return []
29
29
  color = parsed
30
30
  }
@@ -46,7 +46,10 @@ function shadowOf(nodes: Node[]): Effect[] {
46
46
  * The shadows of a CSS `box-shadow` or `text-shadow` list, such as
47
47
  * `0 4px 8px rgb(0 0 0 / 0.2), inset 0 1px #fff`: drop shadows, and inner shadows for `inset`.
48
48
  */
49
- export function parseCSSShadows(value: string | undefined): Effect[] {
49
+ export function parseCSSShadows(
50
+ value: string | undefined,
51
+ profile: DocumentColorSpace = 'srgb'
52
+ ): Effect[] {
50
53
  if (!value) return []
51
- return cssLayers(valueParser(value).nodes).flatMap(shadowOf)
54
+ return cssLayers(valueParser(value).nodes).flatMap((nodes) => shadowOf(nodes, profile))
52
55
  }
package/src/css/values.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import valueParser, { type Node } from 'postcss-value-parser'
2
2
 
3
- import { parseDisplayableColor } from '../color'
3
+ import { tryParseColor } from '../color'
4
4
  import type { Color } from '../primitives'
5
+ import type { DocumentColorSpace } from '../types'
5
6
 
6
7
  /** Pixels in a rem, as browsers use by default. */
7
8
  const ROOT_FONT_SIZE = 16
@@ -27,11 +28,17 @@ export function parseCSSNumber(value: string | undefined): number | null {
27
28
  }
28
29
  }
29
30
 
30
- /** A CSS color that paints something; null for an invalid or fully transparent one. */
31
- export function parseCSSColor(value: string | undefined): Color | null {
31
+ /**
32
+ * A CSS color that paints something, as components in `profile`; null for an invalid or fully
33
+ * transparent one. A stylesheet's own declarations are read in sRGB, as CSS authors them; a caller
34
+ * reading markup into a document passes the document's profile.
35
+ */
36
+ export function parseCSSColor(
37
+ value: string | undefined,
38
+ profile: DocumentColorSpace = 'srgb'
39
+ ): Color | null {
32
40
  if (!value) return null
33
- // CSS clamps `rgb()` channels and maps wide-gamut colors into sRGB, as a stored color must be.
34
- const color = parseDisplayableColor(value.trim())
41
+ const color = tryParseColor(value.trim(), profile)
35
42
  return color && color.a > 0 ? color : null
36
43
  }
37
44
 
@@ -1,5 +1,10 @@
1
1
  import { isEmptyObject, isPlainObject } from 'es-toolkit'
2
2
 
3
+ import {
4
+ EMPTY_INSTANCE_OVERRIDES,
5
+ isEmptyInstanceOverrideState,
6
+ type InstanceOverrideState
7
+ } from './instances/overrides'
3
8
  import type { SceneNode, SourceMetadata } from './types'
4
9
 
5
10
  /**
@@ -39,10 +44,21 @@ function sharedEmptyRecord(value: unknown): unknown {
39
44
  }
40
45
 
41
46
  function sharedEmptyValue(field: string, value: unknown): unknown {
47
+ if (field === 'instanceOverrides') return sharedEmptyOverrideState(value)
42
48
  if (Array.isArray(value)) return OWN_LIST_FIELDS.has(field) ? value : sharedEmptyList(value)
43
49
  return RECORD_FIELDS.has(field) ? sharedEmptyRecord(value) : value
44
50
  }
45
51
 
52
+ /** An override state with nothing in it, so a layer that cleared its overrides shares the empty one. */
53
+ function sharedEmptyOverrideState(value: unknown): unknown {
54
+ if (!isPlainObject(value)) return value
55
+ const { self, descendants } = value as Partial<InstanceOverrideState>
56
+ if (!(self instanceof Map) || !(descendants instanceof Map)) return value
57
+ return isEmptyInstanceOverrideState(value as InstanceOverrideState)
58
+ ? EMPTY_INSTANCE_OVERRIDES
59
+ : value
60
+ }
61
+
46
62
  /**
47
63
  * `record` with the empty lists among `lists` and the empty record at `recordField` swapped for
48
64
  * the shared ones: a copy when anything changes, so the caller's object is never written into.
package/src/graph.ts CHANGED
@@ -23,6 +23,7 @@ import { gridLayoutChanges } from './grid-values'
23
23
  import * as HitTest from './hit-test'
24
24
  import { generateId } from './ids'
25
25
  import * as Instances from './instances'
26
+ import { ownInstanceOverrides } from './instances/overrides'
26
27
  import { LayoutWrites } from './layout/writes'
27
28
  import Matrix from './matrix'
28
29
  import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'
@@ -349,6 +350,16 @@ export class SceneGraph {
349
350
  return Variables.getVariablesByType(this, type)
350
351
  }
351
352
 
353
+ /** Every variable but the deleted ones, which only their bindings still reach. */
354
+ getLiveVariables(): Variable[] {
355
+ return Variables.liveVariables(this)
356
+ }
357
+
358
+ /** Every collection but the deleted ones. */
359
+ getLiveCollections(): VariableCollection[] {
360
+ return Variables.liveCollections(this)
361
+ }
362
+
352
363
  bindVariable(nodeId: string, field: string, variableId: string): void {
353
364
  Variables.bindVariable(this, nodeId, field, variableId)
354
365
  }
@@ -902,7 +913,8 @@ export class SceneGraph {
902
913
  // An override names a layer of its instance: one left naming a deleted layer would be written
903
914
  // as a claim for nothing, and reopening would restore a layer the document no longer has.
904
915
  for (let owner = node.parentId ? this.nodes.get(node.parentId) : undefined; owner;) {
905
- if (owner.type === 'INSTANCE') owner.instanceOverrides.descendants.delete(id)
916
+ if (owner.type === 'INSTANCE' && owner.instanceOverrides.descendants.has(id))
917
+ ownInstanceOverrides(owner).descendants.delete(id)
906
918
  owner = owner.parentId ? this.nodes.get(owner.parentId) : undefined
907
919
  }
908
920
  this.connectorIds.delete(id)
package/src/images.ts CHANGED
@@ -13,7 +13,7 @@ export function computeImageHash(data: Uint8Array): string {
13
13
  return bytesToHex(sha1(data))
14
14
  }
15
15
 
16
- export type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'
16
+ export type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif'
17
17
 
18
18
  /** The image types documents store, by the name `image-size` gives each format. */
19
19
  const IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {
@@ -58,12 +58,36 @@ export function imageHeader(data: Uint8Array): ImageHeader | null {
58
58
  return type ? { type, width: header.width, height: header.height } : null
59
59
  }
60
60
 
61
+ /** A four-character ISO media brand at `start`, or an empty string when the bytes are short. */
62
+ function isoBrand(data: Uint8Array, start: number): string {
63
+ if (start + 4 > data.length) return ''
64
+ return String.fromCharCode(
65
+ data[start] ?? 0,
66
+ data[start + 1] ?? 0,
67
+ data[start + 2] ?? 0,
68
+ data[start + 3] ?? 0
69
+ )
70
+ }
71
+
72
+ /** Whether bytes are an AVIF image, whose `ftyp` box names the brand or lists it as compatible. */
73
+ function isAVIF(data: Uint8Array): boolean {
74
+ if (isoBrand(data, 4) !== 'ftyp') return false
75
+ const size = ((data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]) >>> 0
76
+ const isAvif = (brand: string) => brand === 'avif' || brand === 'avis'
77
+ if (isAvif(isoBrand(data, 8))) return true
78
+ const end = Math.min(size >= 16 ? size : data.length, data.length)
79
+ // The major brand is followed by a minor version, then the compatible brands.
80
+ for (let start = 16; start + 4 <= end; start += 4) if (isAvif(isoBrand(data, start))) return true
81
+ return false
82
+ }
83
+
61
84
  /**
62
85
  * The media type of encoded image bytes, read from their header, for writing them out as a data
63
- * URL or file. Bytes it cannot read are reported as PNG, as image fills began.
86
+ * URL or file. AVIF is read from its ISO media brand, which `image-size` does not decode. Bytes it
87
+ * cannot read are reported as PNG, as image fills began.
64
88
  */
65
89
  export function imageMimeType(data: Uint8Array): ImageMimeType {
66
- return imageHeader(data)?.type ?? 'image/png'
90
+ return imageHeader(data)?.type ?? (isAVIF(data) ? 'image/avif' : 'image/png')
67
91
  }
68
92
 
69
93
  /** An image's size in pixels, read from its header; null for bytes it cannot read. */
@@ -228,7 +228,8 @@ export function removeLeftoverCopies(
228
228
  const overrides = new Map<string, Map<string, unknown>>()
229
229
  for (const removed of nodes) {
230
230
  const fields = context.overrides.descendants.get(removed.id)
231
- if (fields) overrides.set(removed.id, new Map(fields))
231
+ if (!fields) continue
232
+ overrides.set(removed.id, new Map(fields))
232
233
  context.overrides.descendants.delete(removed.id)
233
234
  }
234
235
  let copies = store.byInstance.get(context.instanceId)
@@ -24,6 +24,7 @@ import {
24
24
  hasInstanceOverride as hasNodeInstanceOverride,
25
25
  type InstanceOverrideState,
26
26
  overriddenAssignmentId,
27
+ ownInstanceOverrides,
27
28
  REPLACED_LAYER_OVERRIDE,
28
29
  setInstanceOverride,
29
30
  variableModeOverrideField
@@ -134,14 +135,20 @@ function recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: s
134
135
  )
135
136
  if (typeof existing !== 'string' && instance.componentId)
136
137
  setInstanceOverride(
137
- owner.instanceOverrides,
138
+ ownInstanceOverrides(owner),
138
139
  owner.id,
139
140
  instance.id,
140
141
  'sourceComponentId',
141
142
  instance.componentId
142
143
  )
143
- setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, 'componentId', componentId)
144
- graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })
144
+ setInstanceOverride(
145
+ ownInstanceOverrides(owner),
146
+ owner.id,
147
+ instance.id,
148
+ 'componentId',
149
+ componentId
150
+ )
151
+ graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) })
145
152
  }
146
153
 
147
154
  export interface SwapInstanceOptions {
@@ -299,8 +306,9 @@ function syncInstancesOf(
299
306
  updateSyncedProps(graph, instance, updates, (key) =>
300
307
  isProtectedSyncField(instance, key, protectedField)
301
308
  )
302
- const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)
303
- syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)
309
+ const owned = ownInstanceOverrides(instance)
310
+ const context = createInstanceSyncContext(instance.id, owned)
311
+ syncChildren(graph, component.id, instance.id, owned, context)
304
312
  removeLeftoverCopies(graph, context, removals)
305
313
  }
306
314
  })
@@ -526,7 +534,7 @@ export function recordAssignmentOverride(
526
534
  const outer = assignmentOverrideOwner(graph, instanceId)
527
535
  if (!outer) return
528
536
  setInstanceOverride(
529
- outer.instanceOverrides,
537
+ ownInstanceOverrides(outer),
530
538
  outer.id,
531
539
  instanceId,
532
540
  assignmentOverrideField(propertyId),
@@ -594,9 +602,9 @@ function forgetOverridesOf(graph: SceneGraph, nodeId: string): void {
594
602
  if (!parentId) return
595
603
  graph.closest(parentId, (ancestor) => {
596
604
  if (ancestor.type !== 'INSTANCE') return false
597
- const { descendants } = ancestor.instanceOverrides
598
- if (ids.some((id) => descendants.delete(id)))
599
- graph.updateNode(ancestor.id, { instanceOverrides: ancestor.instanceOverrides })
605
+ const owned = ownInstanceOverrides(ancestor)
606
+ if (ids.some((id) => owned.descendants.delete(id)))
607
+ graph.updateNode(ancestor.id, { instanceOverrides: owned })
600
608
  return false
601
609
  })
602
610
  }
@@ -663,13 +671,13 @@ export function replaceInstanceLayer(
663
671
  })
664
672
  graph.deleteNode(target.id)
665
673
  setInstanceOverride(
666
- owner.instanceOverrides,
674
+ ownInstanceOverrides(owner),
667
675
  owner.id,
668
676
  replacementId,
669
677
  REPLACED_LAYER_OVERRIDE,
670
678
  layerId
671
679
  )
672
- graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })
680
+ graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) })
673
681
  return true
674
682
  }
675
683
 
@@ -1,5 +1,7 @@
1
1
  export type InstanceOverrideField = string
2
2
 
3
+ import type { SceneNode } from '../types'
4
+
3
5
  export interface InstanceOverrideState {
4
6
  self: Map<InstanceOverrideField, unknown>
5
7
  descendants: Map<string, Map<InstanceOverrideField, unknown>>
@@ -74,6 +76,53 @@ export function createInstanceOverrideState(): InstanceOverrideState {
74
76
  return { self: new Map(), descendants: new Map() }
75
77
  }
76
78
 
79
+ const SHARED_STATE_WRITE =
80
+ 'the shared empty instance overrides are read-only; call ownInstanceOverrides(node) first'
81
+
82
+ /** A map the shared state throws from on every write, which still answers all reads. */
83
+ class SharedOverrideMap<K, V> extends Map<K, V> {
84
+ override set(key: K, value: V): this {
85
+ void key
86
+ void value
87
+ throw new Error(SHARED_STATE_WRITE)
88
+ }
89
+
90
+ override delete(key: K): boolean {
91
+ void key
92
+ throw new Error(SHARED_STATE_WRITE)
93
+ }
94
+
95
+ override clear(): void {
96
+ throw new Error(SHARED_STATE_WRITE)
97
+ }
98
+ }
99
+
100
+ /**
101
+ * What a layer holds until it records an override of its own. Shared and frozen, so an empty state
102
+ * costs nothing per layer and a write that skipped `ownInstanceOverrides` throws where it happens
103
+ * instead of reaching every layer of every document.
104
+ */
105
+ export const EMPTY_INSTANCE_OVERRIDES: InstanceOverrideState = Object.freeze({
106
+ self: new SharedOverrideMap<InstanceOverrideField, unknown>(),
107
+ descendants: new SharedOverrideMap<string, Map<InstanceOverrideField, unknown>>()
108
+ })
109
+
110
+ export function isEmptyInstanceOverrideState(state: InstanceOverrideState): boolean {
111
+ return state.self.size === 0 && state.descendants.size === 0
112
+ }
113
+
114
+ /**
115
+ * The layer's own override state, giving it a fresh one when it still holds the shared empty
116
+ * state. Writers record through this and then persist it with `updateNode`, so the change reaches
117
+ * events and undo instead of only the layer.
118
+ */
119
+ export function ownInstanceOverrides(node: SceneNode): InstanceOverrideState {
120
+ if (node.instanceOverrides !== EMPTY_INSTANCE_OVERRIDES) return node.instanceOverrides
121
+ const owned = createInstanceOverrideState()
122
+ node.instanceOverrides = owned
123
+ return owned
124
+ }
125
+
77
126
  export interface SerializedOverrideValue {
78
127
  defined: boolean
79
128
  value?: unknown
@@ -5,6 +5,7 @@ import {
5
5
  isLayerReferenceOverride,
6
6
  overriddenBindingField,
7
7
  overriddenVariableModeCollection,
8
+ ownInstanceOverrides,
8
9
  setInstanceOverride
9
10
  } from './overrides'
10
11
  import { copyProp } from './sync'
@@ -117,7 +118,7 @@ export function restoreInstanceOverrides(
117
118
  const changes = changesFor(layer)
118
119
  if (Object.keys(changes).length) graph.updateNode(child.id, changes)
119
120
  for (const field of layer.fields)
120
- setInstanceOverride(instance.instanceOverrides, instance.id, child.id, field)
121
+ setInstanceOverride(ownInstanceOverrides(instance), instance.id, child.id, field)
121
122
  }
122
- graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
123
+ graph.updateNode(instance.id, { instanceOverrides: ownInstanceOverrides(instance) })
123
124
  }
@@ -23,6 +23,7 @@ import {
23
23
  copyAppliedBoundPaints,
24
24
  keepCopyBoundPaints
25
25
  } from '../variables/paints'
26
+ import { createVariableResolver, type VariableResolver } from '../variables/resolver'
26
27
  import { scaleVariableBindingUnits } from '../variables/units'
27
28
  import { applyEnclosingAssignments, assignedFieldValues, propertyDrivenFields } from './assignments'
28
29
  import { keepOwnContentSize, remeasureChangedText, type SyncedPlacement } from './content-size'
@@ -220,13 +221,14 @@ export function updateSyncedProps(
220
221
  /** A field the copy keeps as its own, which the sync leaves as it is. */
221
222
  kept: (field: string) => boolean = () => false
222
223
  ): void {
223
- resolveBoundNumbersInPlace(graph, target, updates, kept)
224
+ const resolver = createVariableResolver(graph)
225
+ resolveBoundNumbersInPlace(graph, target, updates, kept, resolver)
224
226
  if (updates.fills || updates.strokes || updates.boundVariables) {
225
227
  applySyncedModes(graph, target, updates)
226
- keepCopyBoundPaints(graph, target, updates)
228
+ keepCopyBoundPaints(graph, target, updates, resolver)
227
229
  }
228
230
  // After the copy's own bound paints, which can bring its strokes into the write.
229
- applySyncedStrokeLines(graph, target, updates, kept)
231
+ applySyncedStrokeLines(graph, target, updates, kept, resolver)
230
232
  const changed = Object.fromEntries(
231
233
  Object.entries(updates).filter(
232
234
  ([key, value]) => !isEqual(target[key as keyof SceneNode], value)
@@ -246,7 +248,8 @@ function resolveBoundNumbersInPlace(
246
248
  graph: SceneGraph,
247
249
  target: SceneNode,
248
250
  updates: Partial<SceneNode>,
249
- kept: (field: string) => boolean
251
+ kept: (field: string) => boolean,
252
+ resolver: VariableResolver
250
253
  ): void {
251
254
  const bound = updates.boundVariables ?? target.boundVariables
252
255
  // The fields the sync writes, and the ones it binds anew, which keep an equal value only in
@@ -259,7 +262,7 @@ function resolveBoundNumbersInPlace(
259
262
  )
260
263
  if (synced.length === 0) return
261
264
  applySyncedModes(graph, target, updates)
262
- const resolved = resolvedNumericBindings(graph, { ...target, ...updates })
265
+ const resolved = resolvedNumericBindings(graph, { ...target, ...updates }, 'active', resolver)
263
266
  Object.assign(updates, pick(resolved, synced as (keyof SceneNode)[]))
264
267
  }
265
268
 
@@ -278,7 +281,8 @@ export function applySyncedStrokeLines(
278
281
  graph: SceneGraph,
279
282
  target: SceneNode,
280
283
  updates: Partial<SceneNode>,
281
- kept: (field: string) => boolean
284
+ kept: (field: string) => boolean,
285
+ resolver: VariableResolver = createVariableResolver(graph)
282
286
  ): void {
283
287
  const strokes = updates.strokes
284
288
  const first = strokes?.at(0)
@@ -289,7 +293,7 @@ export function applySyncedStrokeLines(
289
293
  const weightScale =
290
294
  (updates.variableBindingScales ?? target.variableBindingScales).strokeWeight ?? 1
291
295
  const resolvedWeight = boundWeight
292
- ? graph.resolveNumberVariableForNode(target.id, boundWeight, 'active')
296
+ ? resolver.forNode(target.id, 'active').number(boundWeight)
293
297
  : undefined
294
298
  const lines: StrokeLines = {}
295
299
  let set = false
@@ -6,7 +6,7 @@ import {
6
6
  } from './constants'
7
7
  import { normalizeEffects } from './effects'
8
8
  import { EMPTY_LIST, EMPTY_RECORD, shareEmptyNodeValues } from './empty-values'
9
- import { createInstanceOverrideState } from './instances/overrides'
9
+ import { EMPTY_INSTANCE_OVERRIDES } from './instances/overrides'
10
10
  import { NO_LETTER_SPACING } from './text/lengths'
11
11
  import type { NodeType, SceneNode, SourceMetadata } from './types'
12
12
 
@@ -232,7 +232,7 @@ export function createDefaultNode(
232
232
  shapeUserHeight: 0,
233
233
  shapeTruncates: false,
234
234
  componentId: null,
235
- instanceOverrides: createInstanceOverrideState(),
235
+ instanceOverrides: EMPTY_INSTANCE_OVERRIDES,
236
236
  componentPropertyDefinitions: EMPTY_LIST,
237
237
  componentPropertyReferences: EMPTY_LIST,
238
238
  componentPropertyAssignments: EMPTY_RECORD,
@@ -18,12 +18,10 @@ import { tokenSourcesSchema } from '../token-sources/schema'
18
18
  import {
19
19
  MODE_ATTRIBUTE_PATTERN,
20
20
  TOKEN_UNITS,
21
- type EnabledLibraryBinding,
22
21
  type ExportSetting,
23
22
  type LayoutDirection,
24
23
  type LibraryAssetSource,
25
24
  type PluginDataEntry,
26
- type SourceLibraryPublication,
27
25
  type TextDirection,
28
26
  type TokenUnit
29
27
  } from '../types'
@@ -34,7 +32,7 @@ import {
34
32
  withoutPluginData,
35
33
  type PluginDataKey
36
34
  } from './field'
37
- import { webCitationSchema } from './schema'
35
+ import { enabledLibrariesSchema, sourceLibraryPublicationSchema, webCitationSchema } from './schema'
38
36
 
39
37
  const DIRECTIONS = ['AUTO', 'LTR', 'RTL'] as const satisfies readonly (
40
38
  | TextDirection
@@ -79,6 +77,11 @@ const exportSettingsSchema: v.GenericSchema<unknown, ExportSetting[]> = v.array(
79
77
  )
80
78
  )
81
79
 
80
+ const clipboardOriginSchema = v.object({
81
+ documentId: v.pipe(v.string(), v.nonEmpty(), v.maxLength(64)),
82
+ nodeId: v.pipe(v.string(), v.nonEmpty(), v.maxLength(64))
83
+ })
84
+
82
85
  const librarySourceSchema: v.GenericSchema<unknown, LibraryAssetSource> = v.pipe(
83
86
  v.object({
84
87
  identity: v.object({ libraryId: v.string(), assetKey: v.string(), revisionId: v.string() }),
@@ -92,25 +95,6 @@ const librarySourceSchema: v.GenericSchema<unknown, LibraryAssetSource> = v.pipe
92
95
  }))
93
96
  )
94
97
 
95
- const enabledLibrarySchema = v.object({
96
- libraryId: v.string(),
97
- revisionId: v.string(),
98
- enabled: v.optional(v.unknown())
99
- })
100
-
101
- /** Invalid entries are skipped one by one, so one bad binding keeps the others. */
102
- const enabledLibrariesSchema: v.GenericSchema<unknown, EnabledLibraryBinding[]> = v.pipe(
103
- v.array(v.unknown()),
104
- v.transform((items) =>
105
- items.flatMap((item) => {
106
- const parsed = v.safeParse(enabledLibrarySchema, item)
107
- if (!parsed.success) return []
108
- const { libraryId, revisionId, enabled } = parsed.output
109
- return [{ libraryId, revisionId, enabled: enabled === true }]
110
- })
111
- )
112
- )
113
-
114
98
  // Shape only. Whether a string is valid CSS is checked where it is written into a stylesheet.
115
99
  const cssTextSchema = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(1000))
116
100
 
@@ -196,15 +180,6 @@ const meshFillsSchema: v.GenericSchema<unknown, StoredMeshFill[]> = v.pipe(
196
180
  )
197
181
  )
198
182
 
199
- const sourceLibraryPublicationSchema: v.GenericSchema<unknown, SourceLibraryPublication> = v.object(
200
- {
201
- libraryId: v.string(),
202
- revisionId: v.string(),
203
- name: v.string(),
204
- catalogSource: v.optional(v.string())
205
- }
206
- )
207
-
208
183
  /**
209
184
  * Every plugin-data entry Pairdraw writes under {@link PAIRDRAW_PLUGIN_ID}: state Figma's
210
185
  * format has no field for. Add a key here, never as a string elsewhere, so reading and writing
@@ -231,6 +206,11 @@ export const PAIRDRAW_PLUGIN_DATA = {
231
206
  textPathBox: jsonPluginDataField('textPathBox', 'format', textPathBoxSchema),
232
207
  /** The library asset a node was inserted from. */
233
208
  librarySource: jsonPluginDataField('librarySource', 'bookkeeping', librarySourceSchema),
209
+ /**
210
+ * Where a layer of a pasted component came from: the copying document's root id and the node's id
211
+ * there. A later paste of the same snapshot into that document reuses the component it made.
212
+ */
213
+ clipboardOrigin: jsonPluginDataField('clipboardOrigin', 'bookkeeping', clipboardOriginSchema),
234
214
  /**
235
215
  * The document root's id, on the DOCUMENT node, whose own GUID is always Figma's `0:0`; the
236
216
  * root keeps it across a save as every layer keeps its GUID.
@@ -248,6 +228,11 @@ export const PAIRDRAW_PLUGIN_DATA = {
248
228
  'bookkeeping',
249
229
  sourceLibraryPublicationSchema
250
230
  ),
231
+ /**
232
+ * The `.pen` documents this document imports, by alias and relative path, on the DOCUMENT node.
233
+ * A `.pen` file names them in its own `imports`, so a save writes them back from here.
234
+ */
235
+ penImports: jsonPluginDataField('penImports', 'bookkeeping', v.record(v.string(), v.string())),
251
236
  /** Canvas comment threads, deleted ones included, on the DOCUMENT node. */
252
237
  comments: jsonPluginDataField('comments', 'bookkeeping', commentThreadsSchema),
253
238
  /** The statuses layers can be in, on the DOCUMENT node. */
@@ -1,3 +1,4 @@
1
1
  export * from './field'
2
2
  export * from './fields'
3
3
  export * from './citation'
4
+ export { enabledLibrariesSchema, sourceLibraryPublicationSchema } from './schema'