@pairdraw/scene-graph 0.19.2 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) 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/index.d.ts +2 -2
  27. package/dist/components/index.js +2 -2
  28. package/dist/components/properties.d.ts.map +1 -1
  29. package/dist/components/properties.js +7 -7
  30. package/dist/components/properties.js.map +1 -1
  31. package/dist/components/variants.d.ts +12 -1
  32. package/dist/components/variants.d.ts.map +1 -1
  33. package/dist/components/variants.js +30 -1
  34. package/dist/components/variants.js.map +1 -1
  35. package/dist/constants.d.ts +25 -1
  36. package/dist/constants.d.ts.map +1 -1
  37. package/dist/constants.js +94 -1
  38. package/dist/constants.js.map +1 -1
  39. package/dist/copy.d.ts.map +1 -1
  40. package/dist/copy.js +17 -1
  41. package/dist/copy.js.map +1 -1
  42. package/dist/css/index.d.ts +2 -2
  43. package/dist/css/index.js +2 -2
  44. package/dist/css/shadows.d.ts +2 -2
  45. package/dist/css/shadows.d.ts.map +1 -1
  46. package/dist/css/shadows.js +4 -4
  47. package/dist/css/shadows.js.map +1 -1
  48. package/dist/css/text.d.ts +17 -1
  49. package/dist/css/text.d.ts.map +1 -1
  50. package/dist/css/text.js +62 -1
  51. package/dist/css/text.js.map +1 -1
  52. package/dist/css/values.d.ts +7 -2
  53. package/dist/css/values.d.ts.map +1 -1
  54. package/dist/css/values.js +8 -4
  55. package/dist/css/values.js.map +1 -1
  56. package/dist/design-memory/index.d.ts +3 -0
  57. package/dist/design-memory/index.js +3 -0
  58. package/dist/design-memory/model.d.ts +33 -0
  59. package/dist/design-memory/model.d.ts.map +1 -0
  60. package/dist/design-memory/model.js +142 -0
  61. package/dist/design-memory/model.js.map +1 -0
  62. package/dist/design-memory/schema.d.ts +76 -0
  63. package/dist/design-memory/schema.d.ts.map +1 -0
  64. package/dist/design-memory/schema.js +72 -0
  65. package/dist/design-memory/schema.js.map +1 -0
  66. package/dist/effects.d.ts +7 -4
  67. package/dist/effects.d.ts.map +1 -1
  68. package/dist/effects.js +9 -4
  69. package/dist/effects.js.map +1 -1
  70. package/dist/empty-values.js +102 -0
  71. package/dist/empty-values.js.map +1 -0
  72. package/dist/fields/components.d.ts +9 -0
  73. package/dist/fields/components.d.ts.map +1 -0
  74. package/dist/fields/components.js +24 -0
  75. package/dist/fields/components.js.map +1 -0
  76. package/dist/fields/index.d.ts +3 -2
  77. package/dist/fields/index.js +3 -2
  78. package/dist/fields/layout.d.ts +3 -1
  79. package/dist/fields/layout.d.ts.map +1 -1
  80. package/dist/fields/layout.js +10 -1
  81. package/dist/fields/layout.js.map +1 -1
  82. package/dist/graph.d.ts +12 -1
  83. package/dist/graph.d.ts.map +1 -1
  84. package/dist/graph.js +39 -7
  85. package/dist/graph.js.map +1 -1
  86. package/dist/grid-values.d.ts +10 -0
  87. package/dist/grid-values.d.ts.map +1 -0
  88. package/dist/grid-values.js +53 -0
  89. package/dist/grid-values.js.map +1 -0
  90. package/dist/hit-test/drop.d.ts +20 -0
  91. package/dist/hit-test/drop.d.ts.map +1 -0
  92. package/dist/hit-test/drop.js +54 -0
  93. package/dist/hit-test/drop.js.map +1 -0
  94. package/dist/hit-test/geometry.js +86 -0
  95. package/dist/hit-test/geometry.js.map +1 -0
  96. package/dist/hit-test/masks.d.ts +14 -0
  97. package/dist/hit-test/masks.d.ts.map +1 -0
  98. package/dist/hit-test/masks.js +41 -0
  99. package/dist/hit-test/masks.js.map +1 -0
  100. package/dist/hit-test/paint.d.ts +6 -0
  101. package/dist/hit-test/paint.d.ts.map +1 -0
  102. package/dist/hit-test/paint.js +19 -0
  103. package/dist/hit-test/paint.js.map +1 -0
  104. package/dist/hit-test.d.ts +4 -15
  105. package/dist/hit-test.d.ts.map +1 -1
  106. package/dist/hit-test.js +5 -173
  107. package/dist/hit-test.js.map +1 -1
  108. package/dist/images.d.ts +3 -2
  109. package/dist/images.d.ts.map +1 -1
  110. package/dist/images.js +18 -2
  111. package/dist/images.js.map +1 -1
  112. package/dist/index.d.ts +2 -2
  113. package/dist/instances/copies.js +2 -1
  114. package/dist/instances/copies.js.map +1 -1
  115. package/dist/instances/fields.d.ts.map +1 -1
  116. package/dist/instances/fields.js +2 -0
  117. package/dist/instances/fields.js.map +1 -1
  118. package/dist/instances/index.d.ts +2 -1
  119. package/dist/instances/index.d.ts.map +1 -1
  120. package/dist/instances/index.js +13 -12
  121. package/dist/instances/index.js.map +1 -1
  122. package/dist/instances/overrides.d.ts +15 -1
  123. package/dist/instances/overrides.d.ts.map +1 -1
  124. package/dist/instances/overrides.js +37 -1
  125. package/dist/instances/overrides.js.map +1 -1
  126. package/dist/instances/source-walk.d.ts +12 -0
  127. package/dist/instances/source-walk.d.ts.map +1 -0
  128. package/dist/instances/swap-overrides.js +3 -3
  129. package/dist/instances/swap-overrides.js.map +1 -1
  130. package/dist/instances/sync.js +9 -7
  131. package/dist/instances/sync.js.map +1 -1
  132. package/dist/node-defaults.d.ts.map +1 -1
  133. package/dist/node-defaults.js +43 -38
  134. package/dist/node-defaults.js.map +1 -1
  135. package/dist/plugin-data/fields.d.ts +90 -0
  136. package/dist/plugin-data/fields.d.ts.map +1 -1
  137. package/dist/plugin-data/fields.js +33 -24
  138. package/dist/plugin-data/fields.js.map +1 -1
  139. package/dist/plugin-data/index.d.ts +2 -2
  140. package/dist/plugin-data/index.js +2 -2
  141. package/dist/plugin-data/schema.d.ts +6 -1
  142. package/dist/plugin-data/schema.d.ts.map +1 -1
  143. package/dist/plugin-data/schema.js +24 -1
  144. package/dist/plugin-data/schema.js.map +1 -1
  145. package/dist/preview.d.ts.map +1 -1
  146. package/dist/preview.js +2 -0
  147. package/dist/preview.js.map +1 -1
  148. package/dist/scaling/node.d.ts.map +1 -1
  149. package/dist/scaling/node.js +5 -1
  150. package/dist/scaling/node.js.map +1 -1
  151. package/dist/shaders/animation.d.ts +21 -0
  152. package/dist/shaders/animation.d.ts.map +1 -0
  153. package/dist/shaders/animation.js +25 -0
  154. package/dist/shaders/animation.js.map +1 -0
  155. package/dist/shaders/index.d.ts +2 -1
  156. package/dist/shaders/index.js +2 -1
  157. package/dist/slots/content.d.ts.map +1 -1
  158. package/dist/slots/content.js +4 -4
  159. package/dist/slots/content.js.map +1 -1
  160. package/dist/statuses/index.d.ts +2 -2
  161. package/dist/statuses/index.js +2 -2
  162. package/dist/statuses/workflow.d.ts +3 -1
  163. package/dist/statuses/workflow.d.ts.map +1 -1
  164. package/dist/statuses/workflow.js +6 -2
  165. package/dist/statuses/workflow.js.map +1 -1
  166. package/dist/token-sources/document.d.ts +26 -0
  167. package/dist/token-sources/document.d.ts.map +1 -0
  168. package/dist/token-sources/document.js +80 -0
  169. package/dist/token-sources/document.js.map +1 -0
  170. package/dist/token-sources/index.d.ts +3 -0
  171. package/dist/token-sources/index.js +3 -0
  172. package/dist/token-sources/schema.d.ts +43 -0
  173. package/dist/token-sources/schema.d.ts.map +1 -0
  174. package/dist/token-sources/schema.js +50 -0
  175. package/dist/token-sources/schema.js.map +1 -0
  176. package/dist/transfer/variables.d.ts.map +1 -1
  177. package/dist/transfer/variables.js +1 -1
  178. package/dist/transfer/variables.js.map +1 -1
  179. package/dist/types.d.ts +135 -15
  180. package/dist/types.d.ts.map +1 -1
  181. package/dist/types.js.map +1 -1
  182. package/dist/variables/bindings.d.ts +6 -5
  183. package/dist/variables/bindings.d.ts.map +1 -1
  184. package/dist/variables/bindings.js +24 -16
  185. package/dist/variables/bindings.js.map +1 -1
  186. package/dist/variables/formula/index.d.ts.map +1 -1
  187. package/dist/variables/formula/index.js +12 -6
  188. package/dist/variables/formula/index.js.map +1 -1
  189. package/dist/variables/index.d.ts +14 -1
  190. package/dist/variables/index.d.ts.map +1 -1
  191. package/dist/variables/index.js +38 -10
  192. package/dist/variables/index.js.map +1 -1
  193. package/dist/variables/paints.d.ts +9 -8
  194. package/dist/variables/paints.d.ts.map +1 -1
  195. package/dist/variables/paints.js +35 -26
  196. package/dist/variables/paints.js.map +1 -1
  197. package/dist/variables/resolver.d.ts +45 -0
  198. package/dist/variables/resolver.d.ts.map +1 -0
  199. package/dist/variables/resolver.js +106 -0
  200. package/dist/variables/resolver.js.map +1 -0
  201. package/dist/variations/copy.d.ts +16 -0
  202. package/dist/variations/copy.d.ts.map +1 -0
  203. package/dist/variations/copy.js +78 -0
  204. package/dist/variations/copy.js.map +1 -0
  205. package/dist/variations/index.d.ts +6 -0
  206. package/dist/variations/index.js +6 -0
  207. package/dist/variations/match.d.ts +23 -0
  208. package/dist/variations/match.d.ts.map +1 -0
  209. package/dist/variations/match.js +80 -0
  210. package/dist/variations/match.js.map +1 -0
  211. package/dist/variations/model.d.ts +39 -0
  212. package/dist/variations/model.d.ts.map +1 -0
  213. package/dist/variations/model.js +90 -0
  214. package/dist/variations/model.js.map +1 -0
  215. package/dist/variations/pick.d.ts +43 -0
  216. package/dist/variations/pick.d.ts.map +1 -0
  217. package/dist/variations/pick.js +211 -0
  218. package/dist/variations/pick.js.map +1 -0
  219. package/dist/variations/schema.d.ts +27 -0
  220. package/dist/variations/schema.d.ts.map +1 -0
  221. package/dist/variations/schema.js +27 -0
  222. package/dist/variations/schema.js.map +1 -0
  223. package/package.json +21 -1
  224. package/src/color/index.ts +43 -9
  225. package/src/color/management.ts +54 -1
  226. package/src/color/profile.ts +131 -0
  227. package/src/comments/merge.ts +3 -0
  228. package/src/comments/schema.ts +32 -2
  229. package/src/comments/threads.ts +5 -2
  230. package/src/components/properties.ts +13 -7
  231. package/src/components/variants.ts +39 -0
  232. package/src/constants.ts +75 -0
  233. package/src/copy.ts +20 -1
  234. package/src/css/index.ts +7 -1
  235. package/src/css/shadows.ts +8 -5
  236. package/src/css/text.ts +62 -0
  237. package/src/css/values.ts +12 -5
  238. package/src/design-memory/index.ts +2 -0
  239. package/src/design-memory/model.ts +143 -0
  240. package/src/design-memory/schema.ts +84 -0
  241. package/src/effects.ts +16 -7
  242. package/src/empty-values.ts +117 -0
  243. package/src/fields/components.ts +21 -0
  244. package/src/fields/index.ts +1 -0
  245. package/src/fields/layout.ts +10 -0
  246. package/src/graph.ts +50 -6
  247. package/src/grid-values.ts +47 -0
  248. package/src/hit-test/drop.ts +90 -0
  249. package/src/hit-test/geometry.ts +131 -0
  250. package/src/hit-test/masks.ts +57 -0
  251. package/src/hit-test/paint.ts +24 -0
  252. package/src/hit-test.ts +8 -277
  253. package/src/images.ts +27 -3
  254. package/src/instances/copies.ts +2 -1
  255. package/src/instances/fields.ts +2 -0
  256. package/src/instances/index.ts +20 -11
  257. package/src/instances/overrides.ts +49 -0
  258. package/src/instances/swap-overrides.ts +3 -2
  259. package/src/instances/sync.ts +11 -7
  260. package/src/node-defaults.ts +51 -41
  261. package/src/plugin-data/fields.ts +34 -32
  262. package/src/plugin-data/index.ts +1 -0
  263. package/src/plugin-data/schema.ts +30 -0
  264. package/src/preview.ts +2 -0
  265. package/src/scaling/node.ts +7 -2
  266. package/src/shaders/animation.ts +39 -0
  267. package/src/shaders/index.ts +1 -0
  268. package/src/slots/content.ts +8 -4
  269. package/src/statuses/workflow.ts +6 -4
  270. package/src/token-sources/document.ts +104 -0
  271. package/src/token-sources/index.ts +2 -0
  272. package/src/token-sources/schema.ts +59 -0
  273. package/src/transfer/variables.ts +2 -1
  274. package/src/types.ts +145 -14
  275. package/src/variables/bindings.ts +35 -18
  276. package/src/variables/formula/index.ts +19 -18
  277. package/src/variables/index.ts +49 -10
  278. package/src/variables/paints.ts +64 -29
  279. package/src/variables/resolver.ts +178 -0
  280. package/src/variations/copy.ts +89 -0
  281. package/src/variations/index.ts +5 -0
  282. package/src/variations/match.ts +100 -0
  283. package/src/variations/model.ts +132 -0
  284. package/src/variations/pick.ts +293 -0
  285. package/src/variations/schema.ts +29 -0
