@open-pencil/scene-graph 0.17.0-beta.2 → 0.17.0-beta.3

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 (244) hide show
  1. package/dist/asset-keys.d.ts +11 -1
  2. package/dist/asset-keys.d.ts.map +1 -1
  3. package/dist/asset-keys.js +16 -1
  4. package/dist/asset-keys.js.map +1 -1
  5. package/dist/checkpoint.d.ts +3 -3
  6. package/dist/checkpoint.d.ts.map +1 -1
  7. package/dist/checkpoint.js +53 -23
  8. package/dist/checkpoint.js.map +1 -1
  9. package/dist/components/index.d.ts +2 -2
  10. package/dist/components/index.js +2 -2
  11. package/dist/components/properties.d.ts +6 -1
  12. package/dist/components/properties.d.ts.map +1 -1
  13. package/dist/components/properties.js +9 -1
  14. package/dist/components/properties.js.map +1 -1
  15. package/dist/constants.d.ts +6 -1
  16. package/dist/constants.d.ts.map +1 -1
  17. package/dist/constants.js +17 -1
  18. package/dist/constants.js.map +1 -1
  19. package/dist/constraints.d.ts +25 -0
  20. package/dist/constraints.d.ts.map +1 -0
  21. package/dist/constraints.js +51 -0
  22. package/dist/constraints.js.map +1 -0
  23. package/dist/coordinate.d.ts +64 -1
  24. package/dist/coordinate.d.ts.map +1 -1
  25. package/dist/coordinate.js +217 -1
  26. package/dist/coordinate.js.map +1 -1
  27. package/dist/copy.d.ts.map +1 -1
  28. package/dist/copy.js +8 -1
  29. package/dist/copy.js.map +1 -1
  30. package/dist/css/index.d.ts +3 -2
  31. package/dist/css/index.js +3 -2
  32. package/dist/css/text.d.ts +28 -1
  33. package/dist/css/text.d.ts.map +1 -1
  34. package/dist/css/text.js +84 -17
  35. package/dist/css/text.js.map +1 -1
  36. package/dist/css/transform.d.ts +34 -0
  37. package/dist/css/transform.d.ts.map +1 -0
  38. package/dist/css/transform.js +320 -0
  39. package/dist/css/transform.js.map +1 -0
  40. package/dist/css/values.d.ts.map +1 -1
  41. package/dist/css/values.js +11 -1
  42. package/dist/css/values.js.map +1 -1
  43. package/dist/figjam/palette.d.ts +1 -1
  44. package/dist/figjam/palette.js +1 -1
  45. package/dist/figjam/palette.js.map +1 -1
  46. package/dist/geometry.d.ts +8 -1
  47. package/dist/geometry.d.ts.map +1 -1
  48. package/dist/geometry.js +19 -8
  49. package/dist/geometry.js.map +1 -1
  50. package/dist/graph.d.ts +48 -12
  51. package/dist/graph.d.ts.map +1 -1
  52. package/dist/graph.js +110 -24
  53. package/dist/graph.js.map +1 -1
  54. package/dist/group-bounds.d.ts +14 -4
  55. package/dist/group-bounds.d.ts.map +1 -1
  56. package/dist/group-bounds.js +76 -11
  57. package/dist/group-bounds.js.map +1 -1
  58. package/dist/hit-test.d.ts +5 -0
  59. package/dist/hit-test.d.ts.map +1 -1
  60. package/dist/hit-test.js +18 -12
  61. package/dist/hit-test.js.map +1 -1
  62. package/dist/images.d.ts +27 -3
  63. package/dist/images.d.ts.map +1 -1
  64. package/dist/images.js +57 -3
  65. package/dist/images.js.map +1 -1
  66. package/dist/index.d.ts +2 -2
  67. package/dist/instances/index.d.ts.map +1 -1
  68. package/dist/instances/index.js +3 -0
  69. package/dist/instances/index.js.map +1 -1
  70. package/dist/instances/placement.js +55 -12
  71. package/dist/instances/placement.js.map +1 -1
  72. package/dist/instances/swap.js +3 -0
  73. package/dist/instances/swap.js.map +1 -1
  74. package/dist/instances/sync.js +34 -13
  75. package/dist/instances/sync.js.map +1 -1
  76. package/dist/node-defaults.d.ts.map +1 -1
  77. package/dist/node-defaults.js +1 -0
  78. package/dist/node-defaults.js.map +1 -1
  79. package/dist/order-keys.d.ts +3 -1
  80. package/dist/order-keys.d.ts.map +1 -1
  81. package/dist/order-keys.js +6 -1
  82. package/dist/order-keys.js.map +1 -1
  83. package/dist/plugin-data/fields.d.ts +2 -0
  84. package/dist/plugin-data/fields.d.ts.map +1 -1
  85. package/dist/plugin-data/fields.js +2 -0
  86. package/dist/plugin-data/fields.js.map +1 -1
  87. package/dist/resize.d.ts +22 -11
  88. package/dist/resize.d.ts.map +1 -1
  89. package/dist/resize.js +227 -93
  90. package/dist/resize.js.map +1 -1
  91. package/dist/scaling/index.d.ts +3 -2
  92. package/dist/scaling/index.js +3 -2
  93. package/dist/scaling/node.d.ts.map +1 -1
  94. package/dist/scaling/node.js +5 -1
  95. package/dist/scaling/node.js.map +1 -1
  96. package/dist/scaling/snapshot.d.ts +25 -0
  97. package/dist/scaling/snapshot.d.ts.map +1 -0
  98. package/dist/scaling/snapshot.js +39 -0
  99. package/dist/scaling/snapshot.js.map +1 -0
  100. package/dist/scaling/tree.d.ts +24 -2
  101. package/dist/scaling/tree.d.ts.map +1 -1
  102. package/dist/scaling/tree.js +37 -14
  103. package/dist/scaling/tree.js.map +1 -1
  104. package/dist/shaders/model.d.ts.map +1 -1
  105. package/dist/shaders/model.js +2 -1
  106. package/dist/shaders/model.js.map +1 -1
  107. package/dist/shared-styles.d.ts +3 -1
  108. package/dist/shared-styles.d.ts.map +1 -1
  109. package/dist/shared-styles.js +7 -1
  110. package/dist/shared-styles.js.map +1 -1
  111. package/dist/slots/authoring.d.ts +3 -2
  112. package/dist/slots/authoring.d.ts.map +1 -1
  113. package/dist/slots/authoring.js +5 -3
  114. package/dist/slots/authoring.js.map +1 -1
  115. package/dist/slots/content.d.ts.map +1 -1
  116. package/dist/slots/content.js +4 -1
  117. package/dist/slots/content.js.map +1 -1
  118. package/dist/text/direction.d.ts +3 -1
  119. package/dist/text/direction.d.ts.map +1 -1
  120. package/dist/text/direction.js +5 -1
  121. package/dist/text/direction.js.map +1 -1
  122. package/dist/transfer/apply.d.ts.map +1 -1
  123. package/dist/transfer/apply.js +1 -6
  124. package/dist/transfer/apply.js.map +1 -1
  125. package/dist/transfer/copied.d.ts +35 -3
  126. package/dist/transfer/copied.d.ts.map +1 -1
  127. package/dist/transfer/copied.js +44 -13
  128. package/dist/transfer/copied.js.map +1 -1
  129. package/dist/transfer/dependencies.d.ts +38 -0
  130. package/dist/transfer/dependencies.d.ts.map +1 -0
  131. package/dist/transfer/dependencies.js +100 -0
  132. package/dist/transfer/dependencies.js.map +1 -0
  133. package/dist/transfer/history.js +0 -1
  134. package/dist/transfer/history.js.map +1 -1
  135. package/dist/transfer/index.d.ts +5 -3
  136. package/dist/transfer/index.js +5 -3
  137. package/dist/transfer/nodes.d.ts.map +1 -1
  138. package/dist/transfer/nodes.js +7 -14
  139. package/dist/transfer/nodes.js.map +1 -1
  140. package/dist/transfer/plan.d.ts +0 -1
  141. package/dist/transfer/plan.js +3 -5
  142. package/dist/transfer/plan.js.map +1 -1
  143. package/dist/transfer/remove.js +5 -2
  144. package/dist/transfer/remove.js.map +1 -1
  145. package/dist/transfer/resources.d.ts +21 -0
  146. package/dist/transfer/resources.d.ts.map +1 -0
  147. package/dist/transfer/resources.js +38 -0
  148. package/dist/transfer/resources.js.map +1 -0
  149. package/dist/transfer/variables.d.ts +8 -1
  150. package/dist/transfer/variables.d.ts.map +1 -1
  151. package/dist/transfer/variables.js +24 -1
  152. package/dist/transfer/variables.js.map +1 -1
  153. package/dist/types.d.ts +47 -2
  154. package/dist/types.d.ts.map +1 -1
  155. package/dist/types.js.map +1 -1
  156. package/dist/undo.d.ts +28 -3
  157. package/dist/undo.d.ts.map +1 -1
  158. package/dist/undo.js +24 -7
  159. package/dist/undo.js.map +1 -1
  160. package/dist/variables/bindings.d.ts +17 -14
  161. package/dist/variables/bindings.d.ts.map +1 -1
  162. package/dist/variables/bindings.js +30 -72
  163. package/dist/variables/bindings.js.map +1 -1
  164. package/dist/variables/fields.d.ts +1 -1
  165. package/dist/variables/fields.js +1 -1
  166. package/dist/variables/fields.js.map +1 -1
  167. package/dist/variables/formula/check.d.ts +1 -1
  168. package/dist/variables/formula/index.d.ts +2 -2
  169. package/dist/variables/formula/index.js +1 -1
  170. package/dist/variables/formula/index.js.map +1 -1
  171. package/dist/variables/formula/print.d.ts +1 -1
  172. package/dist/variables/formula/signatures.js +1 -1
  173. package/dist/variables/index.d.ts +6 -6
  174. package/dist/variables/index.d.ts.map +1 -1
  175. package/dist/variables/index.js +40 -24
  176. package/dist/variables/index.js.map +1 -1
  177. package/dist/variables/paints.d.ts +57 -0
  178. package/dist/variables/paints.d.ts.map +1 -0
  179. package/dist/variables/paints.js +231 -0
  180. package/dist/variables/paints.js.map +1 -0
  181. package/dist/variables/resolution.d.ts +14 -11
  182. package/dist/variables/resolution.d.ts.map +1 -1
  183. package/dist/variables/resolution.js +36 -17
  184. package/dist/variables/resolution.js.map +1 -1
  185. package/dist/variables/subtree.js +17 -0
  186. package/dist/variables/subtree.js.map +1 -0
  187. package/dist/vector-network.d.ts.map +1 -1
  188. package/dist/vector-network.js +2 -8
  189. package/dist/vector-network.js.map +1 -1
  190. package/package.json +8 -1
  191. package/src/asset-keys.ts +20 -0
  192. package/src/checkpoint.ts +87 -32
  193. package/src/components/properties.ts +9 -0
  194. package/src/constants.ts +17 -0
  195. package/src/constraints.ts +60 -0
  196. package/src/coordinate.ts +220 -0
  197. package/src/copy.ts +9 -4
  198. package/src/css/index.ts +17 -1
  199. package/src/css/text.ts +85 -17
  200. package/src/css/transform.ts +266 -0
  201. package/src/css/values.ts +8 -0
  202. package/src/figjam/palette.ts +1 -1
  203. package/src/geometry.ts +20 -9
  204. package/src/graph.ts +128 -42
  205. package/src/group-bounds.ts +84 -17
  206. package/src/hit-test.ts +30 -14
  207. package/src/images.ts +71 -3
  208. package/src/instances/index.ts +4 -0
  209. package/src/instances/placement.ts +63 -10
  210. package/src/instances/swap.ts +5 -0
  211. package/src/instances/sync.ts +48 -21
  212. package/src/node-defaults.ts +1 -0
  213. package/src/order-keys.ts +6 -0
  214. package/src/plugin-data/fields.ts +6 -0
  215. package/src/resize.ts +267 -119
  216. package/src/scaling/index.ts +9 -1
  217. package/src/scaling/node.ts +9 -1
  218. package/src/scaling/snapshot.ts +51 -0
  219. package/src/scaling/tree.ts +63 -19
  220. package/src/shaders/model.ts +2 -3
  221. package/src/shared-styles.ts +8 -0
  222. package/src/slots/authoring.ts +5 -3
  223. package/src/slots/content.ts +4 -1
  224. package/src/text/direction.ts +5 -0
  225. package/src/transfer/apply.ts +1 -13
  226. package/src/transfer/copied.ts +83 -15
  227. package/src/transfer/dependencies.ts +126 -0
  228. package/src/transfer/history.ts +0 -6
  229. package/src/transfer/index.ts +20 -2
  230. package/src/transfer/nodes.ts +10 -26
  231. package/src/transfer/plan.ts +3 -11
  232. package/src/transfer/remove.ts +5 -2
  233. package/src/transfer/resources.ts +54 -0
  234. package/src/transfer/variables.ts +34 -0
  235. package/src/types.ts +55 -1
  236. package/src/undo.ts +48 -10
  237. package/src/variables/bindings.ts +44 -91
  238. package/src/variables/fields.ts +1 -1
  239. package/src/variables/formula/index.ts +3 -1
  240. package/src/variables/index.ts +56 -38
  241. package/src/variables/paints.ts +296 -0
  242. package/src/variables/resolution.ts +39 -28
  243. package/src/variables/subtree.ts +15 -0
  244. package/src/vector-network.ts +4 -2
