@open-pencil/scene-graph 0.15.0 → 0.16.0-beta.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 (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +596 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +573 -521
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2021 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/fields/text.js +36 -0
  34. package/dist/chunks/fields/text.js.map +1 -0
  35. package/dist/chunks/group-bounds.js +104 -0
  36. package/dist/chunks/group-bounds.js.map +1 -0
  37. package/dist/chunks/icons/glyph.js +147 -0
  38. package/dist/chunks/icons/glyph.js.map +1 -0
  39. package/dist/chunks/index.js +1712 -662
  40. package/dist/chunks/index.js.map +1 -1
  41. package/dist/color.d.ts +72 -0
  42. package/dist/color.d.ts.map +1 -0
  43. package/dist/color.js +3 -0
  44. package/dist/constants.d.ts +2 -2
  45. package/dist/constants.js +2 -2
  46. package/dist/constants2.d.ts +3 -1
  47. package/dist/constants2.d.ts.map +1 -1
  48. package/dist/coordinate.d.ts +2 -448
  49. package/dist/coordinate.js +2 -2
  50. package/dist/copy.d.ts +1 -1
  51. package/dist/copy.js +1 -1
  52. package/dist/css.d.ts +39 -0
  53. package/dist/css.d.ts.map +1 -0
  54. package/dist/css.js +3 -0
  55. package/dist/geometry.d.ts +1 -1
  56. package/dist/geometry.js +1 -1
  57. package/dist/gradient.d.ts +51 -0
  58. package/dist/gradient.d.ts.map +1 -0
  59. package/dist/gradient.js +132 -0
  60. package/dist/gradient.js.map +1 -0
  61. package/dist/guides.d.ts +2 -2
  62. package/dist/guides.js +39 -0
  63. package/dist/guides.js.map +1 -0
  64. package/dist/hit-test.d.ts +2 -9
  65. package/dist/hit-test.js +154 -18
  66. package/dist/hit-test.js.map +1 -1
  67. package/dist/index.d.ts +4 -8
  68. package/dist/index.js +20 -5
  69. package/dist/instances.d.ts +2 -2
  70. package/dist/instances.js +2 -2
  71. package/dist/layout.d.ts +2 -0
  72. package/dist/layout.js +4 -0
  73. package/dist/node-defaults.d.ts +2 -8
  74. package/dist/node-defaults.js +2 -2
  75. package/dist/order-keys.d.ts +39 -0
  76. package/dist/order-keys.d.ts.map +1 -0
  77. package/dist/order-keys.js +136 -0
  78. package/dist/order-keys.js.map +1 -0
  79. package/dist/parse-path.d.ts +7 -1
  80. package/dist/parse-path.d.ts.map +1 -1
  81. package/dist/parse-path.js +6 -2
  82. package/dist/parse-path.js.map +1 -1
  83. package/dist/polygon.d.ts +53 -0
  84. package/dist/polygon.d.ts.map +1 -0
  85. package/dist/polygon.js +205 -0
  86. package/dist/polygon.js.map +1 -0
  87. package/dist/preview.d.ts +1 -1
  88. package/dist/random.d.ts +7 -0
  89. package/dist/random.d.ts.map +1 -0
  90. package/dist/random.js +2 -0
  91. package/dist/resize.d.ts +11 -2
  92. package/dist/resize.d.ts.map +1 -1
  93. package/dist/resize.js +2 -184
  94. package/dist/snap.d.ts +1 -1
  95. package/dist/text-direction.d.ts +13 -0
  96. package/dist/text-direction.d.ts.map +1 -0
  97. package/dist/text-direction.js +31 -0
  98. package/dist/text-direction.js.map +1 -0
  99. package/dist/text-picture.d.ts +1 -1
  100. package/dist/text-picture.d.ts.map +1 -1
  101. package/dist/text.d.ts +2 -0
  102. package/dist/text.js +3 -0
  103. package/dist/types.d.ts +2063 -13
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js +2 -1
  106. package/dist/types2.d.ts +2 -2
  107. package/dist/undo.d.ts +2 -2
  108. package/dist/undo.js +2 -2
  109. package/dist/undo2.d.ts +29 -1
  110. package/dist/undo2.d.ts.map +1 -1
  111. package/dist/variables.d.ts +2 -29
  112. package/dist/variables.js +2 -2
  113. package/dist/variant-properties.d.ts +9 -1
  114. package/dist/variant-properties.d.ts.map +1 -1
  115. package/dist/variant-properties.js +36 -1
  116. package/dist/variant-properties.js.map +1 -1
  117. package/dist/vector-network.d.ts +1 -1
  118. package/dist/vector-network.js +1 -1
  119. package/package.json +60 -9
  120. package/src/behaviours/kinds.ts +185 -0
  121. package/src/behaviours/layers.ts +51 -0
  122. package/src/behaviours/model.ts +192 -0
  123. package/src/behaviours/schema.ts +58 -0
  124. package/src/behaviours/spec.ts +223 -0
  125. package/src/buffered-events.ts +64 -0
  126. package/src/color/contrast.ts +31 -0
  127. package/src/color/index.ts +88 -0
  128. package/src/color/management.ts +210 -0
  129. package/src/color/normalize.ts +7 -0
  130. package/src/color/okhcl.ts +201 -0
  131. package/src/comments/document.ts +51 -0
  132. package/src/comments/list.ts +52 -0
  133. package/src/comments/merge.ts +63 -0
  134. package/src/comments/threads.ts +156 -0
  135. package/src/components/exposure.ts +61 -0
  136. package/src/components/properties.ts +18 -15
  137. package/src/components/variants.ts +53 -0
  138. package/src/constants.ts +2 -0
  139. package/src/coordinate.ts +100 -43
  140. package/src/copy.ts +13 -5
  141. package/src/css/grid.ts +70 -0
  142. package/src/css/index.ts +9 -0
  143. package/src/css/layout.ts +53 -0
  144. package/src/css/shadows.ts +68 -0
  145. package/src/css/values.ts +42 -0
  146. package/src/export-format.ts +12 -0
  147. package/src/fields/geometry.ts +11 -0
  148. package/src/fields/text.ts +35 -0
  149. package/src/gradient.ts +166 -0
  150. package/src/group-bounds.ts +131 -0
  151. package/src/guides.ts +39 -0
  152. package/src/hit-test.ts +219 -25
  153. package/src/icons/glyph.ts +128 -0
  154. package/src/icons/model.ts +54 -0
  155. package/src/icons/schema.ts +18 -0
  156. package/src/index.ts +344 -56
  157. package/src/instance-overrides.ts +27 -0
  158. package/src/instances/copies.ts +239 -0
  159. package/src/instances/cycles.ts +73 -0
  160. package/src/instances/fields.ts +143 -0
  161. package/src/instances/main-component.ts +19 -0
  162. package/src/instances/placement.ts +29 -0
  163. package/src/instances/source-walk.ts +41 -0
  164. package/src/instances/sync.ts +599 -0
  165. package/src/instances.ts +122 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +1 -1
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/slots/authoring.ts +101 -0
  187. package/src/slots/content.ts +124 -0
  188. package/src/slots/frames.ts +160 -0
  189. package/src/slots/limits.ts +49 -0
  190. package/src/text/direction.ts +55 -0
  191. package/src/text/index.ts +2 -0
  192. package/src/text/lists.ts +138 -0
  193. package/src/text/paragraphs.ts +241 -0
  194. package/src/{text-picture.ts → text/picture.ts} +21 -29
  195. package/src/transfer/apply.ts +84 -0
  196. package/src/transfer/history.ts +49 -0
  197. package/src/transfer/identity.ts +16 -0
  198. package/src/transfer/index.ts +6 -0
  199. package/src/transfer/nodes.ts +108 -0
  200. package/src/transfer/plan.ts +107 -0
  201. package/src/transfer/references.ts +9 -0
  202. package/src/transfer/remove.ts +39 -0
  203. package/src/transfer/validation.ts +54 -0
  204. package/src/transfer/variables.ts +82 -0
  205. package/src/types.ts +221 -11
  206. package/src/undo.ts +54 -2
  207. package/src/variables/bindings.ts +186 -0
  208. package/src/variables/fields.ts +43 -0
  209. package/src/variables/token.ts +14 -0
  210. package/src/variables/units.ts +15 -0
  211. package/src/variables.ts +118 -69
  212. package/src/variant-properties.ts +50 -0
  213. package/dist/chunks/components/properties.js.map +0 -1
  214. package/dist/chunks/export-scale.js +0 -19
  215. package/dist/chunks/export-scale.js.map +0 -1
  216. package/dist/coordinate.d.ts.map +0 -1
  217. package/dist/coordinate2.d.ts +0 -2
  218. package/dist/guides2.d.ts +0 -11
  219. package/dist/guides2.d.ts.map +0 -1
  220. package/dist/hit-test.d.ts.map +0 -1
  221. package/dist/layout-guides.d.ts +0 -2
  222. package/dist/layout-guides.js +0 -2
  223. package/dist/layout-guides2.d.ts +0 -16
  224. package/dist/layout-guides2.d.ts.map +0 -1
  225. package/dist/node-defaults.d.ts.map +0 -1
  226. package/dist/preview2.d.ts +0 -12
  227. package/dist/preview2.d.ts.map +0 -1
  228. package/dist/resize.js.map +0 -1
  229. package/dist/variables.d.ts.map +0 -1
  230. package/dist/vector-network2.d.ts +0 -32
  231. package/dist/vector-network2.d.ts.map +0 -1
  232. package/src/instance-overrides.test.ts +0 -67
@@ -1,40 +1,21 @@
1
- import type { SceneNode } from './types'
1
+ import { isEqual } from 'es-toolkit/predicate'
2
+
3
+ import { TEXT_SHAPING_FIELDS, TEXT_LAYOUT_FIELDS } from '../fields/text'
4
+ import type { SceneNode } from '../types'
2
5
 
3
6
  /**
4
7
  * Invalidate cached Skia textPicture (Paragraph snapshot). Includes width/height
5
8
  * because wrapping/layout depends on the box.
6
9
  */
7
10
  export const TEXT_PICTURE_KEYS: ReadonlySet<string> = new Set([
8
- 'text',
9
- 'fontSize',
10
- 'fontFamily',
11
- 'fontWeight',
12
- 'italic',
13
- 'textAlignHorizontal',
14
- 'textDirection',
15
- 'textAlignVertical',
16
- 'lineHeight',
17
- 'letterSpacing',
11
+ ...TEXT_SHAPING_FIELDS,
18
12
  'textDecoration',
19
- 'textCase',
20
- 'styleRuns',
21
13
  'fills',
22
14
  'width',
23
15
  'height'
24
16
  ])
25
17
 
26
- export const GLYPH_AFFECTING_KEYS: ReadonlySet<string> = new Set([
27
- 'text',
28
- 'fontSize',
29
- 'fontFamily',
30
- 'fontWeight',
31
- 'italic',
32
- 'textDirection',
33
- 'lineHeight',
34
- 'letterSpacing',
35
- 'textCase',
36
- 'styleRuns'
37
- ])
18
+ export const GLYPH_AFFECTING_KEYS: ReadonlySet<string> = new Set(TEXT_SHAPING_FIELDS)
38
19
 
39
20
  /**
40
21
  * Shared by SceneGraph.updateNode and updateNodePreview (drag hot path) so the
@@ -46,16 +27,27 @@ export function textCacheInvalidationChanges(
46
27
  changes: Partial<SceneNode>
47
28
  ): Partial<SceneNode> {
48
29
  const invalidated: Partial<SceneNode> = {}
49
- const keys = Object.keys(changes)
30
+ const keys = Object.keys(changes).filter(
31
+ (key) => !isEqual(node[key as keyof SceneNode], changes[key as keyof SceneNode])
32
+ )
50
33
  if (node.textPicture && keys.some((key) => TEXT_PICTURE_KEYS.has(key)))
51
34
  invalidated.textPicture = null
52
- const glyphsInvalidated = keys.some((key) => GLYPH_AFFECTING_KEYS.has(key))
35
+ const glyphsInvalidated =
36
+ keys.some((key) => GLYPH_AFFECTING_KEYS.has(key)) ||
37
+ TEXT_LAYOUT_FIELDS.some((key) => keys.includes(key))
38
+ if (glyphsInvalidated && !('derivedLayout' in changes)) invalidated.derivedLayout = null
53
39
  // A successful path-text edit supplies reflowed glyphs in `changes`. Every
54
40
  // other mutation path must drop stale baked glyphs and path identity rather
55
41
  // than pair new text/style with old visible outlines.
56
42
  if (node.derivedTextGlyphs && glyphsInvalidated && !changes.derivedTextGlyphs) {
57
- invalidated.derivedTextGlyphs = null
58
- invalidated.textPathData = null
43
+ // Path-text resize supplies transformed glyphs through the resize workflow. A raw box
44
+ // preview keeps them until that workflow commits or an actual shaping edit occurs.
45
+ const onlyPathBoxResize =
46
+ !!node.textPathData && keys.every((key) => key === 'width' || key === 'height')
47
+ if (!onlyPathBoxResize) {
48
+ invalidated.derivedTextGlyphs = null
49
+ invalidated.textPathData = null
50
+ }
59
51
  }
60
52
  return invalidated
61
53
  }
@@ -0,0 +1,84 @@
1
+ import { isEqual } from 'es-toolkit/predicate'
2
+
3
+ import type { SceneGraph } from '../index'
4
+ import { variableIdentityReferences } from './identity'
5
+ import type { prepareGraphTransfer } from './plan'
6
+ import { validateTransferReferences } from './validation'
7
+ import { prepareVariableTransfer } from './variables'
8
+
9
+ export type GraphTransferPlan = ReturnType<typeof prepareGraphTransfer>
10
+
11
+ function validate(target: SceneGraph, plan: GraphTransferPlan): void {
12
+ validateTransferReferences(target, plan)
13
+ const reserved = new Set([
14
+ ...target.nodes.keys(),
15
+ ...target.variables.keys(),
16
+ ...target.variableCollections.keys()
17
+ ])
18
+ const claim = (id: string): void => {
19
+ if (reserved.has(id)) throw new Error(`Transfer identity collision ${id}`)
20
+ reserved.add(id)
21
+ }
22
+ prepareVariableTransfer(
23
+ plan.variables,
24
+ plan.collections,
25
+ variableIdentityReferences(plan.variables, plan.collections)
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
+ for (const collection of plan.collections) claim(collection.id)
36
+ for (const variable of plan.variables) claim(variable.id)
37
+ const parents = new Set(target.nodes.keys())
38
+ for (const node of plan.nodes) {
39
+ claim(node.id)
40
+ if ('id' in node.props || 'parentId' in node.props || 'childIds' in node.props)
41
+ throw new Error('Transfer props cannot override hierarchy identity')
42
+ if (!parents.has(node.parentId)) throw new Error(`Missing transfer parent ${node.parentId}`)
43
+ parents.add(node.id)
44
+ }
45
+ for (const id of [...plan.rootIds, ...plan.dependencyPageIds]) {
46
+ if (!plan.nodes.some((node) => node.id === id)) throw new Error(`Missing transfer root ${id}`)
47
+ }
48
+ for (const node of plan.nodes) {
49
+ if (node.props.componentId && !parents.has(node.props.componentId))
50
+ throw new Error(`Missing transfer component ${node.props.componentId}`)
51
+ }
52
+ for (const [hash, bytes] of plan.images) {
53
+ const existing = target.images.get(hash)
54
+ if (existing && !isEqual(existing, bytes)) throw new Error(`Transfer image collision ${hash}`)
55
+ }
56
+ }
57
+
58
+ /** Revalidate at insertion time. Event-delivery failures after commit are not rollback failures. */
59
+ export function applyGraphTransfer(target: SceneGraph, input: GraphTransferPlan): void {
60
+ const plan = structuredClone(input)
61
+ validate(target, plan)
62
+ const imageIds = [...plan.images.keys()].filter((hash) => !target.images.has(hash))
63
+ target.withBufferedEvents(() => {
64
+ try {
65
+ for (const collection of plan.collections) target.addCollection(collection)
66
+ for (const variable of plan.variables) target.addVariable(variable)
67
+ for (const [id, mode] of plan.activeModes) target.activeMode.set(id, mode)
68
+ for (const [hash, bytes] of plan.images)
69
+ if (!target.images.has(hash)) target.images.set(hash, bytes)
70
+ for (const node of plan.nodes)
71
+ target.createNodeWithId(node.id, node.type, node.parentId, { ...node.props, childIds: [] })
72
+ } catch (error) {
73
+ for (const node of plan.nodes.toReversed())
74
+ if (target.getNode(node.id)) target.deleteNode(node.id)
75
+ 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
+ }
80
+ for (const hash of imageIds) target.images.delete(hash)
81
+ throw error
82
+ }
83
+ })
84
+ }
@@ -0,0 +1,49 @@
1
+ import { cloneNodeProps } from '../copy'
2
+ import type { SceneGraph } from '../index'
3
+ import type { GraphTransferPlan } from './apply'
4
+
5
+ /** Capture post-placement state for redo; this does not authorize deleting shared resources. */
6
+ export function captureTransferredState(
7
+ graph: SceneGraph,
8
+ original: GraphTransferPlan
9
+ ): GraphTransferPlan {
10
+ const requireValue = <T>(value: T | undefined, kind: string, id: string): T => {
11
+ if (value === undefined) throw new Error(`Missing transferred ${kind} ${id}`)
12
+ return value
13
+ }
14
+ return {
15
+ nodeIds: new Map(original.nodeIds),
16
+ rootIds: [...original.rootIds],
17
+ dependencyPageIds: [...original.dependencyPageIds],
18
+ nodes: original.nodes.map((entry) => {
19
+ const node = requireValue(graph.getNode(entry.id), 'node', entry.id)
20
+ if (!node.parentId) throw new Error(`Missing transferred parent ${entry.id}`)
21
+ return {
22
+ id: node.id,
23
+ type: node.type,
24
+ parentId: node.parentId,
25
+ props: cloneNodeProps(node, null)
26
+ }
27
+ }),
28
+ variables: original.variables.map((variable) =>
29
+ structuredClone(requireValue(graph.variables.get(variable.id), 'variable', variable.id))
30
+ ),
31
+ collections: original.collections.map((collection) =>
32
+ structuredClone(
33
+ requireValue(graph.variableCollections.get(collection.id), 'collection', collection.id)
34
+ )
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
+ images: new Map(
43
+ [...original.images.keys()].map((hash) => [
44
+ hash,
45
+ requireValue(graph.images.get(hash), 'image', hash).slice()
46
+ ])
47
+ )
48
+ }
49
+ }
@@ -0,0 +1,16 @@
1
+ import type { Variable, VariableCollection } from '../types'
2
+
3
+ export function variableIdentityReferences(
4
+ variables: readonly Variable[],
5
+ collections: readonly VariableCollection[]
6
+ ) {
7
+ return {
8
+ variables: new Map(variables.map((variable) => [variable.id, variable.id])),
9
+ collections: new Map(collections.map((collection) => [collection.id, collection.id])),
10
+ modes: new Map(
11
+ collections.flatMap((collection) =>
12
+ collection.modes.map((mode) => [mode.modeId, mode.modeId] as const)
13
+ )
14
+ )
15
+ }
16
+ }
@@ -0,0 +1,6 @@
1
+ export { removeGraphTransfer } from './remove'
2
+ export { captureTransferredState } from './history'
3
+ export { applyGraphTransfer, type GraphTransferPlan } from './apply'
4
+ export { prepareGraphTransfer, type GraphTransferInput } from './plan'
5
+ export { prepareNodeTransfer, type NodeTransferReferences } from './nodes'
6
+ export { prepareVariableTransfer, type VariableTransferReferences } from './variables'
@@ -0,0 +1,108 @@
1
+ import { cloneNodeProps } from '../copy'
2
+ import { remapInstanceOverrideState } from '../instance-overrides'
3
+ import type { ComponentPropertyType, SceneNode } from '../types'
4
+ import { requireTransferReference as required } from './references'
5
+ import type { VariableTransferReferences } from './variables'
6
+
7
+ export function semanticTransferReferences(node: SceneNode): string[] {
8
+ return [
9
+ ...(node.componentId ? [node.componentId] : []),
10
+ ...Object.values(node.boundVariables),
11
+ ...[
12
+ node.fillStyleId,
13
+ node.strokeStyleId,
14
+ node.textStyleId,
15
+ node.effectStyleId,
16
+ node.gridStyleId
17
+ ].filter((id): id is string => !!id),
18
+ ...node.fillGeometry.flatMap((path) => (path.fillStyleId ? [path.fillStyleId] : [])),
19
+ ...node.strokeGeometry.flatMap((path) => (path.fillStyleId ? [path.fillStyleId] : [])),
20
+ ...Object.entries(node.componentPropertyAssignments).flatMap(([id, value]) => [id, value]),
21
+ ...node.componentPropertyReferences.map((reference) => reference.propertyId),
22
+ ...node.componentPropertyDefinitions.flatMap((definition) => [
23
+ definition.id,
24
+ ...(definition.type === 'INSTANCE_SWAP' && definition.defaultValue
25
+ ? [definition.defaultValue]
26
+ : [])
27
+ ]),
28
+ ...node.instanceOverrides.descendants.keys(),
29
+ ...[
30
+ ...node.instanceOverrides.self,
31
+ ...[...node.instanceOverrides.descendants.values()].flatMap((fields) => [...fields])
32
+ ].flatMap(([field, value]) =>
33
+ typeof value === 'string' &&
34
+ (field === 'componentId' ||
35
+ field === 'sourceComponentId' ||
36
+ field.startsWith('boundVariables/'))
37
+ ? [value]
38
+ : []
39
+ )
40
+ ]
41
+ }
42
+
43
+ export interface NodeTransferReferences extends VariableTransferReferences {
44
+ nodes: ReadonlyMap<string, string>
45
+ styles: ReadonlyMap<string, string>
46
+ properties: ReadonlyMap<string, string>
47
+ propertyTypes: ReadonlyMap<string, ComponentPropertyType>
48
+ }
49
+
50
+ /** Prepare runtime references without rewriting original format identities or ordinary text. */
51
+ export function prepareNodeTransfer(
52
+ source: SceneNode,
53
+ refs: NodeTransferReferences
54
+ ): Partial<SceneNode> {
55
+ const node = (id: string) => required(refs.nodes, id, 'node')
56
+ const variable = (id: string) => required(refs.variables, id, 'variable')
57
+ const property = (id: string) => required(refs.properties, id, 'property')
58
+ const style = (id: string) => required(refs.styles, id, 'style')
59
+ const propertyValue = (id: string, value: string): string => {
60
+ const type = refs.propertyTypes.get(id)
61
+ if (!type) throw new Error(`Missing property transfer type: ${id}`)
62
+ return type === 'INSTANCE_SWAP' && value ? node(value) : value
63
+ }
64
+ const values = (entries: Record<string, string>) =>
65
+ Object.fromEntries(
66
+ Object.entries(entries).map(([id, value]) => [property(id), propertyValue(id, value)])
67
+ )
68
+ const result = cloneNodeProps(source, null)
69
+ result.componentId = source.componentId ? node(source.componentId) : null
70
+ result.instanceOverrides = remapInstanceOverrideState(source.instanceOverrides, {
71
+ node,
72
+ variable
73
+ })
74
+ result.boundVariables = Object.fromEntries(
75
+ Object.entries(source.boundVariables).map(([field, id]) => [field, variable(id)])
76
+ )
77
+ result.variableModes = Object.fromEntries(
78
+ Object.entries(source.variableModes).map(([collection, mode]) => [
79
+ required(refs.collections, collection, 'collection'),
80
+ required(refs.modes, mode, 'mode')
81
+ ])
82
+ )
83
+ for (const field of [
84
+ 'fillStyleId',
85
+ 'strokeStyleId',
86
+ 'textStyleId',
87
+ 'effectStyleId',
88
+ 'gridStyleId'
89
+ ] as const) {
90
+ result[field] = source[field] ? style(source[field]) : null
91
+ }
92
+ for (const paths of [result.fillGeometry, result.strokeGeometry]) {
93
+ for (const path of paths ?? []) if (path.fillStyleId) path.fillStyleId = style(path.fillStyleId)
94
+ }
95
+ result.componentPropertyDefinitions = source.componentPropertyDefinitions.map((definition) => ({
96
+ ...structuredClone(definition),
97
+ id: property(definition.id),
98
+ defaultValue: propertyValue(definition.id, definition.defaultValue)
99
+ }))
100
+ result.componentPropertyReferences = source.componentPropertyReferences.map((reference) => ({
101
+ ...reference,
102
+ propertyId: property(reference.propertyId)
103
+ }))
104
+ result.componentPropertyAssignments = values(source.componentPropertyAssignments)
105
+ // Variant values are keyed by display names, unlike definition-ID assignments.
106
+ result.componentPropertyValues = { ...source.componentPropertyValues }
107
+ return result
108
+ }
@@ -0,0 +1,107 @@
1
+ import type { SceneGraph } from '../index'
2
+ import type { ComponentPropertyType, SceneNode } from '../types'
3
+ import { prepareNodeTransfer } from './nodes'
4
+ import { requireTransferReference } from './references'
5
+ import { prepareVariableTransfer } from './variables'
6
+
7
+ export interface GraphTransferInput {
8
+ source: SceneGraph
9
+ rootIds: readonly string[]
10
+ dependencyPageIds: readonly string[]
11
+ target: SceneGraph
12
+ parentId: string
13
+ }
14
+
15
+ /** Preflight a self-contained fragment; allocation does not insert anything into the target. */
16
+ export function prepareGraphTransfer(input: GraphTransferInput) {
17
+ const { source, target, parentId } = input
18
+ if (!target.getNode(parentId)) throw new Error(`Missing transfer parent ${parentId}`)
19
+ const reserved = new Set([
20
+ ...target.nodes.keys(),
21
+ ...target.variables.keys(),
22
+ ...target.variableCollections.keys()
23
+ ])
24
+ for (const collection of target.variableCollections.values())
25
+ for (const mode of collection.modes) reserved.add(mode.modeId)
26
+ let sequence = 0
27
+ const namespace = crypto.randomUUID()
28
+ const allocate = (): string => {
29
+ let id = `${namespace}:${sequence++}`
30
+ while (reserved.has(id)) id = `${namespace}:${sequence++}`
31
+ reserved.add(id)
32
+ return id
33
+ }
34
+ const ordered: SceneNode[] = []
35
+ const seen = new Set<string>()
36
+ const visit = (id: string): void => {
37
+ if (seen.has(id)) throw new Error(`Repeated transfer node ${id}`)
38
+ const node = source.getNode(id)
39
+ if (!node) throw new Error(`Missing transfer source ${id}`)
40
+ seen.add(id)
41
+ ordered.push(node)
42
+ for (const child of node.childIds) visit(child)
43
+ }
44
+ for (const id of [...input.dependencyPageIds, ...input.rootIds]) visit(id)
45
+ const nodes = new Map(ordered.map((node) => [node.id, allocate()]))
46
+ const variables = new Map([...source.variables.keys()].map((id) => [id, allocate()]))
47
+ const collections = new Map([...source.variableCollections.keys()].map((id) => [id, allocate()]))
48
+ const modes = new Map<string, string>()
49
+ for (const collection of source.variableCollections.values()) {
50
+ for (const mode of collection.modes)
51
+ if (!modes.has(mode.modeId)) modes.set(mode.modeId, allocate())
52
+ }
53
+ const properties = new Map<string, string>()
54
+ const propertyTypes = new Map<string, ComponentPropertyType>()
55
+ for (const node of ordered)
56
+ for (const definition of node.componentPropertyDefinitions) {
57
+ if (propertyTypes.has(definition.id) && propertyTypes.get(definition.id) !== definition.type)
58
+ throw new Error(`Conflicting property type ${definition.id}`)
59
+ propertyTypes.set(definition.id, definition.type)
60
+ if (!properties.has(definition.id)) properties.set(definition.id, allocate())
61
+ }
62
+ const references = {
63
+ nodes,
64
+ variables,
65
+ collections,
66
+ modes,
67
+ properties,
68
+ propertyTypes,
69
+ styles: nodes
70
+ }
71
+ const resources = prepareVariableTransfer(
72
+ [...source.variables.values()],
73
+ [...source.variableCollections.values()],
74
+ references
75
+ )
76
+ const mapped = (id: string): string => {
77
+ const value = nodes.get(id)
78
+ if (!value) throw new Error(`Missing transfer node mapping ${id}`)
79
+ return value
80
+ }
81
+ const roots = new Set(input.rootIds)
82
+ const dependencies = new Set(input.dependencyPageIds)
83
+ const destinationParent = (node: SceneNode): string => {
84
+ if (roots.has(node.id)) return parentId
85
+ if (dependencies.has(node.id)) return target.rootId
86
+ return mapped(node.parentId ?? '')
87
+ }
88
+ return {
89
+ nodeIds: nodes,
90
+ rootIds: input.rootIds.map(mapped),
91
+ dependencyPageIds: input.dependencyPageIds.map(mapped),
92
+ nodes: ordered.map((node) => ({
93
+ id: mapped(node.id),
94
+ type: node.type,
95
+ parentId: destinationParent(node),
96
+ props: prepareNodeTransfer(node, references)
97
+ })),
98
+ ...resources,
99
+ activeModes: new Map(
100
+ [...source.activeMode].map(([collection, mode]) => [
101
+ requireTransferReference(collections, collection, 'collection'),
102
+ requireTransferReference(modes, mode, 'mode')
103
+ ])
104
+ ),
105
+ images: new Map([...source.images].map(([hash, bytes]) => [hash, bytes.slice()]))
106
+ }
107
+ }
@@ -0,0 +1,9 @@
1
+ export function requireTransferReference(
2
+ ids: ReadonlyMap<string, string>,
3
+ id: string,
4
+ kind: string
5
+ ): string {
6
+ const value = ids.get(id)
7
+ if (!value) throw new Error(`Missing ${kind} transfer mapping: ${id}`)
8
+ return value
9
+ }
@@ -0,0 +1,39 @@
1
+ import type { SceneGraph } from '../index'
2
+ import type { GraphTransferPlan } from './apply'
3
+ import { semanticTransferReferences } from './nodes'
4
+
5
+ /** Refuse to remove transferred content that has acquired external dependents. */
6
+ export function removeGraphTransfer(graph: SceneGraph, plan: GraphTransferPlan): void {
7
+ const nodes = new Set(plan.nodes.map((node) => node.id))
8
+ const variables = new Set(plan.variables.map((variable) => variable.id))
9
+ const collections = new Set(plan.collections.map((collection) => collection.id))
10
+ const referencesOwned = (value: unknown): boolean => {
11
+ if (typeof value === 'string')
12
+ return nodes.has(value) || variables.has(value) || collections.has(value)
13
+ if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) return false
14
+ if (value instanceof Map)
15
+ return [...value].some(([key, item]) => referencesOwned(key) || referencesOwned(item))
16
+ return Object.values(value).some(referencesOwned)
17
+ }
18
+ for (const node of graph.getAllNodes()) {
19
+ if (nodes.has(node.id)) {
20
+ if (node.childIds.some((id) => !nodes.has(id)))
21
+ throw new Error('Transferred node has non-owned children')
22
+ continue
23
+ }
24
+ if (semanticTransferReferences(node).some(referencesOwned))
25
+ throw new Error(`Transferred content is referenced by ${node.id}`)
26
+ }
27
+ for (const variable of graph.variables.values()) {
28
+ if (!variables.has(variable.id) && referencesOwned(variable.valuesByMode))
29
+ throw new Error('Transferred variable has external aliases')
30
+ }
31
+ graph.withBufferedEvents(() => {
32
+ for (const node of plan.nodes.toReversed()) graph.deleteNode(node.id)
33
+ for (const id of variables) graph.variables.delete(id)
34
+ for (const id of collections) {
35
+ graph.variableCollections.delete(id)
36
+ graph.activeMode.delete(id)
37
+ }
38
+ })
39
+ }
@@ -0,0 +1,54 @@
1
+ import type { SceneGraph } from '../index'
2
+ import { createDefaultNode } from '../node-defaults'
3
+ import type { ComponentPropertyType } from '../types'
4
+ import type { GraphTransferPlan } from './apply'
5
+ import { variableIdentityReferences } from './identity'
6
+ import { prepareNodeTransfer } from './nodes'
7
+
8
+ /** Revalidate mutable plan references without allocating or registering destination nodes. */
9
+ export function validateTransferReferences(target: SceneGraph, plan: GraphTransferPlan): void {
10
+ const nodes = new Map(
11
+ plan.nodes.map((entry) => [
12
+ entry.id,
13
+ createDefaultNode(() => entry.id, entry.type, entry.props)
14
+ ])
15
+ )
16
+ const identities = new Map([...nodes.keys()].map((id) => [id, id]))
17
+ const properties = new Map<string, string>()
18
+ const propertyTypes = new Map<string, ComponentPropertyType>()
19
+ for (const node of nodes.values())
20
+ for (const definition of node.componentPropertyDefinitions) {
21
+ const previous = propertyTypes.get(definition.id)
22
+ if (previous && previous !== definition.type)
23
+ throw new Error(`Conflicting transfer property ${definition.id}`)
24
+ properties.set(definition.id, definition.id)
25
+ propertyTypes.set(definition.id, definition.type)
26
+ }
27
+ const collections = new Map(plan.collections.map((collection) => [collection.id, collection]))
28
+ const references = {
29
+ nodes: identities,
30
+ styles: identities,
31
+ properties,
32
+ propertyTypes,
33
+ ...variableIdentityReferences(plan.variables, plan.collections)
34
+ }
35
+ for (const node of nodes.values()) {
36
+ prepareNodeTransfer(node, references)
37
+ for (const [collection, mode] of Object.entries(node.variableModes)) {
38
+ if (!collections.get(collection)?.modes.some((entry) => entry.modeId === mode))
39
+ throw new Error(`Invalid node variable mode ${node.id}`)
40
+ }
41
+ }
42
+ const roots = new Set([...plan.rootIds, ...plan.dependencyPageIds])
43
+ if (roots.size !== plan.rootIds.length + plan.dependencyPageIds.length)
44
+ throw new Error('Repeated transfer root')
45
+ for (const entry of plan.nodes) {
46
+ if (roots.has(entry.id) === nodes.has(entry.parentId))
47
+ throw new Error(`Invalid transfer root topology ${entry.id}`)
48
+ if (
49
+ plan.dependencyPageIds.includes(entry.id) &&
50
+ (entry.type !== 'CANVAS' || !entry.props.internalOnly || entry.parentId !== target.rootId)
51
+ )
52
+ throw new Error(`Invalid transfer dependency page ${entry.id}`)
53
+ }
54
+ }
@@ -0,0 +1,82 @@
1
+ import type { Variable, VariableCollection, VariableValue } from '../types'
2
+ import { requireTransferReference as mapped } from './references'
3
+
4
+ export interface VariableTransferReferences {
5
+ variables: ReadonlyMap<string, string>
6
+ collections: ReadonlyMap<string, string>
7
+ modes: ReadonlyMap<string, string>
8
+ }
9
+
10
+ function assertUniqueMappings(ids: ReadonlyMap<string, string>, kind: string): void {
11
+ if (new Set(ids.values()).size !== ids.size)
12
+ throw new Error(`Colliding ${kind} transfer mappings`)
13
+ }
14
+
15
+ function assertResourceOwnership(
16
+ variables: readonly Variable[],
17
+ collections: readonly VariableCollection[]
18
+ ): void {
19
+ const sets = new Map(collections.map((collection) => [collection.id, collection]))
20
+ const tokens = new Map(variables.map((variable) => [variable.id, variable]))
21
+ if (sets.size !== collections.length || tokens.size !== variables.length)
22
+ throw new Error('Duplicate source variable resource')
23
+ for (const collection of collections) {
24
+ const modes = new Set(collection.modes.map((mode) => mode.modeId))
25
+ if (!modes.has(collection.defaultModeId) || modes.size !== collection.modes.length)
26
+ throw new Error(`Invalid modes for collection ${collection.id}`)
27
+ for (const id of collection.variableIds) {
28
+ if (tokens.get(id)?.collectionId !== collection.id)
29
+ throw new Error(`Invalid variable membership ${id} in ${collection.id}`)
30
+ }
31
+ }
32
+ for (const variable of variables) {
33
+ const collection = sets.get(variable.collectionId)
34
+ if (!collection?.variableIds.includes(variable.id))
35
+ throw new Error(`Missing collection membership for ${variable.id}`)
36
+ const modes = new Set(collection.modes.map((mode) => mode.modeId))
37
+ for (const mode of Object.keys(variable.valuesByMode)) {
38
+ if (!modes.has(mode)) throw new Error(`Unknown mode ${mode} for ${variable.id}`)
39
+ }
40
+ }
41
+ }
42
+
43
+ /** Prepare isolated resource copies; never mutate the source or destination graph. */
44
+ export function prepareVariableTransfer(
45
+ variables: readonly Variable[],
46
+ collections: readonly VariableCollection[],
47
+ references: VariableTransferReferences
48
+ ): { variables: Variable[]; collections: VariableCollection[] } {
49
+ assertResourceOwnership(variables, collections)
50
+ assertUniqueMappings(references.variables, 'variable')
51
+ assertUniqueMappings(references.collections, 'collection')
52
+ assertUniqueMappings(references.modes, 'mode')
53
+ const value = (input: VariableValue): VariableValue => {
54
+ if (typeof input === 'object' && 'aliasId' in input) {
55
+ return { aliasId: mapped(references.variables, input.aliasId, 'variable alias') }
56
+ }
57
+ return structuredClone(input)
58
+ }
59
+ return {
60
+ collections: collections.map((collection) => ({
61
+ ...structuredClone(collection),
62
+ id: mapped(references.collections, collection.id, 'collection'),
63
+ defaultModeId: mapped(references.modes, collection.defaultModeId, 'mode'),
64
+ modes: collection.modes.map((mode) => ({
65
+ ...mode,
66
+ modeId: mapped(references.modes, mode.modeId, 'mode')
67
+ })),
68
+ variableIds: collection.variableIds.map((id) => mapped(references.variables, id, 'variable'))
69
+ })),
70
+ variables: variables.map((variable) => ({
71
+ ...structuredClone(variable),
72
+ id: mapped(references.variables, variable.id, 'variable'),
73
+ collectionId: mapped(references.collections, variable.collectionId, 'collection'),
74
+ valuesByMode: Object.fromEntries(
75
+ Object.entries(variable.valuesByMode).map(([mode, input]) => [
76
+ mapped(references.modes, mode, 'mode'),
77
+ value(input)
78
+ ])
79
+ )
80
+ }))
81
+ }
82
+ }