@@ -0,0 +1,100 @@
1
+ import { groupBy } from 'es-toolkit'
2
+
3
+ import type { SceneGraph } from '../graph'
4
+ import { readPluginData } from '../plugin-data/field'
5
+ import { PAIRDRAW_PLUGIN_DATA } from '../plugin-data/fields'
6
+ import type { SceneNode } from '../types'
7
+
8
+ /**
9
+ * Which layer of the original each layer of a version stands for, as version id → original id.
10
+ * The roots always pair. Under each paired parent, children pair first by type and name in
11
+ * order, then the ones left by type in order, so a renamed or moved layer still finds its
12
+ * counterpart; layers of different types never pair, except a main component's or component
13
+ * set's stand-in, marked as such (`standsIn`), which pairs with it; a marked layer that does
14
+ * not find its component here pairs as any other layer. Only layers paired with their own type are
15
+ * searched further. Nothing is stored: a version is a copy of the original, so its layers mostly
16
+ * keep the names and types they were copied with.
17
+ */
18
+ export function matchLayers(
19
+ graph: SceneGraph,
20
+ originalId: string,
21
+ versionId: string
22
+ ): Map<string, string> {
23
+ const pairs = new Map<string, string>([[versionId, originalId]])
24
+ const pending: Array<[string, string]> = [[versionId, originalId]]
25
+ for (let next = pending.pop(); next; next = pending.pop()) {
26
+ const [versionParent, originalParent] = next
27
+ for (const [version, original] of matchChildren(
28
+ graph.getChildren(versionParent),
29
+ graph.getChildren(originalParent)
30
+ )) {
31
+ pairs.set(version.id, original.id)
32
+ if (version.type === original.type) pending.push([version.id, original.id])
33
+ }
34
+ }
35
+ return pairs
36
+ }
37
+
38
+ /**
39
+ * Whether `version` is what a copy holds in place of the main component or component set
40
+ * `original`, as its mark says (`copyVersion`): an instance of the component, or a frame of
41
+ * instances of the set's variants. A name proves nothing, since an instance may share it.
42
+ */
43
+ export function standsIn(version: SceneNode, original: SceneNode): boolean {
44
+ if (original.type !== 'COMPONENT' && original.type !== 'COMPONENT_SET') return false
45
+ return readPluginData(version.pluginData, PAIRDRAW_PLUGIN_DATA.variationStandIn) === original.id
46
+ }
47
+
48
+ /** Takes the next free layer of a bucket, skipping ones another bucket already gave away. */
49
+ function takeNext(
50
+ bucket: readonly SceneNode[] | undefined,
51
+ cursors: Map<readonly SceneNode[], number>,
52
+ taken: Set<string>
53
+ ): SceneNode | undefined {
54
+ if (!bucket) return undefined
55
+ let index = cursors.get(bucket) ?? 0
56
+ while (index < bucket.length && taken.has(bucket[index].id)) index++
57
+ cursors.set(bucket, Math.min(index + 1, bucket.length))
58
+ if (index === bucket.length) return undefined
59
+ const found = bucket[index]
60
+ taken.add(found.id)
61
+ return found
62
+ }
63
+
64
+ /**
65
+ * Pairs in one pass over each list: stand-ins for main components and sets first, then through
66
+ * buckets by type and name and by type alone.
67
+ */
68
+ function matchChildren(
69
+ versions: SceneNode[],
70
+ originals: SceneNode[]
71
+ ): Array<[SceneNode, SceneNode]> {
72
+ const mains = new Map(
73
+ originals
74
+ .filter((node) => node.type === 'COMPONENT' || node.type === 'COMPONENT_SET')
75
+ .map((node) => [node.id, node])
76
+ )
77
+ const byName = groupBy(originals, (node) => `${node.type}\u0000${node.name}`)
78
+ const byType = groupBy(originals, (node) => node.type)
79
+ const cursors = new Map<readonly SceneNode[], number>()
80
+ const taken = new Set<string>()
81
+ const pairs: Array<[SceneNode, SceneNode]> = []
82
+ const left: SceneNode[] = []
83
+ for (const version of versions) {
84
+ const mainId = readPluginData(version.pluginData, PAIRDRAW_PLUGIN_DATA.variationStandIn)
85
+ const main = mainId === undefined ? undefined : mains.get(mainId)
86
+ if (main && !taken.has(main.id) && standsIn(version, main)) {
87
+ taken.add(main.id)
88
+ pairs.push([version, main])
89
+ continue
90
+ }
91
+ const named = takeNext(byName[`${version.type}\u0000${version.name}`], cursors, taken)
92
+ if (named) pairs.push([version, named])
93
+ else left.push(version)
94
+ }
95
+ for (const version of left) {
96
+ const typed = takeNext(byType[version.type], cursors, taken)
97
+ if (typed) pairs.push([version, typed])
98
+ }
99
+ return pairs
100
+ }
@@ -0,0 +1,132 @@
1
+ import type { SceneGraph } from '../graph'
2
+ import { readPluginData, withPluginData } from '../plugin-data/field'
3
+ import { PAIRDRAW_PLUGIN_DATA } from '../plugin-data/fields'
4
+ import type { SceneNode } from '../types'
5
+ import type { VariationSet } from './schema'
6
+
7
+ /** A set of variations as the document holds it now. */
8
+ export interface VariationSetView {
9
+ /** The section holding the versions, which carries the set's mark. */
10
+ section: SceneNode
11
+ set: VariationSet
12
+ /** The layer the versions are variations of, or null when it is gone. */
13
+ original: SceneNode | null
14
+ /** The section's children, in their order. */
15
+ versions: SceneNode[]
16
+ }
17
+
18
+ /** The set a section marks, or null when the layer is not a section or carries none. */
19
+ export function readVariationSet(
20
+ node: Pick<SceneNode, 'type' | 'pluginData'>
21
+ ): VariationSet | null {
22
+ if (node.type !== 'SECTION') return null
23
+ return readPluginData(node.pluginData, PAIRDRAW_PLUGIN_DATA.variationSet) ?? null
24
+ }
25
+
26
+ /** The section's plugin data with its mark replaced by `set`, or removed when it is null. */
27
+ export function withVariationSet(
28
+ node: Pick<SceneNode, 'pluginData'>,
29
+ set: VariationSet | null
30
+ ): SceneNode['pluginData'] {
31
+ return withPluginData(node.pluginData, PAIRDRAW_PLUGIN_DATA.variationSet, set ?? undefined)
32
+ }
33
+
34
+ function viewOf(graph: SceneGraph, section: SceneNode): VariationSetView | null {
35
+ const set = readVariationSet(section)
36
+ if (!set) return null
37
+ const original = graph.getNode(set.originalId) ?? null
38
+ const usable =
39
+ original !== null &&
40
+ original.type !== 'CANVAS' &&
41
+ graph.pageOf(original.id) !== null &&
42
+ !graph.isDescendant(original.id, section.id)
43
+ return {
44
+ section,
45
+ set,
46
+ original: usable ? original : null,
47
+ versions: graph.getChildren(section.id)
48
+ }
49
+ }
50
+
51
+ /** The set a layer belongs to: the marked section itself, one of its versions, or a layer inside one. */
52
+ export function variationSetOf(graph: SceneGraph, nodeId: string): VariationSetView | null {
53
+ const section = graph.closest(nodeId, (node) => readVariationSet(node) !== null)
54
+ return section ? viewOf(graph, section) : null
55
+ }
56
+
57
+ /** The version of `view` that holds `nodeId`, or the version itself; null outside its versions. */
58
+ export function versionOf(
59
+ graph: SceneGraph,
60
+ view: VariationSetView,
61
+ nodeId: string
62
+ ): SceneNode | null {
63
+ return graph.closest(nodeId, (node) => node.parentId === view.section.id) ?? null
64
+ }
65
+
66
+ /** The sets on a page; they sit on the page itself, beside the layers they vary. */
67
+ export function variationSetsOnPage(graph: SceneGraph, pageId: string): VariationSetView[] {
68
+ return graph.getChildren(pageId).flatMap((node) => viewOf(graph, node) ?? [])
69
+ }
70
+
71
+ /** The set whose versions vary `originalId`, if there is one on its page. */
72
+ export function variationSetForOriginal(
73
+ graph: SceneGraph,
74
+ originalId: string
75
+ ): VariationSetView | null {
76
+ const pageId = graph.pageOf(originalId)
77
+ if (!pageId) return null
78
+ return variationSetsOnPage(graph, pageId).find((view) => view.original?.id === originalId) ?? null
79
+ }
80
+
81
+ const FNV_OFFSET = 0x811c9dc5
82
+ const FNV_PRIME = 0x01000193
83
+
84
+ function hashText(hash: number, text: string): number {
85
+ let next = hash
86
+ for (let index = 0; index < text.length; index++) {
87
+ next = Math.imul(next ^ text.charCodeAt(index), FNV_PRIME) >>> 0
88
+ }
89
+ return next
90
+ }
91
+
92
+ /**
93
+ * A short hash of what a layer and its layers look like at a glance: their types, names, boxes,
94
+ * visibility, opacity, text, and how many fills and children they have. The layer's own position
95
+ * is left out, so moving it, or its auto layout parent placing it, is no change. It walks the
96
+ * whole subtree, so callers compute it when they show it rather than on every edit; it changes
97
+ * with most edits, which is all a "changed since" notice needs, and is not a full comparison.
98
+ */
99
+ export function variationFingerprint(graph: SceneGraph, nodeId: string): string {
100
+ let hash = FNV_OFFSET
101
+ const pending = [nodeId]
102
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
103
+ const node = graph.getNode(id)
104
+ if (!node) continue
105
+ hash = hashText(
106
+ hash,
107
+ [
108
+ node.type,
109
+ node.name,
110
+ id === nodeId ? '' : node.x,
111
+ id === nodeId ? '' : node.y,
112
+ node.width,
113
+ node.height,
114
+ node.rotation,
115
+ node.visible,
116
+ node.opacity,
117
+ node.text,
118
+ node.fills.length,
119
+ node.childIds.length
120
+ ].join('\u0000')
121
+ )
122
+ pending.push(...node.childIds)
123
+ }
124
+ return hash.toString(16).padStart(8, '0')
125
+ }
126
+
127
+ /** Whether the set's original looks different from when its versions were made. */
128
+ export function originalChangedSince(graph: SceneGraph, view: VariationSetView): boolean {
129
+ const { original, set } = view
130
+ if (!original || set.originalFingerprint === undefined) return false
131
+ return variationFingerprint(graph, original.id) !== set.originalFingerprint
132
+ }
@@ -0,0 +1,293 @@
1
+ import { isEqual, pick } from 'es-toolkit'
2
+
3
+ import { cloneNodeProps } from '../copy'
4
+ import { MAIN_COMPONENT_FIELDS, PARENT_LAYOUT_FIELDS, TRANSFORM_FIELDS } from '../fields'
5
+ import type { SceneGraph } from '../graph'
6
+ import { findInstanceAncestor, retargetCopiedOverrides } from '../instances'
7
+ import { readPluginData } from '../plugin-data/field'
8
+ import { PAIRDRAW_PLUGIN_DATA } from '../plugin-data/fields'
9
+ import type { NodeType, PrototypeReaction, SceneNode } from '../types'
10
+ import { withStandIn } from './copy'
11
+ import { matchLayers } from './match'
12
+ import { variationSetOf, versionOf, type VariationSetView } from './model'
13
+
14
+ /** Why a version cannot replace its original. */
15
+ export type VariationPickProblem =
16
+ | 'not-in-set'
17
+ | 'not-a-version'
18
+ | 'original-missing'
19
+ | 'original-in-instance'
20
+ | 'original-locked'
21
+ | 'version-type-differs'
22
+
23
+ const PROBLEM_MESSAGES: Record<VariationPickProblem, (nodeId: string) => string> = {
24
+ 'not-in-set': (nodeId) => `"${nodeId}" is not in a set of variations`,
25
+ 'not-a-version': (nodeId) => `"${nodeId}" is not a version: pick one of the set's layers`,
26
+ 'original-missing': () => 'The layer these are variations of is gone; discard them instead',
27
+ 'original-in-instance': () =>
28
+ 'The layer these are variations of is inside an instance; vary the instance or its main component',
29
+ 'original-locked': () =>
30
+ 'The layer these are variations of is locked; unlock it to replace it with a version',
31
+ 'version-type-differs': () =>
32
+ 'This version is a different kind of layer than the original (such as a frame for an ' +
33
+ 'instance), so it cannot replace it; change the layers inside a version instead of ' +
34
+ 'replacing the version, or make a new version'
35
+ }
36
+
37
+ /** A layer that belongs to no set, or a version that cannot be used, with the reason. */
38
+ export class VariationError extends Error {
39
+ constructor(
40
+ readonly problem: VariationPickProblem,
41
+ nodeId: string
42
+ ) {
43
+ super(PROBLEM_MESSAGES[problem](nodeId))
44
+ this.name = 'VariationError'
45
+ }
46
+ }
47
+
48
+ /** Never taken from a version: what places a layer in the tree, who it is, and its review. */
49
+ const OWN_FIELDS: ReadonlySet<string> = new Set<keyof SceneNode>([
50
+ 'id',
51
+ 'parentId',
52
+ 'childIds',
53
+ 'source',
54
+ 'status'
55
+ ])
56
+
57
+ /** What the original keeps of its own place: its name, where it sits, and how it is shown. */
58
+ const ORIGINAL_PLACE_FIELDS: ReadonlySet<string> = new Set<keyof SceneNode>([
59
+ 'name',
60
+ ...TRANSFORM_FIELDS.filter((field) => field !== 'flipX' && field !== 'flipY'),
61
+ ...PARENT_LAYOUT_FIELDS,
62
+ 'visible',
63
+ 'locked'
64
+ ])
65
+
66
+ /** What a main component original keeps: being a component, and its properties and publishing. */
67
+ const MAIN_COMPONENT_KEPT: ReadonlySet<string> = new Set<keyof SceneNode>([
68
+ 'type',
69
+ ...MAIN_COMPONENT_FIELDS
70
+ ])
71
+
72
+ function standInMark(node: SceneNode | undefined): string | undefined {
73
+ return node ? readPluginData(node.pluginData, PAIRDRAW_PLUGIN_DATA.variationStandIn) : undefined
74
+ }
75
+
76
+ /** Removes stand-in marks from a layer moving into the original, and from its layers. */
77
+ function clearStandInMarks(graph: SceneGraph, rootId: string): void {
78
+ for (const node of subtree(graph, rootId)) {
79
+ if (standInMark(node) !== undefined) {
80
+ graph.updateNode(node.id, { pluginData: withStandIn(node, null) })
81
+ }
82
+ }
83
+ }
84
+
85
+ /** The layer at `rootId` and every layer inside it. */
86
+ function* subtree(graph: SceneGraph, rootId: string): Generator<SceneNode> {
87
+ const pending = [rootId]
88
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
89
+ const node = graph.getNode(id)
90
+ if (!node) continue
91
+ pending.push(...node.childIds)
92
+ yield node
93
+ }
94
+ }
95
+
96
+ function isMain(node: SceneNode | undefined): boolean {
97
+ return node?.type === 'COMPONENT' || node?.type === 'COMPONENT_SET'
98
+ }
99
+
100
+ /** Whether a version whose root is `version` may replace an original of type `original`. */
101
+ function replaces(version: NodeType, original: NodeType): boolean {
102
+ // A main component's versions are frames.
103
+ return version === original || (original === 'COMPONENT' && version === 'FRAME')
104
+ }
105
+
106
+ /** Why `versionId` cannot replace the original of `view`, or null when it can. */
107
+ export function variationPickProblem(
108
+ graph: SceneGraph,
109
+ view: VariationSetView,
110
+ versionId: string
111
+ ): VariationPickProblem | null {
112
+ const version = graph.getNode(versionId)
113
+ if (version?.parentId !== view.section.id) return 'not-a-version'
114
+ const { original } = view
115
+ if (!original) return 'original-missing'
116
+ if (original.parentId && findInstanceAncestor(graph, original.parentId)) {
117
+ return 'original-in-instance'
118
+ }
119
+ if (original.locked) return 'original-locked'
120
+ return replaces(version.type, original.type) ? null : 'version-type-differs'
121
+ }
122
+
123
+ /**
124
+ * The set and version `versionId` names, a version or a layer inside one, and why it cannot
125
+ * replace its original, or null when it can. Throws when `versionId` is in no set's versions.
126
+ */
127
+ export function variationToPick(
128
+ graph: SceneGraph,
129
+ versionId: string
130
+ ): { view: VariationSetView; version: SceneNode; problem: VariationPickProblem | null } {
131
+ const view = variationSetOf(graph, versionId)
132
+ if (!view) throw new VariationError('not-in-set', versionId)
133
+ const version = versionOf(graph, view, versionId)
134
+ if (!version) throw new VariationError('not-a-version', versionId)
135
+ return { view, version, problem: variationPickProblem(graph, view, version.id) }
136
+ }
137
+
138
+ /**
139
+ * The version's fields that differ from what `original` holds, as `original` takes them, or null
140
+ * when none do, so an unchanged layer gets no update at all.
141
+ */
142
+ function changedFields(
143
+ versionLayer: SceneNode,
144
+ original: SceneNode,
145
+ isRoot: boolean
146
+ ): Partial<SceneNode> | null {
147
+ // A stand-in mark stays with the version's layer; the original never takes it.
148
+ const version =
149
+ standInMark(versionLayer) === undefined
150
+ ? versionLayer
151
+ : { ...versionLayer, pluginData: withStandIn(versionLayer, null) }
152
+ const kept = (key: string) =>
153
+ OWN_FIELDS.has(key) ||
154
+ (isRoot && ORIGINAL_PLACE_FIELDS.has(key)) ||
155
+ (isRoot && original.type === 'COMPONENT' && MAIN_COMPONENT_KEPT.has(key))
156
+ const keys = (Object.keys(version) as (keyof SceneNode)[]).filter(
157
+ (key) => version[key] !== original[key] && !kept(key) && !isEqual(version[key], original[key])
158
+ )
159
+ return keys.length > 0 ? pick(cloneNodeProps(version, null), keys) : null
160
+ }
161
+
162
+ function renamedReactions(
163
+ reactions: PrototypeReaction[],
164
+ rename: (id: string) => string
165
+ ): PrototypeReaction[] | null {
166
+ const renamed = (action: PrototypeReaction['actions'][number]) =>
167
+ action.type === 'NODE' && action.nodeId !== null && rename(action.nodeId) !== action.nodeId
168
+ if (!reactions.some((reaction) => reaction.actions.some(renamed))) return null
169
+ return reactions.map((reaction) => ({
170
+ ...reaction,
171
+ actions: reaction.actions.map((action) =>
172
+ action.type === 'NODE' && action.nodeId !== null
173
+ ? { ...action, nodeId: rename(action.nodeId) }
174
+ : action
175
+ )
176
+ }))
177
+ }
178
+
179
+ /**
180
+ * Points what the kept layers say about each other, connector ends and prototype targets, at
181
+ * the original's layers where they named the version's.
182
+ */
183
+ function renameReferences(graph: SceneGraph, rootId: string, pairs: ReadonlyMap<string, string>) {
184
+ const rename = (id: string) => pairs.get(id) ?? id
185
+ for (const node of subtree(graph, rootId)) {
186
+ const changes: Partial<SceneNode> = {}
187
+ for (const end of ['connectorStart', 'connectorEnd'] as const) {
188
+ const endpoint = node[end]
189
+ if (endpoint?.nodeId && pairs.has(endpoint.nodeId)) {
190
+ changes[end] = { ...endpoint, nodeId: rename(endpoint.nodeId) }
191
+ }
192
+ }
193
+ const reactions = renamedReactions(node.prototypeReactions, rename)
194
+ if (reactions) changes.prototypeReactions = reactions
195
+ if (Object.keys(changes).length > 0) graph.updateNode(node.id, changes)
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Gives `originalLayer` the children of `versionLayer`, in its order: paired layers stay, layers
201
+ * only the version has move in, and layers only the original had go, apart from main components
202
+ * and sets, which keep their place. Returns the pairs to visit next.
203
+ */
204
+ function applyChildren(
205
+ graph: SceneGraph,
206
+ pairs: ReadonlyMap<string, string>,
207
+ paired: ReadonlySet<string>,
208
+ versionLayer: SceneNode,
209
+ originalLayer: SceneNode
210
+ ): Array<[string, string]> {
211
+ const originalChildren = [...originalLayer.childIds]
212
+ // A main component or set is never deleted: instances elsewhere draw from it.
213
+ const keptMains = originalChildren.flatMap((childId, index) =>
214
+ !paired.has(childId) && isMain(graph.getNode(childId)) ? [{ childId, index }] : []
215
+ )
216
+ const unpaired = originalChildren.filter(
217
+ (childId) => !paired.has(childId) && !isMain(graph.getNode(childId))
218
+ )
219
+ for (const childId of unpaired) graph.deleteNode(childId)
220
+
221
+ const next: Array<[string, string]> = []
222
+ const order: string[] = []
223
+ for (const childId of versionLayer.childIds) {
224
+ const pairedId = pairs.get(childId)
225
+ // A stand-in for a component the document no longer has stands for nothing; any other
226
+ // marked layer moving in is an ordinary layer, such as a copy of a stand-in.
227
+ const mark = pairedId === undefined ? standInMark(graph.getNode(childId)) : undefined
228
+ if (mark !== undefined && !graph.getNode(mark)) continue
229
+ order.push(pairedId ?? childId)
230
+ if (pairedId === undefined) clearStandInMarks(graph, childId)
231
+ // A main component's stand-in leaves the component as it is (`standsIn`).
232
+ else if (graph.getNode(childId)?.type === graph.getNode(pairedId)?.type) {
233
+ next.push([childId, pairedId])
234
+ }
235
+ }
236
+ // A kept main component keeps its place among the layers.
237
+ for (const { childId, index } of keptMains) order.splice(index, 0, childId)
238
+ order.forEach((target, index) => {
239
+ // Read the list afresh: a move replaces it. A layer already in place is not moved.
240
+ if (graph.getNode(originalLayer.id)?.childIds[index] !== target) {
241
+ graph.insertChildAt(target, originalLayer.id, index)
242
+ }
243
+ })
244
+ return next
245
+ }
246
+
247
+ /**
248
+ * Makes the original of the set holding `versionId` look like that version, then removes the
249
+ * set. The original keeps its id, name, place among its siblings, and how its parent lays it
250
+ * out, and so does every layer of it that pairs with one of the version's (`matchLayers`), so
251
+ * what points at them keeps working; layers only the version has move in, and layers only the
252
+ * original had are deleted, apart from main components and sets, which are kept as they are,
253
+ * as when the version holds their stand-ins. Only fields that differ are written and only layers out of place
254
+ * are moved, so a pick sends no more changes than it makes. A main component stays one, keeping
255
+ * its properties and publishing. Comments stay pinned where they were; one on a removed version
256
+ * falls back to its stored point, as on any deleted layer. The caller records the edit as one step and lays out the original and its parent.
257
+ */
258
+ export function applyVariation(graph: SceneGraph, versionId: string): { originalId: string } {
259
+ const { view, version, problem } = variationToPick(graph, versionId)
260
+ if (problem || !view.original) throw new VariationError(problem ?? 'original-missing', versionId)
261
+ const original = view.original
262
+
263
+ const pairs = matchLayers(graph, original.id, version.id)
264
+ const paired = new Set(pairs.values())
265
+ const pending: Array<[string, string]> = [[version.id, original.id]]
266
+ // Pairs are appended while the list is walked, parents before their children.
267
+ for (const [versionLayerId, originalLayerId] of pending) {
268
+ const versionLayer = graph.getNode(versionLayerId)
269
+ const originalLayer = graph.getNode(originalLayerId)
270
+ if (!versionLayer || !originalLayer) continue
271
+ const changes = changedFields(versionLayer, originalLayer, originalLayerId === original.id)
272
+ if (changes) graph.updateNode(originalLayerId, changes)
273
+ pending.push(...applyChildren(graph, pairs, paired, versionLayer, originalLayer))
274
+ }
275
+
276
+ // Instances among the kept layers record overrides of the version's layers; they are the
277
+ // original's now.
278
+ retargetCopiedOverrides(graph, pairs)
279
+ renameReferences(graph, original.id, pairs)
280
+ graph.deleteNode(view.section.id)
281
+ return { originalId: original.id }
282
+ }
283
+
284
+ /** Removes the set holding `nodeId` and every version in it; the original is left as it is. */
285
+ export function discardVariations(
286
+ graph: SceneGraph,
287
+ nodeId: string
288
+ ): { originalId: string | null } {
289
+ const view = variationSetOf(graph, nodeId)
290
+ if (!view) throw new VariationError('not-in-set', nodeId)
291
+ graph.deleteNode(view.section.id)
292
+ return { originalId: view.original?.id ?? null }
293
+ }
@@ -0,0 +1,29 @@
1
+ import * as v from 'valibot'
2
+
3
+ /** The most versions one request makes. */
4
+ export const VARIATION_MAX_COUNT = 8
5
+
6
+ /** The longest label a version's name carries. */
7
+ export const VARIATION_LABEL_MAX_LENGTH = 40
8
+
9
+ /** The most layers one request copies, counting every version's layers. */
10
+ export const VARIATION_MAX_LAYERS = 10_000
11
+
12
+ /**
13
+ * What marks a section as a set of variations: the layer they are versions of, and a fingerprint
14
+ * of that layer when they were made, so a front end can say it changed since. The versions are
15
+ * the section's own children, so none of them needs a mark of its own.
16
+ */
17
+ export const variationSetSchema = v.object({
18
+ version: v.literal(1),
19
+ originalId: v.pipe(v.string(), v.nonEmpty()),
20
+ originalFingerprint: v.optional(v.string())
21
+ })
22
+
23
+ export type VariationSet = v.InferOutput<typeof variationSetSchema>
24
+
25
+ /**
26
+ * On a layer of a version, the id of the main component or component set of the original it
27
+ * stands in for: an instance of the component, or a frame of instances of the set's variants.
28
+ */
29
+ export const variationStandInSchema = v.pipe(v.string(), v.nonEmpty())