@@ -2,6 +2,7 @@ import { sha1 } from '@noble/hashes/legacy.js'
2
2
  import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'
3
3
 
4
4
  import { TRANSPARENT } from '../constants'
5
+ import { imagePaintHashes } from '../images'
5
6
  import { readAllPluginData, withAllPluginData } from '../plugin-data/field'
6
7
  import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'
7
8
  import { randomHex } from '../random'
@@ -43,9 +44,7 @@ export function withShaderPaints(
43
44
  paints: readonly Fill[],
44
45
  shaders: readonly ShaderPaint[] = []
45
46
  ): SceneNode['pluginData'] {
46
- const shown = new Set(
47
- paints.flatMap((paint) => (paint.type === 'IMAGE' && paint.imageHash ? [paint.imageHash] : []))
48
- )
47
+ const shown = new Set(imagePaintHashes(paints))
49
48
  const byImage = new Map(readShaderPaints(node).map((shader) => [shader.image, shader]))
50
49
  for (const shader of shaders) byImage.set(shader.image, shader)
51
50
  return withAllPluginData(
@@ -103,6 +103,14 @@ export function sharedStyleTypeForKind(kind: SharedStyleKind): SharedStyleType {
103
103
  return STYLE_TYPES[kind]
104
104
  }
105
105
 
106
+ /** The document's shared style layers, by the source ID layers link them by. */
107
+ export function sharedStyleLayers(graph: SceneGraph): Map<string, SceneNode> {
108
+ const styles = new Map<string, SceneNode>()
109
+ for (const node of graph.getAllNodes())
110
+ if (node.sharedStyleType !== null && node.source.id) styles.set(node.source.id, node)
111
+ return styles
112
+ }
113
+
106
114
  export function getSharedStyles(graph: SceneGraph, kind: SharedStyleKind): SharedStyle[] {
107
115
  const type = sharedStyleTypeForKind(kind)
108
116
  const styles: SharedStyle[] = []
@@ -1,3 +1,4 @@
1
+ import { propertyOwner } from '../components/properties'
1
2
  import type { SceneGraph } from '../graph'
2
3
  import type { ComponentPropertyDefinition, SceneNode, SlotSettings } from '../types'
3
4
  import { slotPropertyId } from './frames'
@@ -10,13 +11,14 @@ export const DEFAULT_SLOT_SETTINGS: SlotSettings = {
10
11
  }
11
12
 
12
13
  /**
13
- * The main component a layer belongs to, which defines the slots inside it. Layers of an
14
- * instance are not authored there, so a layer under an instance has none.
14
+ * The main component or set that defines the slots inside a layer: the component the layer
15
+ * belongs to, or that component's set. Layers of an instance are not authored there, so a
16
+ * layer under an instance has none.
15
17
  */
16
18
  export function slotOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {
17
19
  let current = node.parentId ? graph.getNode(node.parentId) : undefined
18
20
  while (current && current.type !== 'CANVAS') {
19
- if (current.type === 'COMPONENT') return current
21
+ if (current.type === 'COMPONENT') return propertyOwner(graph, current)
20
22
  if (current.type === 'INSTANCE') return undefined
21
23
  current = current.parentId ? graph.getNode(current.parentId) : undefined
22
24
  }
@@ -3,6 +3,7 @@ import type { SceneGraph } from '../graph'
3
3
  import { getInstanceOverride, setInstanceOverride } from '../instances/overrides'
4
4
  import { cloneChildrenWithMapping } from '../instances/sync'
5
5
  import type { SceneNode } from '../types'
6
+ import { applyBoundPaintColorsIn } from '../variables/paints'
6
7
  import { ownsSlotContent, slotPropertyId } from './frames'
7
8
 
8
9
  /**
@@ -116,7 +117,9 @@ export function resetSlotContent(
116
117
  Reflect.deleteProperty(assignments, propertyId)
117
118
  graph.updateNode(instance.id, { componentPropertyAssignments: assignments })
118
119
  const source = componentSource(instance, frame)
119
- if (source && graph.nodes.has(source)) cloneChildrenWithMapping(graph, source, frame.id)
120
+ if (!source || !graph.nodes.has(source)) return
121
+ cloneChildrenWithMapping(graph, source, frame.id)
122
+ for (const childId of frame.childIds) applyBoundPaintColorsIn(graph, childId)
120
123
  }
121
124
 
122
125
  /** Remove everything from the slot; the instance keeps owning it, now empty. */
@@ -4,6 +4,11 @@ const RTL_CHAR_RE =
4
4
  /\p{Script=Arabic}|\p{Script=Hebrew}|\p{Script=Syriac}|\p{Script=Thaana}|\p{Script=Nko}|\p{Script=Adlam}/u
5
5
  const LTR_CHAR_RE = /\p{Script=Latin}|\p{Script=Cyrillic}|\p{Script=Greek}/u
6
6
 
7
+ /** Whether the text has a letter of a right-to-left script, such as Arabic or Hebrew. */
8
+ export function containsRTLText(text: string): boolean {
9
+ return RTL_CHAR_RE.test(text)
10
+ }
11
+
7
12
  export function detectTextDirection(text: string): Exclude<TextDirection, 'AUTO'> {
8
13
  for (const char of text) {
9
14
  if (RTL_CHAR_RE.test(char)) return 'RTL'
@@ -24,14 +24,6 @@ function validate(target: SceneGraph, plan: GraphTransferPlan): void {
24
24
  plan.collections,
25
25
  variableIdentityReferences(plan.variables, plan.collections)
26
26
  )
27
- for (const [id, mode] of plan.activeModes) {
28
- if (
29
- !plan.collections
30
- .find((collection) => collection.id === id)
31
- ?.modes.some((entry) => entry.modeId === mode)
32
- )
33
- throw new Error(`Invalid transferred active mode ${id}:${mode}`)
34
- }
35
27
  for (const collection of plan.collections) claim(collection.id)
36
28
  for (const variable of plan.variables) claim(variable.id)
37
29
  const parents = new Set(target.nodes.keys())
@@ -64,7 +56,6 @@ export function applyGraphTransfer(target: SceneGraph, input: GraphTransferPlan)
64
56
  try {
65
57
  for (const collection of plan.collections) target.addCollection(collection)
66
58
  for (const variable of plan.variables) target.addVariable(variable)
67
- for (const [id, mode] of plan.activeModes) target.activeMode.set(id, mode)
68
59
  for (const [hash, bytes] of plan.images)
69
60
  if (!target.images.has(hash)) target.images.set(hash, bytes)
70
61
  for (const node of plan.nodes)
@@ -73,10 +64,7 @@ export function applyGraphTransfer(target: SceneGraph, input: GraphTransferPlan)
73
64
  for (const node of plan.nodes.toReversed())
74
65
  if (target.getNode(node.id)) target.deleteNode(node.id)
75
66
  for (const variable of plan.variables) target.variables.delete(variable.id)
76
- for (const collection of plan.collections) {
77
- target.variableCollections.delete(collection.id)
78
- target.activeMode.delete(collection.id)
79
- }
67
+ for (const collection of plan.collections) target.variableCollections.delete(collection.id)
80
68
  for (const hash of imageIds) target.images.delete(hash)
81
69
  throw error
82
70
  }
@@ -3,44 +3,103 @@ import { isEqual, mapValues } from 'es-toolkit'
3
3
  import { componentPropertyDefinitions } from '../components/properties'
4
4
  import type { SceneGraph } from '../graph'
5
5
  import { remapInstanceOverrideState } from '../instances/overrides'
6
+ import { remapStyleRunReferences } from '../text/references'
6
7
  import type { ComponentPropertyDefinition, SceneNode } from '../types'
7
8
 
9
+ /** How a layer's references to other layers are resolved anew. */
10
+ export interface ReferenceResolvers {
11
+ /** The component a reference names now; `previous` is the one the layer named, if any. */
12
+ component: (id: string, previous: string | null) => string
13
+ /** The layer an override names now; `component` is the one its instance now draws. */
14
+ layer: (id: string, component: string | null) => string
15
+ /** The layer a connector's end follows now. */
16
+ endpoint: (id: string) => string
17
+ /**
18
+ * The layer a text link names now. Without it links keep naming their layers, as Figma's
19
+ * duplicate and paste do (desktop 126); copies into another document, which lacks those
20
+ * layers, pass it.
21
+ */
22
+ link?: (id: string) => string
23
+ variable: (id: string) => string
24
+ }
25
+
26
+ /** Copies placed in another document, whose text links must follow the copy. */
27
+ export interface CopiedReferenceOptions {
28
+ followTextLinks?: boolean
29
+ }
30
+
8
31
  function swapPropertyIds(definitions: readonly ComponentPropertyDefinition[]): string[] {
9
32
  return definitions
10
33
  .filter((definition) => definition.type === 'INSTANCE_SWAP')
11
34
  .map((definition) => definition.id)
12
35
  }
13
36
 
14
- function remappedReferences(
37
+ /** The instance-swap properties `nodes` define, whose values name components. */
38
+ export function instanceSwapPropertyIds(nodes: Iterable<SceneNode>): Set<string> {
39
+ return new Set([...nodes].flatMap((node) => swapPropertyIds(node.componentPropertyDefinitions)))
40
+ }
41
+
42
+ /**
43
+ * `node`'s references to other layers, resolved anew: its main component, the layers its
44
+ * overrides change and the components they swap in, the components its instance-swap properties
45
+ * default to or are set to, and the layers its connector ends follow. `previous` is the layer
46
+ * whose references these replace, so a resolver can keep what it already pointed at. Only the
47
+ * fields whose references change are returned: every write is an update collaboration sends.
48
+ */
49
+ export function resolvedReferences(
15
50
  node: SceneNode,
16
- mapped: (id: string) => string,
51
+ previous: SceneNode,
52
+ resolve: ReferenceResolvers,
17
53
  swapProperties: ReadonlySet<string>
18
54
  ): Partial<SceneNode> {
19
55
  const changes: Partial<SceneNode> = {}
20
- if (node.componentId && mapped(node.componentId) !== node.componentId)
21
- changes.componentId = mapped(node.componentId)
22
- // Only what a mapping changes: every write is an update collaboration sends.
56
+ const componentId = node.componentId
57
+ ? resolve.component(node.componentId, previous.componentId)
58
+ : null
59
+ if (componentId !== node.componentId) changes.componentId = componentId
23
60
  const overrides = remapInstanceOverrideState(node.instanceOverrides, {
24
- node: mapped,
25
- variable: (id) => id
61
+ node: (id) => resolve.layer(id, componentId),
62
+ variable: resolve.variable
26
63
  })
27
64
  if (!isEqual(overrides, node.instanceOverrides)) changes.instanceOverrides = overrides
65
+ const previousDefaults = new Map(
66
+ previous.componentPropertyDefinitions.map((definition) => [
67
+ definition.id,
68
+ definition.defaultValue
69
+ ])
70
+ )
28
71
  const definitions = node.componentPropertyDefinitions.map((definition) =>
29
72
  definition.type === 'INSTANCE_SWAP' && definition.defaultValue
30
- ? { ...definition, defaultValue: mapped(definition.defaultValue) }
73
+ ? {
74
+ ...definition,
75
+ defaultValue: resolve.component(
76
+ definition.defaultValue,
77
+ previousDefaults.get(definition.id) ?? null
78
+ )
79
+ }
31
80
  : definition
32
81
  )
33
82
  if (!isEqual(definitions, node.componentPropertyDefinitions))
34
83
  changes.componentPropertyDefinitions = definitions
35
84
  const assignments = mapValues(node.componentPropertyAssignments, (value, id) =>
36
- swapProperties.has(id) ? mapped(value) : value
85
+ swapProperties.has(id)
86
+ ? resolve.component(value, previous.componentPropertyAssignments[id] ?? null)
87
+ : value
37
88
  )
38
89
  if (!isEqual(assignments, node.componentPropertyAssignments))
39
90
  changes.componentPropertyAssignments = assignments
40
91
  for (const field of ['connectorStart', 'connectorEnd'] as const) {
41
92
  const endpoint = node[field]
42
- if (endpoint?.nodeId && mapped(endpoint.nodeId) !== endpoint.nodeId)
43
- changes[field] = { ...endpoint, nodeId: mapped(endpoint.nodeId) }
93
+ const nodeId = endpoint?.nodeId ? resolve.endpoint(endpoint.nodeId) : null
94
+ if (endpoint && nodeId && nodeId !== endpoint.nodeId) changes[field] = { ...endpoint, nodeId }
95
+ }
96
+ if (resolve.link) {
97
+ const styleRuns = remapStyleRunReferences(node.styleRuns, {
98
+ variable: (id) => id,
99
+ style: (id) => id,
100
+ node: resolve.link
101
+ })
102
+ if (!isEqual(styleRuns, node.styleRuns)) changes.styleRuns = styleRuns
44
103
  }
45
104
  return changes
46
105
  }
@@ -51,22 +110,31 @@ function remappedReferences(
51
110
  * components an instance-swap property defaults to or is set to, and the layers a connector's
52
111
  * ends follow. `mappedIds` maps each copied layer to its copy, such as a library copy or a design
53
112
  * JSX render folded into the layers it replaces; a reference outside the copy stays as it is, and
54
- * so do variable IDs, since the copies keep their source's variables.
113
+ * so do variable IDs, since the copies keep their source's variables. Text links follow the copy
114
+ * only with `followTextLinks`.
55
115
  */
56
116
  export function remapCopiedReferences(
57
117
  graph: SceneGraph,
58
- mappedIds: ReadonlyMap<string, string>
118
+ mappedIds: ReadonlyMap<string, string>,
119
+ options: CopiedReferenceOptions = {}
59
120
  ): void {
60
121
  const mapped = (id: string) => mappedIds.get(id) ?? id
122
+ const resolve: ReferenceResolvers = {
123
+ component: mapped,
124
+ layer: mapped,
125
+ endpoint: mapped,
126
+ link: options.followTextLinks ? mapped : undefined,
127
+ variable: (id) => id
128
+ }
61
129
  const copies = [...mappedIds.values()].flatMap((id) => graph.getNode(id) ?? [])
62
- const copiedSwaps = copies.flatMap((node) => swapPropertyIds(node.componentPropertyDefinitions))
130
+ const copiedSwaps = instanceSwapPropertyIds(copies)
63
131
  for (const node of copies) {
64
132
  // An instance's swap property may be defined on a component the copy leaves behind.
65
133
  const swapProperties = new Set([
66
134
  ...copiedSwaps,
67
135
  ...swapPropertyIds(componentPropertyDefinitions(graph, node))
68
136
  ])
69
- const changes = remappedReferences(node, mapped, swapProperties)
137
+ const changes = resolvedReferences(node, node, resolve, swapProperties)
70
138
  if (Object.keys(changes).length > 0) graph.updateNode(node.id, changes)
71
139
  }
72
140
  }
@@ -0,0 +1,126 @@
1
+ import type { SceneGraph } from '../graph'
2
+ import { imagePaintHashes } from '../images'
3
+ import { overriddenBindingField } from '../instances/overrides'
4
+ import { referencedStyleIds, sharedStyleLayers } from '../shared-styles'
5
+ import { styleRunReferences } from '../text/references'
6
+ import type { SceneNode } from '../types'
7
+ import { isUnsupportedVariableValue, variableValueReferences } from '../variables/value'
8
+ import { regionFills } from '../vector-network'
9
+
10
+ /** What layers need from their document to draw the same in another one. */
11
+ export interface LayerDependencies {
12
+ /** The variables the layers and their styles bind, and every variable those alias. */
13
+ variables: Set<string>
14
+ /**
15
+ * The collections of those variables, those the layers set a mode of, and those a kept
16
+ * expression names a mode of.
17
+ */
18
+ collections: Set<string>
19
+ /** The shared styles the layers use, as the style layers that define them. */
20
+ styles: SceneNode[]
21
+ /** The images the layers and their styles paint with. */
22
+ images: Set<string>
23
+ }
24
+
25
+ /** The variables a layer names: its own bindings, its characters', and its overrides'. */
26
+ export function layerVariableIds(node: SceneNode): string[] {
27
+ const { self, descendants } = node.instanceOverrides
28
+ const overridden = [...self, ...[...descendants.values()].flatMap((fields) => [...fields])]
29
+ return [
30
+ ...Object.values(node.boundVariables),
31
+ ...styleRunReferences(node.styleRuns).variables,
32
+ ...overridden.flatMap(([field, value]) =>
33
+ typeof value === 'string' && overriddenBindingField(field) !== null ? [value] : []
34
+ )
35
+ ]
36
+ }
37
+
38
+ /**
39
+ * The images a layer paints with: its fills, strokes, vector regions, text decorations, and
40
+ * characters.
41
+ */
42
+ export function layerImageHashes(node: SceneNode): string[] {
43
+ return imagePaintHashes([
44
+ ...node.fills,
45
+ ...node.strokes,
46
+ ...regionFills(node.vectorNetwork),
47
+ ...node.textDecorationFills,
48
+ ...node.styleRuns.flatMap((run) => [
49
+ ...(run.style.fills ?? []),
50
+ ...(run.style.textDecorationFills ?? [])
51
+ ])
52
+ ])
53
+ }
54
+
55
+ /**
56
+ * The variables, collections, styles, and images `layers` depend on, as a copy into another
57
+ * document must carry them: a style brings what it binds and paints with in turn, and a variable
58
+ * brings the variables it aliases.
59
+ */
60
+ export function layerDependencies(
61
+ graph: SceneGraph,
62
+ layers: Iterable<SceneNode>
63
+ ): LayerDependencies {
64
+ const collections = new Set<string>()
65
+ const images = new Set<string>()
66
+ const styles = new Map<string, SceneNode>()
67
+ const pending: string[] = []
68
+ let styleLayers: Map<string, SceneNode> | undefined
69
+ const styleLayer = (id: string): SceneNode | undefined =>
70
+ (styleLayers ??= sharedStyleLayers(graph)).get(id)
71
+ const visit = (node: SceneNode): void => {
72
+ for (const hash of layerImageHashes(node)) images.add(hash)
73
+ pending.push(...layerVariableIds(node))
74
+ for (const id of Object.keys(node.variableModes))
75
+ if (graph.variableCollections.has(id)) collections.add(id)
76
+ for (const id of referencedStyleIds(node)) {
77
+ const style = styles.has(id) ? undefined : styleLayer(id)
78
+ if (!style) continue
79
+ styles.set(id, style)
80
+ visit(style)
81
+ }
82
+ }
83
+ for (const node of layers) visit(node)
84
+ const resolved = variableDependencies(graph, pending)
85
+ for (const id of resolved.collections) collections.add(id)
86
+ return { variables: resolved.variables, collections, styles: [...styles.values()], images }
87
+ }
88
+
89
+ /**
90
+ * These variables and every variable they alias, at any depth, with their collections and the
91
+ * collections a kept expression names a mode of.
92
+ */
93
+ export function variableDependencies(
94
+ graph: SceneGraph,
95
+ ids: Iterable<string>
96
+ ): Pick<LayerDependencies, 'variables' | 'collections'> {
97
+ const pending = [...ids]
98
+ const variables = new Set<string>()
99
+ const collections = new Set<string>()
100
+ let modeCollections: Map<string, string> | undefined
101
+ const collectionOfMode = (modeId: string): string | undefined => {
102
+ modeCollections ??= new Map(
103
+ [...graph.variableCollections.values()].flatMap((collection) =>
104
+ collection.modes.map((mode) => [mode.modeId, collection.id] as const)
105
+ )
106
+ )
107
+ return modeCollections.get(modeId)
108
+ }
109
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
110
+ if (variables.has(id)) continue
111
+ const variable = graph.variables.get(id)
112
+ if (!variable) continue
113
+ variables.add(id)
114
+ collections.add(variable.collectionId)
115
+ for (const value of Object.values(variable.valuesByMode)) {
116
+ pending.push(...variableValueReferences(value))
117
+ // A kept expression can name a mode of a collection none of its aliases reach.
118
+ if (!isUnsupportedVariableValue(value)) continue
119
+ for (const modeId of value.modes) {
120
+ const collection = collectionOfMode(modeId)
121
+ if (collection) collections.add(collection)
122
+ }
123
+ }
124
+ }
125
+ return { variables, collections }
126
+ }
@@ -33,12 +33,6 @@ export function captureTransferredState(
33
33
  requireValue(graph.variableCollections.get(collection.id), 'collection', collection.id)
34
34
  )
35
35
  ),
36
- activeModes: new Map(
37
- original.collections.map((collection) => [
38
- collection.id,
39
- requireValue(graph.activeMode.get(collection.id), 'active mode', collection.id)
40
- ])
41
- ),
42
36
  images: new Map(
43
37
  [...original.images.keys()].map((hash) => [
44
38
  hash,
@@ -3,5 +3,23 @@ export { captureTransferredState } from './history'
3
3
  export { applyGraphTransfer, type GraphTransferPlan } from './apply'
4
4
  export { prepareGraphTransfer, type GraphTransferInput } from './plan'
5
5
  export { prepareNodeTransfer, type NodeTransferReferences } from './nodes'
6
- export { prepareVariableTransfer, type VariableTransferReferences } from './variables'
7
- export { remapCopiedReferences } from './copied'
6
+ export {
7
+ copyVariableTables,
8
+ prepareVariableTransfer,
9
+ type VariableTransferReferences
10
+ } from './variables'
11
+ export {
12
+ instanceSwapPropertyIds,
13
+ remapCopiedReferences,
14
+ resolvedReferences,
15
+ type CopiedReferenceOptions,
16
+ type ReferenceResolvers
17
+ } from './copied'
18
+ export {
19
+ layerDependencies,
20
+ layerImageHashes,
21
+ layerVariableIds,
22
+ variableDependencies,
23
+ type LayerDependencies
24
+ } from './dependencies'
25
+ export { remappedResourceReferences, type ResourceReferences } from './resources'
@@ -1,9 +1,10 @@
1
1
  import { cloneNodeProps } from '../copy'
2
2
  import { overriddenBindingField, remapInstanceOverrideState } from '../instances/overrides'
3
3
  import { referencedStyleIds } from '../shared-styles'
4
- import { remapStyleRunReferences, styleRunReferences } from '../text/references'
4
+ import { styleRunReferences } from '../text/references'
5
5
  import type { ComponentPropertyType, SceneNode } from '../types'
6
6
  import { requireTransferReference as required } from './references'
7
+ import { remappedResourceReferences } from './resources'
7
8
  import type { VariableTransferReferences } from './variables'
8
9
 
9
10
  export function semanticTransferReferences(node: SceneNode): string[] {
@@ -68,40 +69,23 @@ export function prepareNodeTransfer(
68
69
  variable,
69
70
  collection: (id) => refs.collections.get(id)
70
71
  })
71
- result.boundVariables = Object.fromEntries(
72
- Object.entries(source.boundVariables).map(([field, id]) => [field, variable(id)])
73
- )
74
- result.variableModes = Object.fromEntries(
75
- Object.entries(source.variableModes).map(([collection, mode]) => [
76
- required(refs.collections, collection, 'collection'),
77
- required(refs.modes, mode, 'mode')
78
- ])
79
- )
80
- for (const field of [
81
- 'fillStyleId',
82
- 'strokeStyleId',
83
- 'textStyleId',
84
- 'effectStyleId',
85
- 'gridStyleId'
86
- ] as const) {
87
- result[field] = source[field] ? style(source[field]) : null
88
- }
89
- if (result.styleRuns) {
90
- // A link to a layer the transfer leaves behind keeps naming it.
91
- result.styleRuns = remapStyleRunReferences(result.styleRuns, {
72
+ Object.assign(
73
+ result,
74
+ remappedResourceReferences(source, {
92
75
  variable,
76
+ collection: (id) => required(refs.collections, id, 'collection'),
77
+ mode: (id) => required(refs.modes, id, 'mode'),
93
78
  style,
94
- node: (id) => refs.nodes.get(id) ?? id
79
+ // A link to a layer the transfer leaves behind keeps naming it.
80
+ layer: (id) => refs.nodes.get(id) ?? id
95
81
  })
96
- }
82
+ )
97
83
  // A connector keeps the layers it was attached to when they are left behind; the end becomes
98
84
  // free where nothing by that ID exists, as a pasted Figma connector does.
99
85
  for (const field of ['connectorStart', 'connectorEnd'] as const) {
100
86
  const endpoint = result[field]
101
87
  if (endpoint?.nodeId) endpoint.nodeId = refs.nodes.get(endpoint.nodeId) ?? endpoint.nodeId
102
88
  }
103
- for (const region of result.vectorNetwork?.regions ?? [])
104
- if (region.fillStyleId) region.fillStyleId = style(region.fillStyleId)
105
89
  result.componentPropertyDefinitions = source.componentPropertyDefinitions.map((definition) => ({
106
90
  ...structuredClone(definition),
107
91
  id: property(definition.id),
@@ -1,7 +1,7 @@
1
1
  import type { SceneGraph } from '../graph'
2
+ import { sharedStyleLayers } from '../shared-styles'
2
3
  import type { ComponentPropertyType, SceneNode } from '../types'
3
4
  import { prepareNodeTransfer } from './nodes'
4
- import { requireTransferReference } from './references'
5
5
  import { prepareVariableTransfer } from './variables'
6
6
 
7
7
  export interface GraphTransferInput {
@@ -73,14 +73,12 @@ export function prepareGraphTransfer(input: GraphTransferInput) {
73
73
  }
74
74
  // Layers name a style by the style's own ID, which a transferred style keeps unless the
75
75
  // target already holds another style by it: IDs read from Figma are only unique in one file.
76
- const targetStyleIds = new Set<string>()
77
- for (const node of target.getAllNodes())
78
- if (node.sharedStyleType !== null && node.source.id) targetStyleIds.add(node.source.id)
76
+ const targetStyles = sharedStyleLayers(target)
79
77
  const styles = new Map<string, string>()
80
78
  for (const node of ordered) {
81
79
  const id = node.source.id
82
80
  if (node.sharedStyleType === null || !id) continue
83
- styles.set(id, targetStyleIds.has(id) ? allocate() : id)
81
+ styles.set(id, targetStyles.has(id) ? allocate() : id)
84
82
  }
85
83
  const references = {
86
84
  nodes,
@@ -119,12 +117,6 @@ export function prepareGraphTransfer(input: GraphTransferInput) {
119
117
  props: withStyleId(node, prepareNodeTransfer(node, references), styles)
120
118
  })),
121
119
  ...resources,
122
- activeModes: new Map(
123
- [...source.activeMode].map(([collection, mode]) => [
124
- requireTransferReference(collections, collection, 'collection'),
125
- requireTransferReference(modes, mode, 'mode')
126
- ])
127
- ),
128
120
  images: new Map([...source.images].map(([hash, bytes]) => [hash, bytes.slice()]))
129
121
  }
130
122
  }
@@ -30,10 +30,13 @@ export function removeGraphTransfer(graph: SceneGraph, plan: GraphTransferPlan):
30
30
  }
31
31
  graph.withBufferedEvents(() => {
32
32
  for (const node of plan.nodes.toReversed()) graph.deleteNode(node.id)
33
- for (const id of variables) graph.variables.delete(id)
33
+ for (const id of variables) {
34
+ graph.willChangeVariable(id)
35
+ graph.variables.delete(id)
36
+ }
34
37
  for (const id of collections) {
38
+ graph.willChangeCollection(id)
35
39
  graph.variableCollections.delete(id)
36
- graph.activeMode.delete(id)
37
40
  }
38
41
  })
39
42
  }
@@ -0,0 +1,54 @@
1
+ import { isEqual } from 'es-toolkit'
2
+
3
+ import { STYLE_LINK_FIELDS } from '../shared-styles'
4
+ import { remapStyleRunReferences } from '../text/references'
5
+ import type { SceneNode } from '../types'
6
+
7
+ /** How a layer's references to variables, collections, modes, and styles are renamed. */
8
+ export interface ResourceReferences {
9
+ variable: (id: string) => string
10
+ collection: (id: string) => string
11
+ mode: (id: string) => string
12
+ style: (id: string) => string
13
+ /** The layer a text link names; links keep naming theirs without it. */
14
+ layer?: (id: string) => string
15
+ }
16
+
17
+ /**
18
+ * `node`'s references to variables, collections, modes, and styles, renamed as a copy into
19
+ * another document renames them: its bindings, the modes it sets, the styles it and its text
20
+ * ranges and vector regions use. Only the fields that change are returned. Instance overrides
21
+ * name layers too, so their callers rename them with the layers.
22
+ */
23
+ export function remappedResourceReferences(
24
+ node: SceneNode,
25
+ references: ResourceReferences
26
+ ): Partial<SceneNode> {
27
+ const { variable, collection, mode, style, layer } = references
28
+ const remapped: Partial<SceneNode> = {
29
+ boundVariables: Object.fromEntries(
30
+ Object.entries(node.boundVariables).map(([field, id]) => [field, variable(id)])
31
+ ),
32
+ variableModes: Object.fromEntries(
33
+ Object.entries(node.variableModes).map(([id, modeId]) => [collection(id), mode(modeId)])
34
+ ),
35
+ styleRuns: remapStyleRunReferences(node.styleRuns, { variable, style, node: layer })
36
+ }
37
+ for (const field of STYLE_LINK_FIELDS) {
38
+ const id = node[field]
39
+ if (id) remapped[field] = style(id)
40
+ }
41
+ if (node.vectorNetwork?.regions.some((region) => region.fillStyleId)) {
42
+ remapped.vectorNetwork = {
43
+ ...node.vectorNetwork,
44
+ regions: node.vectorNetwork.regions.map((region) =>
45
+ region.fillStyleId ? { ...region, fillStyleId: style(region.fillStyleId) } : region
46
+ )
47
+ }
48
+ }
49
+ return Object.fromEntries(
50
+ Object.entries(remapped).filter(
51
+ ([field, value]) => !isEqual(value, node[field as keyof SceneNode])
52
+ )
53
+ )
54
+ }
@@ -1,3 +1,6 @@
1
+ import { uniq } from 'es-toolkit'
2
+
3
+ import type { SceneGraph } from '../graph'
1
4
  import type { Variable, VariableCollection, VariableValue } from '../types'
2
5
  import { mapVariableValueReferences } from '../variables/value'
3
6
  import { requireTransferReference as mapped } from './references'
@@ -81,3 +84,34 @@ export function prepareVariableTransfer(
81
84
  }))
82
85
  }
83
86
  }
87
+
88
+ /**
89
+ * Copies the variables `ids` and the collections `collectionIds` into `target`, IDs kept. Each
90
+ * collection comes from the first of its `sources` that has it, and its variables with it; a
91
+ * variable it lacks there comes from the next. A collection keeps only the variables copied.
92
+ */
93
+ export function copyVariableTables(
94
+ target: SceneGraph,
95
+ ids: ReadonlySet<string>,
96
+ collectionIds: Iterable<string>,
97
+ sources: (collectionId: string) => readonly SceneGraph[]
98
+ ): void {
99
+ for (const collectionId of collectionIds) {
100
+ const graphs = sources(collectionId)
101
+ const first = <T>(read: (graph: SceneGraph) => T | undefined): T | undefined =>
102
+ graphs.map(read).find((found) => found !== undefined)
103
+ const collection = first((graph) => graph.variableCollections.get(collectionId))
104
+ if (!collection) continue
105
+ const members = uniq(
106
+ graphs.flatMap((graph) => graph.variableCollections.get(collectionId)?.variableIds ?? [])
107
+ ).filter((id) => ids.has(id))
108
+ target.variableCollections.set(collectionId, {
109
+ ...structuredClone(collection),
110
+ variableIds: members
111
+ })
112
+ for (const id of members) {
113
+ const variable = first((graph) => graph.variables.get(id))
114
+ if (variable) target.variables.set(id, structuredClone(variable))
115
+ }
116
+ }
117
+ }