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

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 (885) hide show
  1. package/dist/arrow-caps.d.ts +35 -14
  2. package/dist/arrow-caps.d.ts.map +1 -1
  3. package/dist/arrow-caps.js +286 -55
  4. package/dist/arrow-caps.js.map +1 -1
  5. package/dist/asset-keys.d.ts +17 -0
  6. package/dist/asset-keys.d.ts.map +1 -0
  7. package/dist/asset-keys.js.map +1 -0
  8. package/dist/behaviours/index.d.ts +6 -0
  9. package/dist/behaviours/index.js +6 -0
  10. package/dist/behaviours/kinds.d.ts +62 -0
  11. package/dist/behaviours/kinds.d.ts.map +1 -0
  12. package/dist/{chunks/behaviours → behaviours}/kinds.js +76 -75
  13. package/dist/behaviours/kinds.js.map +1 -0
  14. package/dist/behaviours/layers.d.ts +16 -0
  15. package/dist/behaviours/layers.d.ts.map +1 -0
  16. package/dist/behaviours/layers.js +43 -0
  17. package/dist/behaviours/layers.js.map +1 -0
  18. package/dist/behaviours/model.d.ts +48 -0
  19. package/dist/behaviours/model.d.ts.map +1 -0
  20. package/dist/behaviours/model.js +156 -0
  21. package/dist/behaviours/model.js.map +1 -0
  22. package/dist/behaviours/schema.d.ts +228 -0
  23. package/dist/behaviours/schema.d.ts.map +1 -0
  24. package/dist/behaviours/schema.js +86 -0
  25. package/dist/behaviours/schema.js.map +1 -0
  26. package/dist/behaviours/spec.d.ts +26 -0
  27. package/dist/behaviours/spec.d.ts.map +1 -0
  28. package/dist/{chunks/behaviours → behaviours}/spec.js +6 -29
  29. package/dist/behaviours/spec.js.map +1 -0
  30. package/dist/bindings.js +26 -0
  31. package/dist/bindings.js.map +1 -0
  32. package/dist/buffered-events.d.ts +21 -0
  33. package/dist/buffered-events.d.ts.map +1 -0
  34. package/dist/buffered-events.js.map +1 -0
  35. package/dist/checkpoint.d.ts +42 -0
  36. package/dist/checkpoint.d.ts.map +1 -0
  37. package/dist/checkpoint.js +249 -0
  38. package/dist/checkpoint.js.map +1 -0
  39. package/dist/clipping.d.ts +31 -0
  40. package/dist/clipping.d.ts.map +1 -0
  41. package/dist/clipping.js +125 -0
  42. package/dist/clipping.js.map +1 -0
  43. package/dist/color/contrast.d.ts +17 -0
  44. package/dist/color/contrast.d.ts.map +1 -0
  45. package/dist/{chunks/color → color}/contrast.js +2 -24
  46. package/dist/color/contrast.js.map +1 -0
  47. package/dist/color/index.d.ts +38 -0
  48. package/dist/color/index.d.ts.map +1 -0
  49. package/dist/color/index.js +110 -0
  50. package/dist/color/index.js.map +1 -0
  51. package/dist/color/management.d.ts +32 -0
  52. package/dist/color/management.d.ts.map +1 -0
  53. package/dist/color/management.js +187 -0
  54. package/dist/color/management.js.map +1 -0
  55. package/dist/color/normalize.d.ts +6 -0
  56. package/dist/color/normalize.d.ts.map +1 -0
  57. package/dist/color/normalize.js +15 -0
  58. package/dist/color/normalize.js.map +1 -0
  59. package/dist/color/okhcl.d.ts +33 -0
  60. package/dist/color/okhcl.d.ts.map +1 -0
  61. package/dist/color/okhcl.js +146 -0
  62. package/dist/color/okhcl.js.map +1 -0
  63. package/dist/color/schema.d.ts +11 -0
  64. package/dist/color/schema.d.ts.map +1 -0
  65. package/dist/color/schema.js +13 -0
  66. package/dist/color/schema.js.map +1 -0
  67. package/dist/comments/document.d.ts +23 -0
  68. package/dist/comments/document.d.ts.map +1 -0
  69. package/dist/{chunks/comments → comments}/document.js +2 -1
  70. package/dist/comments/document.js.map +1 -0
  71. package/dist/comments/index.d.ts +6 -0
  72. package/dist/comments/index.js +6 -0
  73. package/dist/comments/list.d.ts +25 -0
  74. package/dist/comments/list.d.ts.map +1 -0
  75. package/dist/comments/list.js +33 -0
  76. package/dist/comments/list.js.map +1 -0
  77. package/dist/comments/merge.d.ts +16 -0
  78. package/dist/comments/merge.d.ts.map +1 -0
  79. package/dist/{chunks/comments → comments}/merge.js +1 -1
  80. package/dist/comments/merge.js.map +1 -0
  81. package/dist/comments/schema.d.ts +8 -0
  82. package/dist/comments/schema.d.ts.map +1 -0
  83. package/dist/comments/schema.js +50 -0
  84. package/dist/comments/schema.js.map +1 -0
  85. package/dist/comments/threads.d.ts +59 -0
  86. package/dist/comments/threads.d.ts.map +1 -0
  87. package/dist/{chunks/comments/list.js → comments/threads.js} +3 -53
  88. package/dist/comments/threads.js.map +1 -0
  89. package/dist/components/exposure.d.ts +24 -0
  90. package/dist/components/exposure.d.ts.map +1 -0
  91. package/dist/components/exposure.js +51 -0
  92. package/dist/components/exposure.js.map +1 -0
  93. package/dist/components/index.d.ts +4 -0
  94. package/dist/components/index.js +4 -0
  95. package/dist/components/properties.d.ts +32 -0
  96. package/dist/components/properties.d.ts.map +1 -0
  97. package/dist/components/properties.js +180 -0
  98. package/dist/components/properties.js.map +1 -0
  99. package/dist/components/variants.d.ts +33 -0
  100. package/dist/components/variants.d.ts.map +1 -0
  101. package/dist/components/variants.js +58 -0
  102. package/dist/components/variants.js.map +1 -0
  103. package/dist/connectors/controls.d.ts +34 -0
  104. package/dist/connectors/controls.d.ts.map +1 -0
  105. package/dist/connectors/controls.js +196 -0
  106. package/dist/connectors/controls.js.map +1 -0
  107. package/dist/connectors/create.d.ts +23 -0
  108. package/dist/connectors/create.d.ts.map +1 -0
  109. package/dist/connectors/create.js +33 -0
  110. package/dist/connectors/create.js.map +1 -0
  111. package/dist/connectors/elbow.js +191 -0
  112. package/dist/connectors/elbow.js.map +1 -0
  113. package/dist/connectors/gaps.d.ts +10 -0
  114. package/dist/connectors/gaps.d.ts.map +1 -0
  115. package/dist/connectors/gaps.js +86 -0
  116. package/dist/connectors/gaps.js.map +1 -0
  117. package/dist/connectors/hit.d.ts +11 -0
  118. package/dist/connectors/hit.d.ts.map +1 -0
  119. package/dist/connectors/hit.js +47 -0
  120. package/dist/connectors/hit.js.map +1 -0
  121. package/dist/connectors/index.d.ts +11 -0
  122. package/dist/connectors/index.js +11 -0
  123. package/dist/connectors/label.d.ts +32 -0
  124. package/dist/connectors/label.d.ts.map +1 -0
  125. package/dist/connectors/label.js +213 -0
  126. package/dist/connectors/label.js.map +1 -0
  127. package/dist/connectors/layout.d.ts +46 -0
  128. package/dist/connectors/layout.d.ts.map +1 -0
  129. package/dist/connectors/layout.js +234 -0
  130. package/dist/connectors/layout.js.map +1 -0
  131. package/dist/connectors/pieces.d.ts +22 -0
  132. package/dist/connectors/pieces.d.ts.map +1 -0
  133. package/dist/connectors/pieces.js +156 -0
  134. package/dist/connectors/pieces.js.map +1 -0
  135. package/dist/connectors/route.d.ts +23 -0
  136. package/dist/connectors/route.d.ts.map +1 -0
  137. package/dist/connectors/route.js +107 -0
  138. package/dist/connectors/route.js.map +1 -0
  139. package/dist/connectors/sides.d.ts +23 -0
  140. package/dist/connectors/sides.d.ts.map +1 -0
  141. package/dist/connectors/sides.js +98 -0
  142. package/dist/connectors/sides.js.map +1 -0
  143. package/dist/connectors/sublayers.d.ts +76 -0
  144. package/dist/connectors/sublayers.d.ts.map +1 -0
  145. package/dist/connectors/sublayers.js +208 -0
  146. package/dist/connectors/sublayers.js.map +1 -0
  147. package/dist/constants.d.ts +11 -2
  148. package/dist/constants.d.ts.map +1 -0
  149. package/dist/constants.js +25 -1
  150. package/dist/constants.js.map +1 -0
  151. package/dist/coordinate.d.ts +94 -2
  152. package/dist/coordinate.d.ts.map +1 -0
  153. package/dist/coordinate.js +268 -1
  154. package/dist/coordinate.js.map +1 -0
  155. package/dist/copy.d.ts +49 -2
  156. package/dist/copy.d.ts.map +1 -0
  157. package/dist/copy.js +264 -2
  158. package/dist/copy.js.map +1 -0
  159. package/dist/css/blend.d.ts +11 -0
  160. package/dist/css/blend.d.ts.map +1 -0
  161. package/dist/css/blend.js +30 -0
  162. package/dist/css/blend.js.map +1 -0
  163. package/dist/css/grid.d.ts +7 -0
  164. package/dist/css/grid.d.ts.map +1 -0
  165. package/dist/{chunks/css → css}/grid.js +2 -33
  166. package/dist/css/grid.js.map +1 -0
  167. package/dist/css/index.d.ts +7 -0
  168. package/dist/css/index.js +7 -0
  169. package/dist/css/layout.d.ts +17 -0
  170. package/dist/css/layout.d.ts.map +1 -0
  171. package/dist/css/layout.js +45 -0
  172. package/dist/css/layout.js.map +1 -0
  173. package/dist/css/shadows.d.ts +10 -0
  174. package/dist/css/shadows.d.ts.map +1 -0
  175. package/dist/css/shadows.js +64 -0
  176. package/dist/css/shadows.js.map +1 -0
  177. package/dist/css/text.d.ts +22 -0
  178. package/dist/css/text.d.ts.map +1 -0
  179. package/dist/css/text.js +76 -0
  180. package/dist/css/text.js.map +1 -0
  181. package/dist/css/values.d.ts +14 -0
  182. package/dist/css/values.d.ts.map +1 -0
  183. package/dist/css/values.js +36 -0
  184. package/dist/css/values.js.map +1 -0
  185. package/dist/cubic.d.ts +7 -0
  186. package/dist/cubic.d.ts.map +1 -0
  187. package/dist/cubic.js +17 -0
  188. package/dist/cubic.js.map +1 -0
  189. package/dist/events.js.map +1 -0
  190. package/dist/export-format.d.ts +25 -0
  191. package/dist/export-format.d.ts.map +1 -0
  192. package/dist/export-format.js +47 -0
  193. package/dist/export-format.js.map +1 -0
  194. package/dist/export-scale.d.ts +14 -0
  195. package/dist/export-scale.d.ts.map +1 -0
  196. package/dist/export-scale.js +19 -0
  197. package/dist/export-scale.js.map +1 -0
  198. package/dist/fields/appearance.d.ts +9 -0
  199. package/dist/fields/appearance.d.ts.map +1 -0
  200. package/dist/fields/appearance.js +36 -0
  201. package/dist/fields/appearance.js.map +1 -0
  202. package/dist/fields/geometry.d.ts +7 -0
  203. package/dist/fields/geometry.d.ts.map +1 -0
  204. package/dist/fields/geometry.js.map +1 -0
  205. package/dist/fields/index.d.ts +5 -0
  206. package/dist/fields/index.js +5 -0
  207. package/dist/fields/layout.d.ts +10 -0
  208. package/dist/fields/layout.d.ts.map +1 -0
  209. package/dist/fields/layout.js +49 -0
  210. package/dist/fields/layout.js.map +1 -0
  211. package/dist/fields/text.d.ts +11 -0
  212. package/dist/fields/text.d.ts.map +1 -0
  213. package/dist/fields/text.js +64 -0
  214. package/dist/fields/text.js.map +1 -0
  215. package/dist/fig-compression.d.ts +11 -0
  216. package/dist/fig-compression.d.ts.map +1 -0
  217. package/dist/fig-compression.js +15 -0
  218. package/dist/fig-compression.js.map +1 -0
  219. package/dist/figjam/index.d.ts +3 -0
  220. package/dist/figjam/index.js +3 -0
  221. package/dist/figjam/palette.d.ts +270 -0
  222. package/dist/figjam/palette.d.ts.map +1 -0
  223. package/dist/figjam/palette.js +439 -0
  224. package/dist/figjam/palette.js.map +1 -0
  225. package/dist/figjam/text.d.ts +70 -0
  226. package/dist/figjam/text.d.ts.map +1 -0
  227. package/dist/figjam/text.js +95 -0
  228. package/dist/figjam/text.js.map +1 -0
  229. package/dist/font-style.d.ts +46 -0
  230. package/dist/font-style.d.ts.map +1 -0
  231. package/dist/font-style.js +127 -0
  232. package/dist/font-style.js.map +1 -0
  233. package/dist/generated/index.d.ts +44 -0
  234. package/dist/generated/index.d.ts.map +1 -0
  235. package/dist/generated/index.js +58 -0
  236. package/dist/generated/index.js.map +1 -0
  237. package/dist/generated/kind.d.ts +27 -0
  238. package/dist/generated/kind.d.ts.map +1 -0
  239. package/dist/generated/shape-with-text.d.ts +43 -0
  240. package/dist/generated/shape-with-text.d.ts.map +1 -0
  241. package/dist/generated/shape-with-text.js +135 -0
  242. package/dist/generated/shape-with-text.js.map +1 -0
  243. package/dist/generated/sticky.d.ts +128 -0
  244. package/dist/generated/sticky.d.ts.map +1 -0
  245. package/dist/generated/sticky.js +233 -0
  246. package/dist/generated/sticky.js.map +1 -0
  247. package/dist/geometry.d.ts +89 -2
  248. package/dist/geometry.d.ts.map +1 -0
  249. package/dist/geometry.js +306 -2
  250. package/dist/geometry.js.map +1 -0
  251. package/dist/gradient.d.ts +9 -2
  252. package/dist/gradient.d.ts.map +1 -1
  253. package/dist/gradient.js +13 -1
  254. package/dist/gradient.js.map +1 -1
  255. package/dist/graph.d.ts +178 -0
  256. package/dist/graph.d.ts.map +1 -0
  257. package/dist/graph.js +625 -0
  258. package/dist/graph.js.map +1 -0
  259. package/dist/group-bounds.d.ts +42 -0
  260. package/dist/group-bounds.d.ts.map +1 -0
  261. package/dist/{chunks/group-bounds.js → group-bounds.js} +56 -14
  262. package/dist/group-bounds.js.map +1 -0
  263. package/dist/guides.d.ts +21 -2
  264. package/dist/guides.d.ts.map +1 -0
  265. package/dist/guides.js +5 -1
  266. package/dist/guides.js.map +1 -1
  267. package/dist/hit-test.d.ts +48 -2
  268. package/dist/hit-test.d.ts.map +1 -0
  269. package/dist/hit-test.js +75 -57
  270. package/dist/hit-test.js.map +1 -1
  271. package/dist/icons/glyph.d.ts +22 -0
  272. package/dist/icons/glyph.d.ts.map +1 -0
  273. package/dist/{chunks/icons → icons}/glyph.js +2 -40
  274. package/dist/icons/glyph.js.map +1 -0
  275. package/dist/icons/index.d.ts +4 -0
  276. package/dist/icons/index.js +4 -0
  277. package/dist/icons/model.d.ts +29 -0
  278. package/dist/icons/model.d.ts.map +1 -0
  279. package/dist/icons/model.js +51 -0
  280. package/dist/icons/model.js.map +1 -0
  281. package/dist/icons/schema.d.ts +31 -0
  282. package/dist/icons/schema.d.ts.map +1 -0
  283. package/dist/icons/schema.js +28 -0
  284. package/dist/icons/schema.js.map +1 -0
  285. package/dist/ids.d.ts +12 -0
  286. package/dist/ids.d.ts.map +1 -0
  287. package/dist/ids.js +31 -0
  288. package/dist/ids.js.map +1 -0
  289. package/dist/images.d.ts +39 -2
  290. package/dist/images.d.ts.map +1 -0
  291. package/dist/images.js +67 -9
  292. package/dist/images.js.map +1 -1
  293. package/dist/index.d.ts +5 -7
  294. package/dist/index.js +5 -23
  295. package/dist/instances/assignments.js +89 -0
  296. package/dist/instances/assignments.js.map +1 -0
  297. package/dist/instances/content-size.js +60 -0
  298. package/dist/instances/content-size.js.map +1 -0
  299. package/dist/instances/copies.js +161 -0
  300. package/dist/instances/copies.js.map +1 -0
  301. package/dist/instances/cycles.d.ts +20 -0
  302. package/dist/instances/cycles.d.ts.map +1 -0
  303. package/dist/instances/cycles.js +53 -0
  304. package/dist/instances/cycles.js.map +1 -0
  305. package/dist/instances/fields.d.ts +18 -0
  306. package/dist/instances/fields.d.ts.map +1 -0
  307. package/dist/instances/fields.js +90 -0
  308. package/dist/instances/fields.js.map +1 -0
  309. package/dist/instances/index.d.ts +38 -0
  310. package/dist/instances/index.d.ts.map +1 -0
  311. package/dist/instances/index.js +180 -0
  312. package/dist/instances/index.js.map +1 -0
  313. package/dist/instances/kept-overrides.js +204 -0
  314. package/dist/instances/kept-overrides.js.map +1 -0
  315. package/dist/instances/main-component.d.ts +13 -0
  316. package/dist/instances/main-component.d.ts.map +1 -0
  317. package/dist/instances/main-component.js +50 -0
  318. package/dist/instances/main-component.js.map +1 -0
  319. package/dist/instances/overrides.d.ts +51 -0
  320. package/dist/instances/overrides.d.ts.map +1 -0
  321. package/dist/instances/overrides.js +158 -0
  322. package/dist/instances/overrides.js.map +1 -0
  323. package/dist/instances/placement.js +30 -0
  324. package/dist/instances/placement.js.map +1 -0
  325. package/dist/instances/source-walk.js +31 -0
  326. package/dist/instances/source-walk.js.map +1 -0
  327. package/dist/instances/swap.js +288 -0
  328. package/dist/instances/swap.js.map +1 -0
  329. package/dist/instances/sync.js +327 -0
  330. package/dist/instances/sync.js.map +1 -0
  331. package/dist/instances/vector-geometry.js +70 -0
  332. package/dist/instances/vector-geometry.js.map +1 -0
  333. package/dist/layout/aspect-ratio.d.ts +27 -0
  334. package/dist/layout/aspect-ratio.d.ts.map +1 -0
  335. package/dist/layout/aspect-ratio.js +45 -0
  336. package/dist/layout/aspect-ratio.js.map +1 -0
  337. package/dist/layout/guides.d.ts +25 -0
  338. package/dist/layout/guides.d.ts.map +1 -0
  339. package/dist/layout/guides.js +105 -0
  340. package/dist/layout/guides.js.map +1 -0
  341. package/dist/layout/index.d.ts +5 -0
  342. package/dist/{layout.js → layout/index.js} +4 -3
  343. package/dist/layout/keywords.d.ts +26 -0
  344. package/dist/layout/keywords.d.ts.map +1 -0
  345. package/dist/layout/keywords.js +59 -0
  346. package/dist/layout/keywords.js.map +1 -0
  347. package/dist/layout/sizing.d.ts +40 -0
  348. package/dist/layout/sizing.d.ts.map +1 -0
  349. package/dist/layout/sizing.js +122 -0
  350. package/dist/layout/sizing.js.map +1 -0
  351. package/dist/layout/writes.js +55 -0
  352. package/dist/layout/writes.js.map +1 -0
  353. package/dist/matrix.d.ts +16 -2
  354. package/dist/matrix.d.ts.map +1 -0
  355. package/dist/matrix.js +119 -1
  356. package/dist/matrix.js.map +1 -0
  357. package/dist/mutation-impact.d.ts +23 -0
  358. package/dist/mutation-impact.d.ts.map +1 -0
  359. package/dist/mutation-impact.js +67 -0
  360. package/dist/mutation-impact.js.map +1 -0
  361. package/dist/node-defaults.d.ts +22 -2
  362. package/dist/node-defaults.d.ts.map +1 -0
  363. package/dist/node-defaults.js +254 -2
  364. package/dist/node-defaults.js.map +1 -0
  365. package/dist/outline/flatten.d.ts +15 -0
  366. package/dist/outline/flatten.d.ts.map +1 -0
  367. package/dist/outline/flatten.js +189 -0
  368. package/dist/outline/flatten.js.map +1 -0
  369. package/dist/outline/heads.js +34 -0
  370. package/dist/outline/heads.js.map +1 -0
  371. package/dist/outline/hit.d.ts +21 -0
  372. package/dist/outline/hit.d.ts.map +1 -0
  373. package/dist/outline/hit.js +276 -0
  374. package/dist/outline/hit.js.map +1 -0
  375. package/dist/outline/index.d.ts +5 -0
  376. package/dist/outline/index.js +5 -0
  377. package/dist/outline/point.d.ts +16 -0
  378. package/dist/outline/point.d.ts.map +1 -0
  379. package/dist/outline/point.js +42 -0
  380. package/dist/outline/point.js.map +1 -0
  381. package/dist/outline/shapes.d.ts +35 -0
  382. package/dist/outline/shapes.d.ts.map +1 -0
  383. package/dist/outline/shapes.js +181 -0
  384. package/dist/outline/shapes.js.map +1 -0
  385. package/dist/paints/index.d.ts +2 -0
  386. package/dist/paints/index.js +2 -0
  387. package/dist/paints/schema.d.ts +77 -0
  388. package/dist/paints/schema.d.ts.map +1 -0
  389. package/dist/paints/schema.js +56 -0
  390. package/dist/paints/schema.js.map +1 -0
  391. package/dist/parse-path.d.ts +9 -1
  392. package/dist/parse-path.d.ts.map +1 -1
  393. package/dist/parse-path.js +39 -2
  394. package/dist/parse-path.js.map +1 -1
  395. package/dist/plugin-data/field.d.ts +47 -0
  396. package/dist/plugin-data/field.d.ts.map +1 -0
  397. package/dist/plugin-data/field.js +73 -0
  398. package/dist/plugin-data/field.js.map +1 -0
  399. package/dist/plugin-data/fields.d.ts +143 -0
  400. package/dist/plugin-data/fields.d.ts.map +1 -0
  401. package/dist/plugin-data/fields.js +168 -0
  402. package/dist/plugin-data/fields.js.map +1 -0
  403. package/dist/plugin-data/index.d.ts +3 -0
  404. package/dist/plugin-data/index.js +3 -0
  405. package/dist/polygon.d.ts +4 -2
  406. package/dist/polygon.d.ts.map +1 -1
  407. package/dist/polygon.js +17 -2
  408. package/dist/polygon.js.map +1 -1
  409. package/dist/preview.d.ts +12 -2
  410. package/dist/preview.d.ts.map +1 -0
  411. package/dist/preview.js +62 -1
  412. package/dist/preview.js.map +1 -0
  413. package/dist/{primitives2.d.ts → primitives/index.d.ts} +4 -3
  414. package/dist/primitives/index.d.ts.map +1 -0
  415. package/dist/primitives/index.js +2 -0
  416. package/dist/primitives/schema.d.ts +18 -0
  417. package/dist/primitives/schema.d.ts.map +1 -0
  418. package/dist/primitives/schema.js +19 -0
  419. package/dist/primitives/schema.js.map +1 -0
  420. package/dist/random.js +24 -1
  421. package/dist/random.js.map +1 -0
  422. package/dist/resize.d.ts +6 -4
  423. package/dist/resize.d.ts.map +1 -1
  424. package/dist/resize.js +287 -2
  425. package/dist/resize.js.map +1 -0
  426. package/dist/scaling/index.d.ts +3 -0
  427. package/dist/scaling/index.js +3 -0
  428. package/dist/scaling/node.d.ts +6 -0
  429. package/dist/scaling/node.d.ts.map +1 -0
  430. package/dist/scaling/node.js +148 -0
  431. package/dist/scaling/node.js.map +1 -0
  432. package/dist/scaling/tree.d.ts +7 -0
  433. package/dist/scaling/tree.d.ts.map +1 -0
  434. package/dist/scaling/tree.js +47 -0
  435. package/dist/scaling/tree.js.map +1 -0
  436. package/dist/shaders/index.d.ts +4 -0
  437. package/dist/shaders/index.js +4 -0
  438. package/dist/shaders/model.d.ts +41 -0
  439. package/dist/shaders/model.d.ts.map +1 -0
  440. package/dist/shaders/model.js +71 -0
  441. package/dist/shaders/model.js.map +1 -0
  442. package/dist/shaders/schema.d.ts +41 -0
  443. package/dist/shaders/schema.d.ts.map +1 -0
  444. package/dist/shaders/schema.js +36 -0
  445. package/dist/shaders/schema.js.map +1 -0
  446. package/dist/shaders/still.d.ts +18 -0
  447. package/dist/shaders/still.d.ts.map +1 -0
  448. package/dist/shaders/still.js +36 -0
  449. package/dist/shaders/still.js.map +1 -0
  450. package/dist/shape-with-text/fit.d.ts +28 -0
  451. package/dist/shape-with-text/fit.d.ts.map +1 -0
  452. package/dist/shape-with-text/fit.js +271 -0
  453. package/dist/shape-with-text/fit.js.map +1 -0
  454. package/dist/shape-with-text/geometry.d.ts +20 -0
  455. package/dist/shape-with-text/geometry.d.ts.map +1 -0
  456. package/dist/shape-with-text/geometry.js +539 -0
  457. package/dist/shape-with-text/geometry.js.map +1 -0
  458. package/dist/shape-with-text/index.d.ts +4 -0
  459. package/dist/shape-with-text/index.js +4 -0
  460. package/dist/shape-with-text/kinds.d.ts +20 -0
  461. package/dist/shape-with-text/kinds.d.ts.map +1 -0
  462. package/dist/shape-with-text/kinds.js +86 -0
  463. package/dist/shape-with-text/kinds.js.map +1 -0
  464. package/dist/shared-styles.d.ts +51 -0
  465. package/dist/shared-styles.d.ts.map +1 -0
  466. package/dist/shared-styles.js +186 -0
  467. package/dist/shared-styles.js.map +1 -0
  468. package/dist/slots/authoring.d.ts +27 -0
  469. package/dist/slots/authoring.d.ts.map +1 -0
  470. package/dist/slots/authoring.js +77 -0
  471. package/dist/slots/authoring.js.map +1 -0
  472. package/dist/slots/content.d.ts +41 -0
  473. package/dist/slots/content.d.ts.map +1 -0
  474. package/dist/slots/content.js +105 -0
  475. package/dist/slots/content.js.map +1 -0
  476. package/dist/slots/frames.d.ts +40 -0
  477. package/dist/slots/frames.d.ts.map +1 -0
  478. package/dist/slots/frames.js +118 -0
  479. package/dist/slots/frames.js.map +1 -0
  480. package/dist/slots/index.d.ts +5 -0
  481. package/dist/slots/index.js +5 -0
  482. package/dist/slots/limits.d.ts +14 -0
  483. package/dist/slots/limits.d.ts.map +1 -0
  484. package/dist/slots/limits.js +28 -0
  485. package/dist/slots/limits.js.map +1 -0
  486. package/dist/snap.d.ts +21 -2
  487. package/dist/snap.d.ts.map +1 -0
  488. package/dist/snap.js +109 -1
  489. package/dist/snap.js.map +1 -0
  490. package/dist/source-metadata.js +10 -1
  491. package/dist/source-metadata.js.map +1 -0
  492. package/dist/statuses/impact.d.ts +18 -0
  493. package/dist/statuses/impact.d.ts.map +1 -0
  494. package/dist/statuses/impact.js +33 -0
  495. package/dist/statuses/impact.js.map +1 -0
  496. package/dist/statuses/index.d.ts +5 -0
  497. package/dist/statuses/index.js +5 -0
  498. package/dist/statuses/node.d.ts +22 -0
  499. package/dist/statuses/node.d.ts.map +1 -0
  500. package/dist/statuses/node.js +47 -0
  501. package/dist/statuses/node.js.map +1 -0
  502. package/dist/statuses/schema.d.ts +59 -0
  503. package/dist/statuses/schema.d.ts.map +1 -0
  504. package/dist/statuses/schema.js +27 -0
  505. package/dist/statuses/schema.js.map +1 -0
  506. package/dist/statuses/workflow.d.ts +120 -0
  507. package/dist/statuses/workflow.d.ts.map +1 -0
  508. package/dist/statuses/workflow.js +135 -0
  509. package/dist/statuses/workflow.js.map +1 -0
  510. package/dist/{text-direction.d.ts → text/direction.d.ts} +2 -2
  511. package/dist/text/direction.d.ts.map +1 -0
  512. package/dist/{text-direction.js → text/direction.js} +1 -1
  513. package/dist/text/direction.js.map +1 -0
  514. package/dist/text/index.d.ts +7 -0
  515. package/dist/text/index.js +7 -0
  516. package/dist/text/lengths.d.ts +24 -0
  517. package/dist/text/lengths.d.ts.map +1 -0
  518. package/dist/text/lengths.js +49 -0
  519. package/dist/text/lengths.js.map +1 -0
  520. package/dist/text/lists.d.ts +44 -0
  521. package/dist/text/lists.d.ts.map +1 -0
  522. package/dist/text/lists.js +100 -0
  523. package/dist/text/lists.js.map +1 -0
  524. package/dist/text/overflow.d.ts +11 -0
  525. package/dist/text/overflow.d.ts.map +1 -0
  526. package/dist/text/overflow.js +13 -0
  527. package/dist/text/overflow.js.map +1 -0
  528. package/dist/text/paragraphs.d.ts +62 -0
  529. package/dist/text/paragraphs.d.ts.map +1 -0
  530. package/dist/text/paragraphs.js +166 -0
  531. package/dist/text/paragraphs.js.map +1 -0
  532. package/dist/{text-picture.d.ts → text/picture.d.ts} +3 -4
  533. package/dist/text/picture.d.ts.map +1 -0
  534. package/dist/text/picture.js +38 -0
  535. package/dist/text/picture.js.map +1 -0
  536. package/dist/text/references.d.ts +21 -0
  537. package/dist/text/references.d.ts.map +1 -0
  538. package/dist/text/references.js +43 -0
  539. package/dist/text/references.js.map +1 -0
  540. package/dist/text/schema.d.ts +10 -0
  541. package/dist/text/schema.d.ts.map +1 -0
  542. package/dist/text/schema.js +11 -0
  543. package/dist/text/schema.js.map +1 -0
  544. package/dist/transfer/apply.d.ts +9 -0
  545. package/dist/transfer/apply.d.ts.map +1 -0
  546. package/dist/transfer/apply.js +65 -0
  547. package/dist/transfer/apply.js.map +1 -0
  548. package/dist/transfer/copied.d.ts +14 -0
  549. package/dist/transfer/copied.d.ts.map +1 -0
  550. package/dist/transfer/copied.js +52 -0
  551. package/dist/transfer/copied.js.map +1 -0
  552. package/dist/transfer/history.d.ts +8 -0
  553. package/dist/transfer/history.d.ts.map +1 -0
  554. package/dist/transfer/history.js +32 -0
  555. package/dist/transfer/history.js.map +1 -0
  556. package/dist/transfer/identity.js +12 -0
  557. package/dist/transfer/identity.js.map +1 -0
  558. package/dist/transfer/index.d.ts +8 -0
  559. package/dist/transfer/index.js +8 -0
  560. package/dist/transfer/nodes.d.ts +14 -0
  561. package/dist/transfer/nodes.d.ts.map +1 -0
  562. package/dist/transfer/nodes.js +78 -0
  563. package/dist/transfer/nodes.js.map +1 -0
  564. package/dist/transfer/plan.d.ts +29 -0
  565. package/dist/transfer/plan.d.ts.map +1 -0
  566. package/dist/transfer/plan.js +106 -0
  567. package/dist/transfer/plan.js.map +1 -0
  568. package/dist/transfer/references.js +10 -0
  569. package/dist/transfer/references.js.map +1 -0
  570. package/dist/transfer/remove.d.ts +8 -0
  571. package/dist/transfer/remove.d.ts.map +1 -0
  572. package/dist/transfer/remove.js +34 -0
  573. package/dist/transfer/remove.js.map +1 -0
  574. package/dist/transfer/validation.js +39 -0
  575. package/dist/transfer/validation.js.map +1 -0
  576. package/dist/transfer/variables.d.ts +15 -0
  577. package/dist/transfer/variables.d.ts.map +1 -0
  578. package/dist/transfer/variables.js +52 -0
  579. package/dist/transfer/variables.js.map +1 -0
  580. package/dist/types.d.ts +195 -2007
  581. package/dist/types.d.ts.map +1 -1
  582. package/dist/types.js +89 -2
  583. package/dist/types.js.map +1 -0
  584. package/dist/undo.d.ts +93 -2
  585. package/dist/undo.d.ts.map +1 -0
  586. package/dist/undo.js +235 -1
  587. package/dist/undo.js.map +1 -0
  588. package/dist/variables/bindings.d.ts +83 -0
  589. package/dist/variables/bindings.d.ts.map +1 -0
  590. package/dist/variables/bindings.js +314 -0
  591. package/dist/variables/bindings.js.map +1 -0
  592. package/dist/variables/corners.d.ts +12 -0
  593. package/dist/variables/corners.d.ts.map +1 -0
  594. package/dist/variables/corners.js +38 -0
  595. package/dist/variables/corners.js.map +1 -0
  596. package/dist/variables/fields.d.ts +43 -0
  597. package/dist/variables/fields.d.ts.map +1 -0
  598. package/dist/variables/fields.js +104 -0
  599. package/dist/variables/fields.js.map +1 -0
  600. package/dist/variables/formula/check.d.ts +14 -0
  601. package/dist/variables/formula/check.d.ts.map +1 -0
  602. package/dist/variables/formula/check.js +73 -0
  603. package/dist/variables/formula/check.js.map +1 -0
  604. package/dist/variables/formula/evaluate.d.ts +7 -0
  605. package/dist/variables/formula/evaluate.d.ts.map +1 -0
  606. package/dist/variables/formula/evaluate.js +30 -0
  607. package/dist/variables/formula/evaluate.js.map +1 -0
  608. package/dist/variables/formula/index.d.ts +21 -0
  609. package/dist/variables/formula/index.d.ts.map +1 -0
  610. package/dist/variables/formula/index.js +77 -0
  611. package/dist/variables/formula/index.js.map +1 -0
  612. package/dist/variables/formula/parse.js +141 -0
  613. package/dist/variables/formula/parse.js.map +1 -0
  614. package/dist/variables/formula/print.d.ts +25 -0
  615. package/dist/variables/formula/print.d.ts.map +1 -0
  616. package/dist/variables/formula/print.js +105 -0
  617. package/dist/variables/formula/print.js.map +1 -0
  618. package/dist/variables/formula/schema.d.ts +7 -0
  619. package/dist/variables/formula/schema.d.ts.map +1 -0
  620. package/dist/variables/formula/schema.js +62 -0
  621. package/dist/variables/formula/schema.js.map +1 -0
  622. package/dist/variables/formula/signatures.d.ts +9 -0
  623. package/dist/variables/formula/signatures.d.ts.map +1 -0
  624. package/dist/variables/formula/signatures.js +238 -0
  625. package/dist/variables/formula/signatures.js.map +1 -0
  626. package/dist/variables/formula/tokens.d.ts +26 -0
  627. package/dist/variables/formula/tokens.d.ts.map +1 -0
  628. package/dist/variables/formula/tokens.js +82 -0
  629. package/dist/variables/formula/tokens.js.map +1 -0
  630. package/dist/variables/formula/tree.d.ts +22 -0
  631. package/dist/variables/formula/tree.d.ts.map +1 -0
  632. package/dist/variables/formula/tree.js +35 -0
  633. package/dist/variables/formula/tree.js.map +1 -0
  634. package/dist/variables/index.d.ts +41 -0
  635. package/dist/variables/index.d.ts.map +1 -0
  636. package/dist/variables/index.js +238 -0
  637. package/dist/variables/index.js.map +1 -0
  638. package/dist/variables/resolution.d.ts +39 -0
  639. package/dist/variables/resolution.d.ts.map +1 -0
  640. package/dist/variables/resolution.js +154 -0
  641. package/dist/variables/resolution.js.map +1 -0
  642. package/dist/variables/schema.d.ts +40 -0
  643. package/dist/variables/schema.d.ts.map +1 -0
  644. package/dist/variables/schema.js +32 -0
  645. package/dist/variables/schema.js.map +1 -0
  646. package/dist/variables/text.d.ts +16 -0
  647. package/dist/variables/text.d.ts.map +1 -0
  648. package/dist/variables/text.js +49 -0
  649. package/dist/variables/text.js.map +1 -0
  650. package/dist/variables/token.d.ts +18 -0
  651. package/dist/variables/token.d.ts.map +1 -0
  652. package/dist/variables/token.js +39 -0
  653. package/dist/variables/token.js.map +1 -0
  654. package/dist/variables/units.js +19 -0
  655. package/dist/variables/units.js.map +1 -0
  656. package/dist/variables/value.d.ts +12 -0
  657. package/dist/variables/value.d.ts.map +1 -0
  658. package/dist/variables/value.js +70 -0
  659. package/dist/variables/value.js.map +1 -0
  660. package/dist/vector-network.d.ts +65 -2
  661. package/dist/vector-network.d.ts.map +1 -0
  662. package/dist/vector-network.js +375 -2
  663. package/dist/vector-network.js.map +1 -0
  664. package/package.json +303 -137
  665. package/src/arrow-caps.ts +279 -62
  666. package/src/behaviours/index.ts +5 -0
  667. package/src/behaviours/kinds.ts +51 -34
  668. package/src/behaviours/layers.ts +5 -3
  669. package/src/behaviours/model.ts +25 -22
  670. package/src/behaviours/schema.ts +64 -13
  671. package/src/behaviours/spec.ts +11 -50
  672. package/src/bindings.ts +11 -2
  673. package/src/checkpoint.ts +252 -5
  674. package/src/clipping.ts +112 -0
  675. package/src/color/index.ts +1 -0
  676. package/src/color/schema.ts +10 -0
  677. package/src/comments/document.ts +1 -1
  678. package/src/comments/index.ts +5 -0
  679. package/src/comments/schema.ts +51 -0
  680. package/src/comments/threads.ts +1 -1
  681. package/src/components/exposure.ts +1 -1
  682. package/src/components/index.ts +8 -0
  683. package/src/components/properties.ts +94 -4
  684. package/src/components/variants.ts +52 -31
  685. package/src/connectors/controls.ts +229 -0
  686. package/src/connectors/create.ts +48 -0
  687. package/src/connectors/elbow.ts +235 -0
  688. package/src/connectors/gaps.ts +72 -0
  689. package/src/connectors/hit.ts +49 -0
  690. package/src/connectors/index.ts +28 -0
  691. package/src/connectors/label.ts +238 -0
  692. package/src/connectors/layout.ts +280 -0
  693. package/src/connectors/pieces.ts +141 -0
  694. package/src/connectors/route.ts +148 -0
  695. package/src/connectors/sides.ts +94 -0
  696. package/src/connectors/sublayers.ts +203 -0
  697. package/src/coordinate.ts +10 -3
  698. package/src/copy.ts +71 -31
  699. package/src/css/blend.ts +27 -0
  700. package/src/css/index.ts +2 -0
  701. package/src/css/text.ts +84 -0
  702. package/src/cubic.ts +14 -0
  703. package/src/export-format.ts +30 -1
  704. package/src/fields/appearance.ts +35 -0
  705. package/src/fields/index.ts +4 -0
  706. package/src/fields/layout.ts +48 -0
  707. package/src/fields/text.ts +32 -1
  708. package/src/fig-compression.ts +9 -0
  709. package/src/figjam/index.ts +2 -0
  710. package/src/figjam/palette.ts +473 -0
  711. package/src/figjam/text.ts +83 -0
  712. package/src/font-style.ts +58 -14
  713. package/src/generated/index.ts +76 -0
  714. package/src/generated/kind.ts +24 -0
  715. package/src/generated/shape-with-text.ts +157 -0
  716. package/src/generated/sticky.ts +213 -0
  717. package/src/geometry.ts +102 -312
  718. package/src/gradient.ts +14 -0
  719. package/src/graph.ts +849 -0
  720. package/src/group-bounds.ts +59 -12
  721. package/src/guides.ts +6 -1
  722. package/src/hit-test.ts +118 -74
  723. package/src/icons/index.ts +3 -0
  724. package/src/icons/model.ts +9 -0
  725. package/src/icons/schema.ts +19 -3
  726. package/src/ids.ts +34 -0
  727. package/src/images.ts +71 -8
  728. package/src/index.ts +2 -976
  729. package/src/instances/assignments.ts +116 -0
  730. package/src/instances/content-size.ts +23 -2
  731. package/src/instances/copies.ts +7 -10
  732. package/src/instances/cycles.ts +1 -1
  733. package/src/instances/fields.ts +47 -92
  734. package/src/{instances.ts → instances/index.ts} +69 -44
  735. package/src/instances/kept-overrides.ts +280 -0
  736. package/src/instances/main-component.ts +55 -1
  737. package/src/{instance-overrides.ts → instances/overrides.ts} +58 -2
  738. package/src/instances/placement.ts +1 -1
  739. package/src/instances/source-walk.ts +3 -9
  740. package/src/instances/swap.ts +451 -0
  741. package/src/instances/sync.ts +166 -177
  742. package/src/instances/vector-geometry.ts +3 -3
  743. package/src/layout/aspect-ratio.ts +1 -1
  744. package/src/layout/sizing.ts +1 -1
  745. package/src/layout/writes.ts +59 -0
  746. package/src/matrix.ts +1 -1
  747. package/src/mutation-impact.ts +1 -1
  748. package/src/node-defaults.ts +43 -3
  749. package/src/outline/flatten.ts +190 -0
  750. package/src/outline/heads.ts +52 -0
  751. package/src/outline/hit.ts +369 -0
  752. package/src/outline/index.ts +4 -0
  753. package/src/outline/point.ts +59 -0
  754. package/src/outline/shapes.ts +207 -0
  755. package/src/paints/index.ts +1 -0
  756. package/src/paints/schema.ts +67 -0
  757. package/src/parse-path.ts +49 -4
  758. package/src/plugin-data/fields.ts +69 -77
  759. package/src/plugin-data/index.ts +2 -0
  760. package/src/polygon.ts +17 -0
  761. package/src/preview.ts +1 -1
  762. package/src/{primitives.ts → primitives/index.ts} +2 -0
  763. package/src/primitives/schema.ts +14 -0
  764. package/src/resize.ts +32 -6
  765. package/src/scaling/node.ts +10 -6
  766. package/src/scaling/tree.ts +2 -1
  767. package/src/shaders/index.ts +3 -0
  768. package/src/shaders/schema.ts +3 -3
  769. package/src/shape-with-text/fit.ts +154 -0
  770. package/src/shape-with-text/geometry.ts +496 -0
  771. package/src/shape-with-text/index.ts +10 -0
  772. package/src/shape-with-text/kinds.ts +86 -0
  773. package/src/shared-styles.ts +169 -17
  774. package/src/slots/authoring.ts +1 -1
  775. package/src/slots/content.ts +10 -5
  776. package/src/slots/frames.ts +12 -10
  777. package/src/slots/index.ts +4 -0
  778. package/src/slots/limits.ts +1 -1
  779. package/src/snap.ts +3 -1
  780. package/src/statuses/impact.ts +38 -0
  781. package/src/statuses/index.ts +4 -0
  782. package/src/statuses/node.ts +63 -0
  783. package/src/statuses/schema.ts +39 -0
  784. package/src/statuses/workflow.ts +121 -0
  785. package/src/text/index.ts +3 -0
  786. package/src/text/lengths.ts +44 -0
  787. package/src/text/overflow.ts +12 -0
  788. package/src/text/picture.ts +0 -4
  789. package/src/text/schema.ts +7 -0
  790. package/src/transfer/apply.ts +1 -1
  791. package/src/transfer/copied.ts +72 -0
  792. package/src/transfer/history.ts +1 -1
  793. package/src/transfer/index.ts +1 -0
  794. package/src/transfer/nodes.ts +18 -19
  795. package/src/transfer/plan.ts +1 -1
  796. package/src/transfer/remove.ts +1 -1
  797. package/src/transfer/validation.ts +1 -1
  798. package/src/transfer/variables.ts +7 -6
  799. package/src/types.ts +246 -13
  800. package/src/undo.ts +64 -2
  801. package/src/variables/bindings.ts +166 -66
  802. package/src/variables/corners.ts +39 -0
  803. package/src/variables/fields.ts +83 -0
  804. package/src/variables/formula/check.ts +99 -0
  805. package/src/variables/formula/evaluate.ts +33 -0
  806. package/src/variables/formula/index.ts +129 -0
  807. package/src/variables/formula/parse.ts +160 -0
  808. package/src/variables/formula/print.ts +167 -0
  809. package/src/variables/formula/schema.ts +77 -0
  810. package/src/variables/formula/signatures.ts +266 -0
  811. package/src/variables/formula/tokens.ts +114 -0
  812. package/src/variables/formula/tree.ts +53 -0
  813. package/src/{variables.ts → variables/index.ts} +86 -146
  814. package/src/variables/resolution.ts +293 -0
  815. package/src/variables/schema.ts +31 -0
  816. package/src/variables/text.ts +51 -0
  817. package/src/variables/token.ts +27 -1
  818. package/src/variables/value.ts +92 -0
  819. package/src/vector-network.ts +263 -22
  820. package/dist/chunks/asset-keys.js.map +0 -1
  821. package/dist/chunks/behaviours/kinds.js.map +0 -1
  822. package/dist/chunks/behaviours/layers.js +0 -611
  823. package/dist/chunks/behaviours/layers.js.map +0 -1
  824. package/dist/chunks/behaviours/spec.js.map +0 -1
  825. package/dist/chunks/bindings.js +0 -18
  826. package/dist/chunks/bindings.js.map +0 -1
  827. package/dist/chunks/buffered-events.js.map +0 -1
  828. package/dist/chunks/checkpoint.js +0 -78
  829. package/dist/chunks/checkpoint.js.map +0 -1
  830. package/dist/chunks/color/contrast.js.map +0 -1
  831. package/dist/chunks/color/index.js +0 -1662
  832. package/dist/chunks/color/index.js.map +0 -1
  833. package/dist/chunks/comments/document.js.map +0 -1
  834. package/dist/chunks/comments/list.js.map +0 -1
  835. package/dist/chunks/comments/merge.js.map +0 -1
  836. package/dist/chunks/components/exposure.js +0 -2291
  837. package/dist/chunks/components/exposure.js.map +0 -1
  838. package/dist/chunks/components/variants.js +0 -32
  839. package/dist/chunks/components/variants.js.map +0 -1
  840. package/dist/chunks/coordinate.js +0 -385
  841. package/dist/chunks/coordinate.js.map +0 -1
  842. package/dist/chunks/css/grid.js.map +0 -1
  843. package/dist/chunks/css/index.js +0 -160
  844. package/dist/chunks/css/index.js.map +0 -1
  845. package/dist/chunks/events.js.map +0 -1
  846. package/dist/chunks/fields/geometry.js.map +0 -1
  847. package/dist/chunks/font-style.js +0 -96
  848. package/dist/chunks/font-style.js.map +0 -1
  849. package/dist/chunks/group-bounds.js.map +0 -1
  850. package/dist/chunks/icons/glyph.js.map +0 -1
  851. package/dist/chunks/index.js +0 -2430
  852. package/dist/chunks/index.js.map +0 -1
  853. package/dist/color.d.ts +0 -78
  854. package/dist/color.d.ts.map +0 -1
  855. package/dist/color.js +0 -3
  856. package/dist/constants2.d.ts +0 -11
  857. package/dist/constants2.d.ts.map +0 -1
  858. package/dist/css.d.ts +0 -39
  859. package/dist/css.d.ts.map +0 -1
  860. package/dist/css.js +0 -3
  861. package/dist/images2.d.ts +0 -16
  862. package/dist/images2.d.ts.map +0 -1
  863. package/dist/instances.d.ts +0 -2
  864. package/dist/instances.js +0 -2
  865. package/dist/layout.d.ts +0 -2
  866. package/dist/matrix2.d.ts +0 -16
  867. package/dist/matrix2.d.ts.map +0 -1
  868. package/dist/primitives.d.ts +0 -2
  869. package/dist/primitives.js +0 -0
  870. package/dist/primitives2.d.ts.map +0 -1
  871. package/dist/text-direction.d.ts.map +0 -1
  872. package/dist/text-direction.js.map +0 -1
  873. package/dist/text-picture.d.ts.map +0 -1
  874. package/dist/text-picture.js +0 -2
  875. package/dist/text.d.ts +0 -2
  876. package/dist/text.js +0 -3
  877. package/dist/types2.d.ts +0 -2
  878. package/dist/undo2.d.ts +0 -73
  879. package/dist/undo2.d.ts.map +0 -1
  880. package/dist/variables.d.ts +0 -2
  881. package/dist/variables.js +0 -2
  882. /package/dist/{chunks/asset-keys.js → asset-keys.js} +0 -0
  883. /package/dist/{chunks/buffered-events.js → buffered-events.js} +0 -0
  884. /package/dist/{chunks/events.js → events.js} +0 -0
  885. /package/dist/{chunks/fields → fields}/geometry.js +0 -0
@@ -1,2430 +0,0 @@
1
- import { CONTAINER_TYPES, cloneNodeProps, copyFills, copyStrokes, createDefaultNode, getInstanceOverride, normalizeVectorNetwork, remapInstanceOverrideState, rotatedBBox, setInstanceOverride } from "./color/index.js";
2
- import { BLACK, TRANSPARENT } from "./color/contrast.js";
3
- import { BOOLEAN_BINDING_FIELDS, NUMERIC_FIELDS, STRING_BINDING_FIELDS, TEXT_LAYOUT_FIELDS, TEXT_SHAPING_FIELDS, cloneChildrenWithMapping, createInstance, detachInstance, findInstanceAncestor, getInstances, getMainComponent, hasInstanceOverride, isNumericVariableBindingField, ownsSlotContent, paragraphStyleAt, populateInstanceChildren, scaleNodeChanges, scaleVariableBindingUnits, slotPropertyId, swapInstanceComponent, syncInstance, syncInstances, syncInstancesTogether, textParagraphRanges } from "./components/exposure.js";
4
- import { OPEN_PENCIL_PLUGIN_DATA, readAllPluginData, withAllPluginData } from "./behaviours/layers.js";
5
- import { SIZE_FIELDS, TRANSFORM_FIELDS } from "./fields/geometry.js";
6
- import { randomHex, randomIndex } from "./comments/list.js";
7
- import { Matrix, getAbsolutePosition, getNodeLocalMatrix, getParentWorldMatrix, isTranslationOnly, localTransformFromWorld } from "./coordinate.js";
8
- import { removeStaleBindings } from "./bindings.js";
9
- import { BufferedSceneEmitter } from "./buffered-events.js";
10
- import { bindNodeEvents } from "./events.js";
11
- import { hitTest, hitTestDeep, hitTestDropTarget, hitTestOpenContainer, hitTestSelectable, isOpenContainer, isPointInNode } from "../hit-test.js";
12
- import { partition, uniq } from "es-toolkit/array";
13
- import { isEqual } from "es-toolkit/predicate";
14
- import { mapValues, omit, omitBy } from "es-toolkit/object";
15
- import { sha1 } from "@noble/hashes/legacy.js";
16
- import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
17
- //#region src/mutation-impact.ts
18
- function createSceneMutationImpact() {
19
- return {
20
- changedNodeIds: /* @__PURE__ */ new Set(),
21
- previousParentIds: /* @__PURE__ */ new Set(),
22
- currentParentIds: /* @__PURE__ */ new Set(),
23
- createdNodeIds: /* @__PURE__ */ new Set(),
24
- deletedNodeIds: /* @__PURE__ */ new Set()
25
- };
26
- }
27
- /** Records into `impact` the nodes and parent containers the graph's edits touch, until unbound. */
28
- function recordSceneMutations(graph, impact, shouldRecord = () => true) {
29
- return graph.onNodeEvents({
30
- created: (node) => {
31
- if (!shouldRecord()) return;
32
- impact.createdNodeIds.add(node.id);
33
- impact.changedNodeIds.add(node.id);
34
- if (node.parentId) impact.currentParentIds.add(node.parentId);
35
- },
36
- updated: (id) => {
37
- if (shouldRecord()) impact.changedNodeIds.add(id);
38
- },
39
- deleted: (id, parentId) => {
40
- if (!shouldRecord()) return;
41
- if (parentId) impact.previousParentIds.add(parentId);
42
- impact.deletedNodeIds.add(id);
43
- impact.changedNodeIds.add(id);
44
- },
45
- reparented: (nodeId, oldParentId, newParentId) => {
46
- if (!shouldRecord()) return;
47
- impact.changedNodeIds.add(nodeId);
48
- if (oldParentId) impact.previousParentIds.add(oldParentId);
49
- impact.currentParentIds.add(newParentId);
50
- },
51
- reordered: (nodeId, parentId, _index, previousParentId) => {
52
- if (!shouldRecord()) return;
53
- impact.changedNodeIds.add(nodeId);
54
- if (previousParentId && previousParentId !== parentId) impact.previousParentIds.add(previousParentId);
55
- impact.currentParentIds.add(parentId);
56
- }
57
- });
58
- }
59
- /** Collects the actual graph nodes and parent containers touched by an operation. */
60
- async function collectSceneMutation(graph, operation) {
61
- const impact = createSceneMutationImpact();
62
- const unbind = recordSceneMutations(graph, impact);
63
- try {
64
- return {
65
- result: await operation(),
66
- impact
67
- };
68
- } finally {
69
- unbind();
70
- }
71
- }
72
- function mutationLayoutScopeIds(impact) {
73
- return uniq([
74
- ...impact.changedNodeIds,
75
- ...impact.previousParentIds,
76
- ...impact.currentParentIds
77
- ]);
78
- }
79
- //#endregion
80
- //#region src/variables/bindings.ts
81
- /** New declarations belong to the outermost occurrence, bounded by a component definition. */
82
- function variableBindingOwner(graph, node) {
83
- let owner = node;
84
- let current = node;
85
- while (current) {
86
- if (current.type === "COMPONENT" || current.type === "COMPONENT_SET") break;
87
- if (current.type === "INSTANCE") owner = current;
88
- current = current.parentId ? graph.getNode(current.parentId) : void 0;
89
- }
90
- return owner;
91
- }
92
- function assignVariableBindingUnits(graph, node, field) {
93
- if (!isNumericVariableBindingField(field)) return;
94
- const owner = variableBindingOwner(graph, node);
95
- node.variableBindingScales = {
96
- ...node.variableBindingScales,
97
- [field]: owner.variableAssignmentScales[field] ?? 1
98
- };
99
- }
100
- /**
101
- * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields
102
- * whose stored value differs. A width or height an instance overrides keeps its own value.
103
- */
104
- function resolvedNumericBindings(graph, node, fallback = "active") {
105
- const updates = {};
106
- for (const [field, variableId] of Object.entries(node.boundVariables)) {
107
- if (!NUMERIC_FIELDS.has(field)) continue;
108
- if ((field === "width" || field === "height") && hasInstanceOverride(graph, node.id, field)) continue;
109
- const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback);
110
- if (value === void 0 || !Number.isFinite(value)) continue;
111
- const effective = value * (node.variableBindingScales[field] ?? 1);
112
- if (!Number.isFinite(effective)) continue;
113
- const next = field === "opacity" ? Math.max(0, Math.min(1, effective)) : effective;
114
- if (node[field] !== next) Object.assign(updates, { [field]: next });
115
- }
116
- return updates;
117
- }
118
- /**
119
- * The text a variable bound to text content shows: a string as it is, and a number or boolean
120
- * as Figma writes it, since Figma lets either be text content.
121
- */
122
- function variableText(value) {
123
- if (typeof value === "string") return value;
124
- if (typeof value === "boolean") return String(value);
125
- if (typeof value === "number" && Number.isFinite(value)) return numberText(value);
126
- }
127
- const INT32_MIN = -2147483648;
128
- const INT32_MAX = 2147483647;
129
- /** How near a whole number a value must be for Figma to write it as one. */
130
- const WHOLE_NUMBER_TOLERANCE = 1e-6;
131
- /**
132
- * A number as Figma desktop 126 writes it as text: one within a millionth of a whole number as
133
- * that integer, clamped to 32 bits, and anything else with two decimals, its sign kept and an
134
- * exact tie rounded to even, as C's `%.2f` does (0.125 is "0.12", 0.999 is "1.00", -0.004 is
135
- * "-0.00").
136
- */
137
- function numberText(value) {
138
- const whole = Math.round(value);
139
- if (Math.abs(value - whole) < WHOLE_NUMBER_TOLERANCE) return String(Math.min(INT32_MAX, Math.max(INT32_MIN, whole)) || 0);
140
- const scaled = Math.abs(value) * 100;
141
- const floor = Math.floor(scaled);
142
- const cents = scaled - floor === .5 ? floor + floor % 2 : Math.round(scaled);
143
- return `${value < 0 ? "-" : ""}${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
144
- }
145
- /**
146
- * The text and visibility a node's string and boolean bindings resolve to in its mode, for the
147
- * fields whose stored value differs. Text or visibility an instance overrides, which typing in a
148
- * layer or toggling its eye records, keeps its own value, as an overridden width or height does.
149
- * A bound font family is left as stored: changing it needs the font loaded, which resolving a
150
- * binding cannot do.
151
- */
152
- function resolvedValueBindings(graph, node, fallback = "active") {
153
- const updates = {};
154
- const resolve = (field) => {
155
- const variableId = node.boundVariables[field];
156
- if (!variableId || hasInstanceOverride(graph, node.id, field)) return void 0;
157
- return graph.resolveVariableForNode(node.id, variableId, fallback);
158
- };
159
- const text = node.type === "TEXT" ? variableText(resolve("text")) : void 0;
160
- if (text !== void 0 && text !== node.text) updates.text = text;
161
- const visible = resolve("visible");
162
- if (typeof visible === "boolean" && visible !== node.visible) updates.visible = visible;
163
- return updates;
164
- }
165
- /** Fields of a range of characters a bound number gives its value; the rest need fonts loaded. */
166
- const NUMERIC_RUN_FIELDS = [
167
- "fontSize",
168
- "fontWeight",
169
- "letterSpacing",
170
- "lineHeight"
171
- ];
172
- /**
173
- * The runs a text's character bindings resolve to in its mode, when a bound number differs from
174
- * what its characters hold. Bound font families and styles are left as stored, as the text's own.
175
- */
176
- function resolvedRunBindings(graph, node, fallback = "active") {
177
- const styleRuns = node.styleRuns.map((run) => {
178
- const bound = run.style.boundVariables;
179
- if (!bound) return run;
180
- let style = run.style;
181
- for (const field of NUMERIC_RUN_FIELDS) {
182
- const variableId = bound[field];
183
- if (!variableId) continue;
184
- const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback);
185
- if (value === void 0 || !Number.isFinite(value) || style[field] === value) continue;
186
- style = {
187
- ...style,
188
- [field]: value
189
- };
190
- }
191
- return style === run.style ? run : {
192
- ...run,
193
- style
194
- };
195
- });
196
- return styleRuns.some((run, index) => run !== node.styleRuns[index]) ? { styleRuns } : {};
197
- }
198
- /** The variables a node binds, its own and its characters'. */
199
- function boundVariableIds(node) {
200
- return [...Object.values(node.boundVariables), ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))].filter((id) => typeof id === "string");
201
- }
202
- /**
203
- * A bound paint takes its whole color from the variable, alpha included, the way Figma stores
204
- * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.
205
- */
206
- function applyBoundColor(paint, color) {
207
- paint.color = {
208
- ...color,
209
- a: 1
210
- };
211
- paint.opacity = color.a;
212
- }
213
- /** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */
214
- function resolvedPaintBindings(graph, node, fallback = "active") {
215
- const changes = {};
216
- for (const field in node.boundVariables) {
217
- if (!field.endsWith("/color")) continue;
218
- const match = /^(fills|strokes)\/(\d+)\/color$/.exec(field);
219
- if (!match) continue;
220
- const color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback);
221
- const index = Number(match[2]);
222
- if (!color) continue;
223
- if (match[1] === "fills") {
224
- if (!node.fills[index]) continue;
225
- changes.fills ??= copyFills(node.fills);
226
- applyBoundColor(changes.fills[index], color);
227
- } else {
228
- if (!node.strokes[index]) continue;
229
- changes.strokes ??= copyStrokes(node.strokes);
230
- applyBoundColor(changes.strokes[index], color);
231
- }
232
- }
233
- return changes;
234
- }
235
- /** These variables and every variable that aliases one of them, at any depth and in any mode. */
236
- function variablesResolvingThrough(graph, ids) {
237
- const found = new Set(ids);
238
- let grew = true;
239
- while (grew) {
240
- grew = false;
241
- for (const variable of graph.variables.values()) {
242
- if (found.has(variable.id)) continue;
243
- if (Object.values(variable.valuesByMode).some((value) => typeof value === "object" && "aliasId" in value && found.has(value.aliasId))) {
244
- found.add(variable.id);
245
- grew = true;
246
- }
247
- }
248
- }
249
- return found;
250
- }
251
- function subtreeNodes(graph, roots) {
252
- const nodes = [];
253
- const pending = [...roots];
254
- for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
255
- const node = graph.getNode(id);
256
- if (!node) continue;
257
- nodes.push(node);
258
- pending.push(...node.childIds);
259
- }
260
- return nodes;
261
- }
262
- /**
263
- * The collections whose variables the layers in these subtrees resolve: those they bind, and
264
- * those the bound variables alias, so a mode set on the subtrees can change what they show.
265
- */
266
- function collectionsBoundIn(graph, roots) {
267
- const pending = subtreeNodes(graph, roots).flatMap(boundVariableIds);
268
- const seen = /* @__PURE__ */ new Set();
269
- const collections = /* @__PURE__ */ new Set();
270
- for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
271
- if (seen.has(id)) continue;
272
- seen.add(id);
273
- const variable = graph.variables.get(id);
274
- if (!variable) continue;
275
- collections.add(variable.collectionId);
276
- for (const value of Object.values(variable.valuesByMode)) if (typeof value === "object" && "aliasId" in value) pending.push(value.aliasId);
277
- }
278
- return collections;
279
- }
280
- /**
281
- * The layers a change to these variables reaches: those binding one of them, or a variable that
282
- * aliases one, on the layer itself or on its characters.
283
- */
284
- function layersUsingVariables(graph, ids) {
285
- const variables = variablesResolvingThrough(graph, ids);
286
- return [...graph.getAllNodes()].filter((node) => boundVariableIds(node).some((id) => variables.has(id)));
287
- }
288
- function scopedNodes(graph, scope) {
289
- if (!scope) return graph.getAllNodes();
290
- if ("subtrees" in scope) return subtreeNodes(graph, scope.subtrees);
291
- return layersUsingVariables(graph, scope.variables);
292
- }
293
- /**
294
- * Resolve live numeric, text, and visibility bindings, numbers in scene units, without authoring
295
- * instance overrides. A scope limits it to the layers a change can reach, so layers whose saved
296
- * values differ from their bindings elsewhere in the document are left as saved.
297
- */
298
- function reconcileVariableBindings(graph, scope) {
299
- const changed = [];
300
- for (const node of scopedNodes(graph, scope)) {
301
- const updates = {
302
- ...resolvedNumericBindings(graph, node),
303
- ...resolvedValueBindings(graph, node),
304
- ...resolvedRunBindings(graph, node)
305
- };
306
- if (Object.keys(updates).length === 0) continue;
307
- graph.updateNode(node.id, updates);
308
- changed.push(node.id);
309
- }
310
- return changed;
311
- }
312
- //#endregion
313
- //#region src/variables.ts
314
- function addVariable(graph, variable) {
315
- graph.variables.set(variable.id, variable);
316
- const collection = graph.variableCollections.get(variable.collectionId);
317
- if (collection && !collection.variableIds.includes(variable.id)) collection.variableIds.push(variable.id);
318
- }
319
- function removeVariable(graph, id) {
320
- const variable = graph.variables.get(id);
321
- if (!variable) return;
322
- graph.variables.delete(id);
323
- const collection = graph.variableCollections.get(variable.collectionId);
324
- if (collection) collection.variableIds = collection.variableIds.filter((vid) => vid !== id);
325
- for (const node of graph.nodes.values()) {
326
- if (!Object.values(node.boundVariables).includes(id)) continue;
327
- graph.willChangeNode(node);
328
- node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id);
329
- node.variableBindingScales = omitBy(node.variableBindingScales, (_, field) => !(field in node.boundVariables));
330
- graph.emitter.emit("node:updated", node.id, {
331
- boundVariables: { ...node.boundVariables },
332
- variableBindingScales: { ...node.variableBindingScales }
333
- });
334
- markBoundVariablesOverrideOnInstance(graph, node.id);
335
- }
336
- }
337
- function addCollection(graph, collection) {
338
- graph.variableCollections.set(collection.id, collection);
339
- if (!graph.activeMode.has(collection.id)) graph.activeMode.set(collection.id, collection.defaultModeId);
340
- }
341
- function defaultVariableValue(type, value) {
342
- if (value !== void 0) return value;
343
- if (type === "COLOR") return { ...BLACK };
344
- if (type === "FLOAT") return 0;
345
- if (type === "BOOLEAN") return false;
346
- return "";
347
- }
348
- function createVariable(graph, generateId, name, type, collectionId, value) {
349
- const collection = graph.variableCollections.get(collectionId);
350
- if (!collection) throw new Error(`Collection "${collectionId}" not found`);
351
- const id = generateId();
352
- const defaultValue = defaultVariableValue(type, value);
353
- const valuesByMode = {};
354
- for (const mode of collection.modes) valuesByMode[mode.modeId] = structuredClone(defaultValue);
355
- const variable = {
356
- id,
357
- name,
358
- type,
359
- collectionId,
360
- valuesByMode,
361
- description: "",
362
- hiddenFromPublishing: false
363
- };
364
- addVariable(graph, variable);
365
- return variable;
366
- }
367
- function createCollection(graph, generateId, name) {
368
- const id = generateId();
369
- const modeId = generateId();
370
- const collection = {
371
- id,
372
- name,
373
- modes: [{
374
- modeId,
375
- name: "Mode 1"
376
- }],
377
- defaultModeId: modeId,
378
- variableIds: []
379
- };
380
- addCollection(graph, collection);
381
- return collection;
382
- }
383
- function removeCollection(graph, id) {
384
- const collection = graph.variableCollections.get(id);
385
- if (collection) for (const varId of Array.from(collection.variableIds)) removeVariable(graph, varId);
386
- graph.variableCollections.delete(id);
387
- graph.activeMode.delete(id);
388
- }
389
- function getActiveModeId(graph, collectionId) {
390
- const mode = graph.activeMode.get(collectionId);
391
- if (mode) return mode;
392
- return graph.variableCollections.get(collectionId)?.defaultModeId ?? "";
393
- }
394
- function getNodeVariableModeId(graph, nodeId, collectionId, fallback = "active") {
395
- let node = graph.nodes.get(nodeId);
396
- while (node) {
397
- const modeId = node.variableModes[collectionId];
398
- if (modeId) return modeId;
399
- node = node.parentId ? graph.nodes.get(node.parentId) : void 0;
400
- }
401
- if (fallback === "default") return graph.variableCollections.get(collectionId)?.defaultModeId ?? "";
402
- return getActiveModeId(graph, collectionId);
403
- }
404
- function setActiveMode(graph, collectionId, modeId) {
405
- graph.activeMode.set(collectionId, modeId);
406
- }
407
- function addMode(graph, collectionId, modeId, name, sourceMode) {
408
- const collection = graph.variableCollections.get(collectionId);
409
- if (!collection) return;
410
- collection.modes.push({
411
- modeId,
412
- name
413
- });
414
- const sourceModeId = sourceMode ?? collection.defaultModeId;
415
- for (const varId of collection.variableIds) {
416
- const variable = graph.variables.get(varId);
417
- if (!variable) continue;
418
- variable.valuesByMode[modeId] = structuredClone(variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]);
419
- }
420
- }
421
- /** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */
422
- function createMode(graph, generateId, collectionId, name, sourceMode) {
423
- if (!graph.variableCollections.has(collectionId)) return void 0;
424
- const modeId = generateId();
425
- addMode(graph, collectionId, modeId, name, sourceMode);
426
- return modeId;
427
- }
428
- function removeMode(graph, collectionId, modeId) {
429
- const collection = graph.variableCollections.get(collectionId);
430
- if (!collection || collection.modes.length <= 1) return;
431
- collection.modes = collection.modes.filter((m) => m.modeId !== modeId);
432
- if (collection.defaultModeId === modeId) collection.defaultModeId = collection.modes[0].modeId;
433
- for (const varId of collection.variableIds) {
434
- const variable = graph.variables.get(varId);
435
- if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId]);
436
- }
437
- if (graph.activeMode.get(collectionId) === modeId) graph.activeMode.set(collectionId, collection.defaultModeId);
438
- }
439
- function renameMode(graph, collectionId, modeId, name) {
440
- const collection = graph.variableCollections.get(collectionId);
441
- if (!collection) return;
442
- const mode = collection.modes.find((m) => m.modeId === modeId);
443
- if (mode) mode.name = name;
444
- }
445
- function setDefaultMode(graph, collectionId, modeId) {
446
- const collection = graph.variableCollections.get(collectionId);
447
- if (!collection) return;
448
- if (!collection.modes.some((m) => m.modeId === modeId)) return;
449
- collection.defaultModeId = modeId;
450
- collection.modes = modesDefaultFirst(collection);
451
- }
452
- /** Figma has no default-mode field: the first mode is the default. */
453
- function modesDefaultFirst(collection) {
454
- const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId);
455
- return [...defaults, ...rest];
456
- }
457
- function resolveVariable(graph, variableId, modeId, visited) {
458
- if (visited?.has(variableId)) return void 0;
459
- const variable = graph.variables.get(variableId);
460
- if (!variable) return void 0;
461
- const collection = graph.variableCollections.get(variable.collectionId);
462
- const preferredModeId = modeId ?? getActiveModeId(graph, variable.collectionId);
463
- const fallbackModeId = collection?.defaultModeId;
464
- let value = Object.hasOwn(variable.valuesByMode, preferredModeId) ? variable.valuesByMode[preferredModeId] : void 0;
465
- if (value === void 0 && fallbackModeId && Object.hasOwn(variable.valuesByMode, fallbackModeId)) value = variable.valuesByMode[fallbackModeId];
466
- value ??= Object.values(variable.valuesByMode)[0];
467
- if (value && typeof value === "object" && "aliasId" in value) {
468
- const seen = visited ?? /* @__PURE__ */ new Set();
469
- seen.add(variableId);
470
- return resolveVariable(graph, value.aliasId, preferredModeId, seen);
471
- }
472
- return value;
473
- }
474
- function resolveColorVariable(graph, variableId) {
475
- const value = resolveVariable(graph, variableId);
476
- if (value && typeof value === "object" && "r" in value) return value;
477
- }
478
- function resolveNumberVariable(graph, variableId) {
479
- const value = resolveVariable(graph, variableId);
480
- return typeof value === "number" ? value : void 0;
481
- }
482
- function resolveColorVariableForNode(graph, nodeId, variableId, fallback = "active") {
483
- const variable = graph.variables.get(variableId);
484
- if (!variable) return void 0;
485
- const value = resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback));
486
- if (value && typeof value === "object" && "r" in value) return value;
487
- }
488
- function resolveNumberVariableForNode(graph, nodeId, variableId, fallback = "active") {
489
- const variable = graph.variables.get(variableId);
490
- if (!variable) return void 0;
491
- const value = resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback));
492
- return typeof value === "number" ? value : void 0;
493
- }
494
- /** A variable's value in the mode a node is in, aliases followed. */
495
- function resolveVariableForNode(graph, nodeId, variableId, fallback = "active") {
496
- const variable = graph.variables.get(variableId);
497
- if (!variable) return void 0;
498
- return resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback));
499
- }
500
- function resolveStringVariableForNode(graph, nodeId, variableId, fallback = "active") {
501
- const value = resolveVariableForNode(graph, nodeId, variableId, fallback);
502
- return typeof value === "string" ? value : void 0;
503
- }
504
- function getVariablesForCollection(graph, collectionId) {
505
- const collection = graph.variableCollections.get(collectionId);
506
- if (!collection) return [];
507
- return collection.variableIds.map((id) => graph.variables.get(id)).filter((v) => v !== void 0);
508
- }
509
- function getVariablesByType(graph, type) {
510
- return [...graph.variables.values()].filter((v) => v.type === type);
511
- }
512
- function bindVariable(graph, nodeId, field, variableId) {
513
- const node = graph.nodes.get(nodeId);
514
- if (!node) return;
515
- const variable = graph.variables.get(variableId);
516
- if (!variable) throw new Error(`Variable "${variableId}" not found`);
517
- const colorFieldMatch = field.match(/^(fills|strokes)\/(\d+)\/color$/);
518
- if (colorFieldMatch) {
519
- if (variable.type !== "COLOR") throw new Error(`Cannot bind ${variable.type} variable to color field "${field}"`);
520
- const arrayKey = colorFieldMatch[1];
521
- const index = Number.parseInt(colorFieldMatch[2], 10);
522
- const currentLength = node[arrayKey]?.length ?? 0;
523
- if (index >= currentLength) throw new Error(`Index ${index} out of range for ${arrayKey} (length ${currentLength})`);
524
- const topLevelKey = colorFieldMatch[1];
525
- if (topLevelKey in node.boundVariables) node.boundVariables = omit(node.boundVariables, [topLevelKey]);
526
- }
527
- if (isNumericVariableBindingField(field) && variable.type !== "FLOAT") throw new Error(`Cannot bind ${variable.type} variable to scalar field "${field}"`);
528
- if (STRING_BINDING_FIELDS.has(field) && variable.type !== "STRING") throw new Error(`Cannot bind ${variable.type} variable to string field "${field}"`);
529
- if (BOOLEAN_BINDING_FIELDS.has(field) && variable.type !== "BOOLEAN") throw new Error(`Cannot bind ${variable.type} variable to boolean field "${field}"`);
530
- if (!(isNumericVariableBindingField(field) || STRING_BINDING_FIELDS.has(field) || BOOLEAN_BINDING_FIELDS.has(field) || colorFieldMatch)) throw new Error(`Unknown binding field "${field}"`);
531
- graph.willChangeNode(node);
532
- node.boundVariables = {
533
- ...node.boundVariables,
534
- [field]: variableId
535
- };
536
- assignVariableBindingUnits(graph, node, field);
537
- markBoundVariablesOverrideOnInstance(graph, nodeId, field);
538
- graph.emitter.emit("node:updated", nodeId, {
539
- boundVariables: { ...node.boundVariables },
540
- variableBindingScales: { ...node.variableBindingScales }
541
- });
542
- }
543
- function unbindVariable(graph, nodeId, field) {
544
- const node = graph.nodes.get(nodeId);
545
- if (!node) return;
546
- if (!(field in node.boundVariables)) return;
547
- graph.willChangeNode(node);
548
- node.boundVariables = omit(node.boundVariables, [field]);
549
- node.variableBindingScales = omit(node.variableBindingScales, [field]);
550
- markBoundVariablesOverrideOnInstance(graph, nodeId, field);
551
- graph.emitter.emit("node:updated", nodeId, {
552
- boundVariables: { ...node.boundVariables },
553
- variableBindingScales: { ...node.variableBindingScales }
554
- });
555
- }
556
- function markBoundVariablesOverrideOnInstance(graph, nodeId, field) {
557
- const node = graph.nodes.get(nodeId);
558
- if (!node) return;
559
- const owner = variableBindingOwner(graph, node);
560
- if (owner.type !== "INSTANCE") return;
561
- const nearest = findInstanceAncestor(graph, nodeId);
562
- if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, "boundVariables");
563
- setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, "boundVariables");
564
- if (field) setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, `boundVariables/${field}`, node.boundVariables[field] ?? null);
565
- }
566
- //#endregion
567
- //#region src/variables/token.ts
568
- /** `rem` tokens are stored in canvas pixels and shown against this root font size. */
569
- const ROOT_FONT_SIZE_PX = 16;
570
- /** The stored number for a value typed in a unit: `1.5` in `rem` is 24 canvas pixels. */
571
- function tokenNumberFromUnit(value, unit) {
572
- return unit === "rem" ? value * 16 : value;
573
- }
574
- /** A stored number as it reads in its unit: 24 canvas pixels in `rem` is `1.5`. */
575
- function tokenNumberInUnit(value, unit) {
576
- return unit === "rem" ? value / 16 : value;
577
- }
578
- //#endregion
579
- //#region src/scaling/tree.ts
580
- const MIN_SCALE = .01;
581
- const RESCALABLE_NODE_TYPES = /* @__PURE__ */ new Set([
582
- "BOOLEAN_OPERATION",
583
- "COMPONENT",
584
- "COMPONENT_SET",
585
- "ELLIPSE",
586
- "FRAME",
587
- "GROUP",
588
- "INSTANCE",
589
- "LINE",
590
- "POLYGON",
591
- "RECTANGLE",
592
- "STAR",
593
- "TEXT",
594
- "VECTOR"
595
- ]);
596
- /** Scale a node tree from the root node's top-left, matching Figma's Scale tool. */
597
- function rescaleNodeTree(graph, rootId, scale) {
598
- if (!Number.isFinite(scale)) throw new TypeError("Scale must be a finite number");
599
- if (scale < MIN_SCALE) throw new RangeError(`Scale must be at least ${MIN_SCALE}`);
600
- const root = graph.getNode(rootId);
601
- if (!root || !RESCALABLE_NODE_TYPES.has(root.type)) throw new Error("rescale() is not supported on this node");
602
- const nodes = [root];
603
- const collect = (node) => {
604
- for (const childId of node.childIds) {
605
- const child = graph.getNode(childId);
606
- if (!child) continue;
607
- nodes.push(child);
608
- collect(child);
609
- }
610
- };
611
- collect(root);
612
- for (const node of nodes) graph.updateNode(node.id, {
613
- ...scaleNodeChanges(node, scale, node.id !== rootId),
614
- ...scaleVariableBindingUnits(node, scale),
615
- componentScale: findInstanceAncestor(graph, node.id) ? node.componentScale * scale : node.componentScale
616
- });
617
- }
618
- //#endregion
619
- //#region src/text/references.ts
620
- /** The variables and styles a text's runs refer to, which copies and transfers carry with it. */
621
- function styleRunReferences(runs) {
622
- const variables = /* @__PURE__ */ new Set();
623
- const styles = /* @__PURE__ */ new Set();
624
- for (const { style } of runs) {
625
- for (const id of Object.values(style.boundVariables ?? {})) if (id) variables.add(id);
626
- if (style.textStyleId) styles.add(style.textStyleId);
627
- if (style.fillStyleId) styles.add(style.fillStyleId);
628
- }
629
- return {
630
- variables: [...variables],
631
- styles: [...styles]
632
- };
633
- }
634
- /**
635
- * Runs whose variables, styles, and linked layers are renamed, as a copy into another document
636
- * renames them. Layers are renamed only when given, since a link may name a layer left behind.
637
- */
638
- function remapStyleRunReferences(runs, rename) {
639
- return runs.map((run) => {
640
- const { boundVariables, textStyleId, fillStyleId, hyperlink } = run.style;
641
- const linksLayer = hyperlink?.type === "NODE" && rename.node !== void 0;
642
- if (!boundVariables && !textStyleId && !fillStyleId && !linksLayer) return run;
643
- const style = { ...run.style };
644
- if (hyperlink?.type === "NODE" && rename.node) style.hyperlink = {
645
- type: "NODE",
646
- value: rename.node(hyperlink.value)
647
- };
648
- if (boundVariables) style.boundVariables = mapValues(boundVariables, (id) => id ? rename.variable(id) : id);
649
- if (textStyleId) style.textStyleId = rename.style(textStyleId);
650
- if (fillStyleId) style.fillStyleId = rename.style(fillStyleId);
651
- return {
652
- ...run,
653
- style
654
- };
655
- });
656
- }
657
- //#endregion
658
- //#region src/transfer/references.ts
659
- function requireTransferReference(ids, id, kind) {
660
- const value = ids.get(id);
661
- if (!value) throw new Error(`Missing ${kind} transfer mapping: ${id}`);
662
- return value;
663
- }
664
- //#endregion
665
- //#region src/transfer/nodes.ts
666
- function semanticTransferReferences(node) {
667
- const runs = styleRunReferences(node.styleRuns);
668
- return [
669
- ...node.componentId ? [node.componentId] : [],
670
- ...Object.values(node.boundVariables),
671
- ...runs.variables,
672
- ...runs.styles,
673
- ...[
674
- node.fillStyleId,
675
- node.strokeStyleId,
676
- node.textStyleId,
677
- node.effectStyleId,
678
- node.gridStyleId
679
- ].filter((id) => !!id),
680
- ...node.fillGeometry.flatMap((path) => path.fillStyleId ? [path.fillStyleId] : []),
681
- ...node.strokeGeometry.flatMap((path) => path.fillStyleId ? [path.fillStyleId] : []),
682
- ...Object.entries(node.componentPropertyAssignments).flatMap(([id, value]) => [id, value]),
683
- ...node.componentPropertyReferences.map((reference) => reference.propertyId),
684
- ...node.componentPropertyDefinitions.flatMap((definition) => [definition.id, ...definition.type === "INSTANCE_SWAP" && definition.defaultValue ? [definition.defaultValue] : []]),
685
- ...node.instanceOverrides.descendants.keys(),
686
- ...[...node.instanceOverrides.self, ...[...node.instanceOverrides.descendants.values()].flatMap((fields) => [...fields])].flatMap(([field, value]) => typeof value === "string" && (field === "componentId" || field === "sourceComponentId" || field.startsWith("boundVariables/")) ? [value] : [])
687
- ];
688
- }
689
- /** Prepare runtime references without rewriting original format identities or ordinary text. */
690
- function prepareNodeTransfer(source, refs) {
691
- const node = (id) => requireTransferReference(refs.nodes, id, "node");
692
- const variable = (id) => requireTransferReference(refs.variables, id, "variable");
693
- const property = (id) => requireTransferReference(refs.properties, id, "property");
694
- const style = (id) => requireTransferReference(refs.styles, id, "style");
695
- const propertyValue = (id, value) => {
696
- const type = refs.propertyTypes.get(id);
697
- if (!type) throw new Error(`Missing property transfer type: ${id}`);
698
- return type === "INSTANCE_SWAP" && value ? node(value) : value;
699
- };
700
- const values = (entries) => Object.fromEntries(Object.entries(entries).map(([id, value]) => [property(id), propertyValue(id, value)]));
701
- const result = cloneNodeProps(source, null);
702
- result.componentId = source.componentId ? node(source.componentId) : null;
703
- result.instanceOverrides = remapInstanceOverrideState(source.instanceOverrides, {
704
- node,
705
- variable
706
- });
707
- result.boundVariables = Object.fromEntries(Object.entries(source.boundVariables).map(([field, id]) => [field, variable(id)]));
708
- result.variableModes = Object.fromEntries(Object.entries(source.variableModes).map(([collection, mode]) => [requireTransferReference(refs.collections, collection, "collection"), requireTransferReference(refs.modes, mode, "mode")]));
709
- for (const field of [
710
- "fillStyleId",
711
- "strokeStyleId",
712
- "textStyleId",
713
- "effectStyleId",
714
- "gridStyleId"
715
- ]) result[field] = source[field] ? style(source[field]) : null;
716
- if (result.styleRuns) result.styleRuns = remapStyleRunReferences(result.styleRuns, {
717
- variable,
718
- style,
719
- node: (id) => refs.nodes.get(id) ?? id
720
- });
721
- for (const paths of [result.fillGeometry, result.strokeGeometry]) for (const path of paths ?? []) if (path.fillStyleId) path.fillStyleId = style(path.fillStyleId);
722
- result.componentPropertyDefinitions = source.componentPropertyDefinitions.map((definition) => ({
723
- ...structuredClone(definition),
724
- id: property(definition.id),
725
- defaultValue: propertyValue(definition.id, definition.defaultValue)
726
- }));
727
- result.componentPropertyReferences = source.componentPropertyReferences.map((reference) => ({
728
- ...reference,
729
- propertyId: property(reference.propertyId)
730
- }));
731
- result.componentPropertyAssignments = values(source.componentPropertyAssignments);
732
- result.componentPropertyValues = { ...source.componentPropertyValues };
733
- return result;
734
- }
735
- //#endregion
736
- //#region src/transfer/remove.ts
737
- /** Refuse to remove transferred content that has acquired external dependents. */
738
- function removeGraphTransfer(graph, plan) {
739
- const nodes = new Set(plan.nodes.map((node) => node.id));
740
- const variables = new Set(plan.variables.map((variable) => variable.id));
741
- const collections = new Set(plan.collections.map((collection) => collection.id));
742
- const referencesOwned = (value) => {
743
- if (typeof value === "string") return nodes.has(value) || variables.has(value) || collections.has(value);
744
- if (!value || typeof value !== "object" || ArrayBuffer.isView(value)) return false;
745
- if (value instanceof Map) return [...value].some(([key, item]) => referencesOwned(key) || referencesOwned(item));
746
- return Object.values(value).some(referencesOwned);
747
- };
748
- for (const node of graph.getAllNodes()) {
749
- if (nodes.has(node.id)) {
750
- if (node.childIds.some((id) => !nodes.has(id))) throw new Error("Transferred node has non-owned children");
751
- continue;
752
- }
753
- if (semanticTransferReferences(node).some(referencesOwned)) throw new Error(`Transferred content is referenced by ${node.id}`);
754
- }
755
- for (const variable of graph.variables.values()) if (!variables.has(variable.id) && referencesOwned(variable.valuesByMode)) throw new Error("Transferred variable has external aliases");
756
- graph.withBufferedEvents(() => {
757
- for (const node of plan.nodes.toReversed()) graph.deleteNode(node.id);
758
- for (const id of variables) graph.variables.delete(id);
759
- for (const id of collections) {
760
- graph.variableCollections.delete(id);
761
- graph.activeMode.delete(id);
762
- }
763
- });
764
- }
765
- //#endregion
766
- //#region src/transfer/history.ts
767
- /** Capture post-placement state for redo; this does not authorize deleting shared resources. */
768
- function captureTransferredState(graph, original) {
769
- const requireValue = (value, kind, id) => {
770
- if (value === void 0) throw new Error(`Missing transferred ${kind} ${id}`);
771
- return value;
772
- };
773
- return {
774
- nodeIds: new Map(original.nodeIds),
775
- rootIds: [...original.rootIds],
776
- dependencyPageIds: [...original.dependencyPageIds],
777
- nodes: original.nodes.map((entry) => {
778
- const node = requireValue(graph.getNode(entry.id), "node", entry.id);
779
- if (!node.parentId) throw new Error(`Missing transferred parent ${entry.id}`);
780
- return {
781
- id: node.id,
782
- type: node.type,
783
- parentId: node.parentId,
784
- props: cloneNodeProps(node, null)
785
- };
786
- }),
787
- variables: original.variables.map((variable) => structuredClone(requireValue(graph.variables.get(variable.id), "variable", variable.id))),
788
- collections: original.collections.map((collection) => structuredClone(requireValue(graph.variableCollections.get(collection.id), "collection", collection.id))),
789
- activeModes: new Map(original.collections.map((collection) => [collection.id, requireValue(graph.activeMode.get(collection.id), "active mode", collection.id)])),
790
- images: new Map([...original.images.keys()].map((hash) => [hash, requireValue(graph.images.get(hash), "image", hash).slice()]))
791
- };
792
- }
793
- //#endregion
794
- //#region src/transfer/identity.ts
795
- function variableIdentityReferences(variables, collections) {
796
- return {
797
- variables: new Map(variables.map((variable) => [variable.id, variable.id])),
798
- collections: new Map(collections.map((collection) => [collection.id, collection.id])),
799
- modes: new Map(collections.flatMap((collection) => collection.modes.map((mode) => [mode.modeId, mode.modeId])))
800
- };
801
- }
802
- //#endregion
803
- //#region src/transfer/validation.ts
804
- /** Revalidate mutable plan references without allocating or registering destination nodes. */
805
- function validateTransferReferences(target, plan) {
806
- const nodes = new Map(plan.nodes.map((entry) => [entry.id, createDefaultNode(() => entry.id, entry.type, entry.props)]));
807
- const identities = new Map([...nodes.keys()].map((id) => [id, id]));
808
- const properties = /* @__PURE__ */ new Map();
809
- const propertyTypes = /* @__PURE__ */ new Map();
810
- for (const node of nodes.values()) for (const definition of node.componentPropertyDefinitions) {
811
- const previous = propertyTypes.get(definition.id);
812
- if (previous && previous !== definition.type) throw new Error(`Conflicting transfer property ${definition.id}`);
813
- properties.set(definition.id, definition.id);
814
- propertyTypes.set(definition.id, definition.type);
815
- }
816
- const collections = new Map(plan.collections.map((collection) => [collection.id, collection]));
817
- const references = {
818
- nodes: identities,
819
- styles: new Map([...nodes.values()].flatMap((node) => node.sharedStyleType !== null && node.source.id ? [[node.source.id, node.source.id]] : [])),
820
- properties,
821
- propertyTypes,
822
- ...variableIdentityReferences(plan.variables, plan.collections)
823
- };
824
- for (const node of nodes.values()) {
825
- prepareNodeTransfer(node, references);
826
- for (const [collection, mode] of Object.entries(node.variableModes)) if (!collections.get(collection)?.modes.some((entry) => entry.modeId === mode)) throw new Error(`Invalid node variable mode ${node.id}`);
827
- }
828
- const roots = /* @__PURE__ */ new Set([...plan.rootIds, ...plan.dependencyPageIds]);
829
- if (roots.size !== plan.rootIds.length + plan.dependencyPageIds.length) throw new Error("Repeated transfer root");
830
- for (const entry of plan.nodes) {
831
- if (roots.has(entry.id) === nodes.has(entry.parentId)) throw new Error(`Invalid transfer root topology ${entry.id}`);
832
- if (plan.dependencyPageIds.includes(entry.id) && (entry.type !== "CANVAS" || !entry.props.internalOnly || entry.parentId !== target.rootId)) throw new Error(`Invalid transfer dependency page ${entry.id}`);
833
- }
834
- }
835
- //#endregion
836
- //#region src/transfer/variables.ts
837
- function assertUniqueMappings(ids, kind) {
838
- if (new Set(ids.values()).size !== ids.size) throw new Error(`Colliding ${kind} transfer mappings`);
839
- }
840
- function assertResourceOwnership(variables, collections) {
841
- const sets = new Map(collections.map((collection) => [collection.id, collection]));
842
- const tokens = new Map(variables.map((variable) => [variable.id, variable]));
843
- if (sets.size !== collections.length || tokens.size !== variables.length) throw new Error("Duplicate source variable resource");
844
- for (const collection of collections) {
845
- const modes = new Set(collection.modes.map((mode) => mode.modeId));
846
- if (!modes.has(collection.defaultModeId) || modes.size !== collection.modes.length) throw new Error(`Invalid modes for collection ${collection.id}`);
847
- for (const id of collection.variableIds) if (tokens.get(id)?.collectionId !== collection.id) throw new Error(`Invalid variable membership ${id} in ${collection.id}`);
848
- }
849
- for (const variable of variables) {
850
- const collection = sets.get(variable.collectionId);
851
- if (!collection?.variableIds.includes(variable.id)) throw new Error(`Missing collection membership for ${variable.id}`);
852
- const modes = new Set(collection.modes.map((mode) => mode.modeId));
853
- for (const mode of Object.keys(variable.valuesByMode)) if (!modes.has(mode)) throw new Error(`Unknown mode ${mode} for ${variable.id}`);
854
- }
855
- }
856
- /** Prepare isolated resource copies; never mutate the source or destination graph. */
857
- function prepareVariableTransfer(variables, collections, references) {
858
- assertResourceOwnership(variables, collections);
859
- assertUniqueMappings(references.variables, "variable");
860
- assertUniqueMappings(references.collections, "collection");
861
- assertUniqueMappings(references.modes, "mode");
862
- const value = (input) => {
863
- if (typeof input === "object" && "aliasId" in input) return { aliasId: requireTransferReference(references.variables, input.aliasId, "variable alias") };
864
- return structuredClone(input);
865
- };
866
- return {
867
- collections: collections.map((collection) => ({
868
- ...structuredClone(collection),
869
- id: requireTransferReference(references.collections, collection.id, "collection"),
870
- defaultModeId: requireTransferReference(references.modes, collection.defaultModeId, "mode"),
871
- modes: collection.modes.map((mode) => ({
872
- ...mode,
873
- modeId: requireTransferReference(references.modes, mode.modeId, "mode")
874
- })),
875
- variableIds: collection.variableIds.map((id) => requireTransferReference(references.variables, id, "variable"))
876
- })),
877
- variables: variables.map((variable) => ({
878
- ...structuredClone(variable),
879
- id: requireTransferReference(references.variables, variable.id, "variable"),
880
- collectionId: requireTransferReference(references.collections, variable.collectionId, "collection"),
881
- valuesByMode: Object.fromEntries(Object.entries(variable.valuesByMode).map(([mode, input]) => [requireTransferReference(references.modes, mode, "mode"), value(input)]))
882
- }))
883
- };
884
- }
885
- //#endregion
886
- //#region src/transfer/apply.ts
887
- function validate(target, plan) {
888
- validateTransferReferences(target, plan);
889
- const reserved = /* @__PURE__ */ new Set([
890
- ...target.nodes.keys(),
891
- ...target.variables.keys(),
892
- ...target.variableCollections.keys()
893
- ]);
894
- const claim = (id) => {
895
- if (reserved.has(id)) throw new Error(`Transfer identity collision ${id}`);
896
- reserved.add(id);
897
- };
898
- prepareVariableTransfer(plan.variables, plan.collections, variableIdentityReferences(plan.variables, plan.collections));
899
- for (const [id, mode] of plan.activeModes) if (!plan.collections.find((collection) => collection.id === id)?.modes.some((entry) => entry.modeId === mode)) throw new Error(`Invalid transferred active mode ${id}:${mode}`);
900
- for (const collection of plan.collections) claim(collection.id);
901
- for (const variable of plan.variables) claim(variable.id);
902
- const parents = new Set(target.nodes.keys());
903
- for (const node of plan.nodes) {
904
- claim(node.id);
905
- if ("id" in node.props || "parentId" in node.props || "childIds" in node.props) throw new Error("Transfer props cannot override hierarchy identity");
906
- if (!parents.has(node.parentId)) throw new Error(`Missing transfer parent ${node.parentId}`);
907
- parents.add(node.id);
908
- }
909
- for (const id of [...plan.rootIds, ...plan.dependencyPageIds]) if (!plan.nodes.some((node) => node.id === id)) throw new Error(`Missing transfer root ${id}`);
910
- for (const node of plan.nodes) if (node.props.componentId && !parents.has(node.props.componentId)) throw new Error(`Missing transfer component ${node.props.componentId}`);
911
- for (const [hash, bytes] of plan.images) {
912
- const existing = target.images.get(hash);
913
- if (existing && !isEqual(existing, bytes)) throw new Error(`Transfer image collision ${hash}`);
914
- }
915
- }
916
- /** Revalidate at insertion time. Event-delivery failures after commit are not rollback failures. */
917
- function applyGraphTransfer(target, input) {
918
- const plan = structuredClone(input);
919
- validate(target, plan);
920
- const imageIds = [...plan.images.keys()].filter((hash) => !target.images.has(hash));
921
- target.withBufferedEvents(() => {
922
- try {
923
- for (const collection of plan.collections) target.addCollection(collection);
924
- for (const variable of plan.variables) target.addVariable(variable);
925
- for (const [id, mode] of plan.activeModes) target.activeMode.set(id, mode);
926
- for (const [hash, bytes] of plan.images) if (!target.images.has(hash)) target.images.set(hash, bytes);
927
- for (const node of plan.nodes) target.createNodeWithId(node.id, node.type, node.parentId, {
928
- ...node.props,
929
- childIds: []
930
- });
931
- } catch (error) {
932
- for (const node of plan.nodes.toReversed()) if (target.getNode(node.id)) target.deleteNode(node.id);
933
- for (const variable of plan.variables) target.variables.delete(variable.id);
934
- for (const collection of plan.collections) {
935
- target.variableCollections.delete(collection.id);
936
- target.activeMode.delete(collection.id);
937
- }
938
- for (const hash of imageIds) target.images.delete(hash);
939
- throw error;
940
- }
941
- });
942
- }
943
- //#endregion
944
- //#region src/transfer/plan.ts
945
- /** A transferred style's props under the ID the transfer gives it. */
946
- function withStyleId(node, props, styles) {
947
- const id = node.sharedStyleType !== null && node.source.id ? styles.get(node.source.id) : void 0;
948
- if (!id || id === node.source.id) return props;
949
- return {
950
- ...props,
951
- source: {
952
- ...props.source ?? node.source,
953
- id
954
- }
955
- };
956
- }
957
- /** Preflight a self-contained fragment; allocation does not insert anything into the target. */
958
- function prepareGraphTransfer(input) {
959
- const { source, target, parentId } = input;
960
- if (!target.getNode(parentId)) throw new Error(`Missing transfer parent ${parentId}`);
961
- const reserved = /* @__PURE__ */ new Set([
962
- ...target.nodes.keys(),
963
- ...target.variables.keys(),
964
- ...target.variableCollections.keys()
965
- ]);
966
- for (const collection of target.variableCollections.values()) for (const mode of collection.modes) reserved.add(mode.modeId);
967
- let sequence = 0;
968
- const namespace = crypto.randomUUID();
969
- const allocate = () => {
970
- let id = `${namespace}:${sequence++}`;
971
- while (reserved.has(id)) id = `${namespace}:${sequence++}`;
972
- reserved.add(id);
973
- return id;
974
- };
975
- const ordered = [];
976
- const seen = /* @__PURE__ */ new Set();
977
- const visit = (id) => {
978
- if (seen.has(id)) throw new Error(`Repeated transfer node ${id}`);
979
- const node = source.getNode(id);
980
- if (!node) throw new Error(`Missing transfer source ${id}`);
981
- seen.add(id);
982
- ordered.push(node);
983
- for (const child of node.childIds) visit(child);
984
- };
985
- for (const id of [...input.dependencyPageIds, ...input.rootIds]) visit(id);
986
- const nodes = new Map(ordered.map((node) => [node.id, allocate()]));
987
- const variables = new Map([...source.variables.keys()].map((id) => [id, allocate()]));
988
- const collections = new Map([...source.variableCollections.keys()].map((id) => [id, allocate()]));
989
- const modes = /* @__PURE__ */ new Map();
990
- for (const collection of source.variableCollections.values()) for (const mode of collection.modes) if (!modes.has(mode.modeId)) modes.set(mode.modeId, allocate());
991
- const properties = /* @__PURE__ */ new Map();
992
- const propertyTypes = /* @__PURE__ */ new Map();
993
- for (const node of ordered) for (const definition of node.componentPropertyDefinitions) {
994
- if (propertyTypes.has(definition.id) && propertyTypes.get(definition.id) !== definition.type) throw new Error(`Conflicting property type ${definition.id}`);
995
- propertyTypes.set(definition.id, definition.type);
996
- if (!properties.has(definition.id)) properties.set(definition.id, allocate());
997
- }
998
- const targetStyleIds = /* @__PURE__ */ new Set();
999
- for (const node of target.getAllNodes()) if (node.sharedStyleType !== null && node.source.id) targetStyleIds.add(node.source.id);
1000
- const styles = /* @__PURE__ */ new Map();
1001
- for (const node of ordered) {
1002
- const id = node.source.id;
1003
- if (node.sharedStyleType === null || !id) continue;
1004
- styles.set(id, targetStyleIds.has(id) ? allocate() : id);
1005
- }
1006
- const references = {
1007
- nodes,
1008
- variables,
1009
- collections,
1010
- modes,
1011
- properties,
1012
- propertyTypes,
1013
- styles
1014
- };
1015
- const resources = prepareVariableTransfer([...source.variables.values()], [...source.variableCollections.values()], references);
1016
- const mapped = (id) => {
1017
- const value = nodes.get(id);
1018
- if (!value) throw new Error(`Missing transfer node mapping ${id}`);
1019
- return value;
1020
- };
1021
- const roots = new Set(input.rootIds);
1022
- const dependencies = new Set(input.dependencyPageIds);
1023
- const destinationParent = (node) => {
1024
- if (roots.has(node.id)) return parentId;
1025
- if (dependencies.has(node.id)) return target.rootId;
1026
- return mapped(node.parentId ?? "");
1027
- };
1028
- return {
1029
- nodeIds: nodes,
1030
- rootIds: input.rootIds.map(mapped),
1031
- dependencyPageIds: input.dependencyPageIds.map(mapped),
1032
- nodes: ordered.map((node) => ({
1033
- id: mapped(node.id),
1034
- type: node.type,
1035
- parentId: destinationParent(node),
1036
- props: withStyleId(node, prepareNodeTransfer(node, references), styles)
1037
- })),
1038
- ...resources,
1039
- activeModes: new Map([...source.activeMode].map(([collection, mode]) => [requireTransferReference(collections, collection, "collection"), requireTransferReference(modes, mode, "mode")])),
1040
- images: new Map([...source.images].map(([hash, bytes]) => [hash, bytes.slice()]))
1041
- };
1042
- }
1043
- //#endregion
1044
- //#region src/slots/content.ts
1045
- function parentOf(graph, node) {
1046
- return node.parentId ? graph.nodes.get(node.parentId) : void 0;
1047
- }
1048
- function nearestInstance(graph, node) {
1049
- let current = parentOf(graph, node);
1050
- while (current && current.type !== "INSTANCE") current = parentOf(graph, current);
1051
- return current;
1052
- }
1053
- function slotScope(graph, parentId) {
1054
- let current = graph.nodes.get(parentId);
1055
- while (current) {
1056
- const propertyId = slotPropertyId(current);
1057
- if (propertyId) {
1058
- const instance = nearestInstance(graph, current);
1059
- return instance ? {
1060
- kind: "slot",
1061
- frame: current,
1062
- instance,
1063
- propertyId
1064
- } : { kind: "free" };
1065
- }
1066
- if (current.type === "INSTANCE") return {
1067
- kind: "locked",
1068
- instance: current
1069
- };
1070
- current = parentOf(graph, current);
1071
- }
1072
- return { kind: "free" };
1073
- }
1074
- /** Every layer below `node`; `enterInstances` also walks the layers of nested instances. */
1075
- function descendants(graph, node, enterInstances) {
1076
- const result = [];
1077
- const visit = (parent) => {
1078
- for (const childId of parent.childIds) {
1079
- const child = graph.nodes.get(childId);
1080
- if (!child) continue;
1081
- result.push(child);
1082
- if (enterInstances || child.type !== "INSTANCE") visit(child);
1083
- }
1084
- };
1085
- visit(node);
1086
- return result;
1087
- }
1088
- /**
1089
- * Make the instance own its slot's content, as Figma does on the first edit: the layers
1090
- * stay where they are, but stop following the component. Overrides the instance held for
1091
- * them become their own values, or move to the nested instance they belong to.
1092
- */
1093
- function claimSlotContent(graph, scope) {
1094
- const { frame, instance, propertyId } = scope;
1095
- if (ownsSlotContent(graph, frame, propertyId)) return;
1096
- const overrides = instance.instanceOverrides;
1097
- for (const node of descendants(graph, frame, false)) {
1098
- overrides.descendants.delete(node.id);
1099
- if (node.type !== "INSTANCE") {
1100
- graph.updateNode(node.id, { componentId: null });
1101
- continue;
1102
- }
1103
- for (const inner of descendants(graph, node, true)) {
1104
- const fields = overrides.descendants.get(inner.id);
1105
- if (!fields) continue;
1106
- for (const [field, value] of fields) if (field !== "sourceComponentId") setInstanceOverride(node.instanceOverrides, node.id, inner.id, field, value);
1107
- overrides.descendants.delete(inner.id);
1108
- }
1109
- graph.updateNode(node.id, { instanceOverrides: node.instanceOverrides });
1110
- }
1111
- graph.updateNode(instance.id, {
1112
- instanceOverrides: overrides,
1113
- componentPropertyAssignments: {
1114
- ...instance.componentPropertyAssignments,
1115
- [propertyId]: ""
1116
- }
1117
- });
1118
- }
1119
- /** The component layer an instance layer was cloned from. */
1120
- function componentSource(instance, node) {
1121
- const mapped = getInstanceOverride(instance.instanceOverrides, instance.id, node.id, "sourceComponentId");
1122
- return typeof mapped === "string" ? mapped : node.componentId;
1123
- }
1124
- /** Return the slot to its component's content: the instance stops owning it. */
1125
- function resetSlotContent(graph, scope) {
1126
- const { frame, instance, propertyId } = scope;
1127
- for (const childId of Array.from(frame.childIds)) graph.deleteNode(childId);
1128
- const assignments = { ...instance.componentPropertyAssignments };
1129
- Reflect.deleteProperty(assignments, propertyId);
1130
- graph.updateNode(instance.id, { componentPropertyAssignments: assignments });
1131
- const source = componentSource(instance, frame);
1132
- if (source && graph.nodes.has(source)) cloneChildrenWithMapping(graph, source, frame.id);
1133
- }
1134
- /** Remove everything from the slot; the instance keeps owning it, now empty. */
1135
- function clearSlotContent(graph, scope) {
1136
- claimSlotContent(graph, scope);
1137
- for (const childId of Array.from(scope.frame.childIds)) graph.deleteNode(childId);
1138
- }
1139
- //#endregion
1140
- //#region src/slots/authoring.ts
1141
- /** The settings a new slot starts with: no limits, any layer allowed. */
1142
- const DEFAULT_SLOT_SETTINGS = {
1143
- allowPreferredValuesOnly: false,
1144
- displayEmptyByDefault: false,
1145
- stretchChildOnInsert: false
1146
- };
1147
- /**
1148
- * The main component a layer belongs to, which defines the slots inside it. Layers of an
1149
- * instance are not authored there, so a layer under an instance has none.
1150
- */
1151
- function slotOwner(graph, node) {
1152
- let current = node.parentId ? graph.getNode(node.parentId) : void 0;
1153
- while (current && current.type !== "CANVAS") {
1154
- if (current.type === "COMPONENT") return current;
1155
- if (current.type === "INSTANCE") return void 0;
1156
- current = current.parentId ? graph.getNode(current.parentId) : void 0;
1157
- }
1158
- }
1159
- /** Whether a frame inside a main component can become a slot. */
1160
- function canCreateSlot(graph, node) {
1161
- return node.type === "FRAME" && !slotPropertyId(node) && !!slotOwner(graph, node);
1162
- }
1163
- function uniqueSlotName(owner, base) {
1164
- const taken = new Set(owner.componentPropertyDefinitions.map((definition) => definition.name));
1165
- if (!taken.has(base)) return base;
1166
- let index = 2;
1167
- while (taken.has(`${base} ${index}`)) index++;
1168
- return `${base} ${index}`;
1169
- }
1170
- /**
1171
- * Make a frame of a main component a slot: define a SLOT property, named after the frame, on
1172
- * the component and bind the frame's children to it. Instances pick up the slot on their next
1173
- * sync.
1174
- */
1175
- function createSlotProperty(graph, frameId, id) {
1176
- const frame = graph.getNode(frameId);
1177
- const owner = frame && canCreateSlot(graph, frame) ? slotOwner(graph, frame) : void 0;
1178
- if (!frame || !owner) return null;
1179
- const definition = {
1180
- id,
1181
- name: uniqueSlotName(owner, frame.name.trim() || "Slot"),
1182
- type: "SLOT",
1183
- defaultValue: "",
1184
- preferredValues: [],
1185
- slotSettings: { ...DEFAULT_SLOT_SETTINGS }
1186
- };
1187
- graph.updateNode(owner.id, { componentPropertyDefinitions: [...owner.componentPropertyDefinitions, definition] });
1188
- graph.updateNode(frame.id, { componentPropertyReferences: [...frame.componentPropertyReferences, {
1189
- propertyId: id,
1190
- field: "SLOT_CONTENT"
1191
- }] });
1192
- return definition;
1193
- }
1194
- /** Change a slot property's name, description, preferred components, or limits. */
1195
- function updateSlotProperty(graph, ownerId, propertyId, patch) {
1196
- const owner = graph.getNode(ownerId);
1197
- const current = owner?.componentPropertyDefinitions.find((definition) => definition.id === propertyId && definition.type === "SLOT");
1198
- if (!owner || !current) return false;
1199
- const { slotSettings, ...fields } = patch;
1200
- const next = {
1201
- ...current,
1202
- ...fields,
1203
- slotSettings: {
1204
- ...DEFAULT_SLOT_SETTINGS,
1205
- ...current.slotSettings,
1206
- ...slotSettings
1207
- }
1208
- };
1209
- graph.updateNode(owner.id, { componentPropertyDefinitions: owner.componentPropertyDefinitions.map((definition) => definition.id === propertyId ? next : definition) });
1210
- return true;
1211
- }
1212
- //#endregion
1213
- //#region src/slots/limits.ts
1214
- /** Whether a component is among a slot's preferred values, by id, key, or library key. */
1215
- function isPreferredComponent(component, preferredValues = []) {
1216
- if (!component) return false;
1217
- return [
1218
- component.id,
1219
- component.componentKey,
1220
- component.sourceLibraryKey
1221
- ].some((value) => !!value && preferredValues.includes(value));
1222
- }
1223
- /** Content layers a preferred-only slot does not allow: anything but preferred instances. */
1224
- function nonPreferredLayers(graph, definition, content) {
1225
- if (!definition.slotSettings?.allowPreferredValuesOnly) return [];
1226
- return content.filter((node) => node.type !== "INSTANCE" || !isPreferredComponent(node.componentId ? graph.getNode(node.componentId) : void 0, definition.preferredValues));
1227
- }
1228
- /** The limits a slot's content breaks; below-minimum and above-maximum exclude each other. */
1229
- function slotLimitViolations(graph, definition, content) {
1230
- const settings = definition.slotSettings;
1231
- const violations = [];
1232
- if (settings?.minChildren !== void 0 && content.length < settings.minChildren) violations.push("BELOW_MIN");
1233
- else if (settings?.maxChildren !== void 0 && content.length > settings.maxChildren) violations.push("ABOVE_MAX");
1234
- if (nonPreferredLayers(graph, definition, content).length) violations.push("HAS_NON_PREFERRED");
1235
- return violations;
1236
- }
1237
- //#endregion
1238
- //#region src/shaders/model.ts
1239
- /** Every shader a node's fills and strokes draw, whether or not a paint still shows it. */
1240
- function readShaderPaints(node) {
1241
- return readAllPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.shader);
1242
- }
1243
- /**
1244
- * The shader a fill or stroke of `node` draws: an image paint whose image is a shader's frame.
1245
- * Null for any other paint, including one whose image was replaced, which then draws as the
1246
- * image it holds.
1247
- */
1248
- function shaderOfPaint(node, paint) {
1249
- if (paint.type !== "IMAGE" || !paint.imageHash) return null;
1250
- return readShaderPaints(node).find((shader) => shader.image === paint.imageHash) ?? null;
1251
- }
1252
- /** Whether any paint of `node` draws a shader. */
1253
- function hasShaderPaint(node) {
1254
- return [...node.fills, ...node.strokes].some((paint) => shaderOfPaint(node, paint) !== null);
1255
- }
1256
- /**
1257
- * The node's plugin data with `shaders` set by their image, keeping only shaders a fill or
1258
- * stroke of `paints` still shows, so removing or replacing a paint leaves no entry behind.
1259
- */
1260
- function withShaderPaints(node, paints, shaders = []) {
1261
- const shown = new Set(paints.flatMap((paint) => paint.type === "IMAGE" && paint.imageHash ? [paint.imageHash] : []));
1262
- const byImage = new Map(readShaderPaints(node).map((shader) => [shader.image, shader]));
1263
- for (const shader of shaders) byImage.set(shader.image, shader);
1264
- return withAllPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.shader, [...byImage.values()].filter((shader) => shown.has(shader.image)));
1265
- }
1266
- /**
1267
- * A new paint that draws `preset`, and the shader entry it shows. Its image names a frame not yet
1268
- * rendered, unique to this paint, so no other paint's entry claims it until the frame is drawn.
1269
- */
1270
- function createShaderPaint(preset) {
1271
- const image = randomHex(20);
1272
- return {
1273
- paint: {
1274
- type: "IMAGE",
1275
- color: TRANSPARENT,
1276
- opacity: 1,
1277
- visible: true,
1278
- imageHash: image,
1279
- imageScaleMode: "FILL"
1280
- },
1281
- shader: {
1282
- image,
1283
- preset: structuredClone(preset)
1284
- }
1285
- };
1286
- }
1287
- /** A short key that tells one preset from another, which a rendered frame records. */
1288
- function shaderPresetKey(preset) {
1289
- return bytesToHex(sha1(utf8ToBytes(JSON.stringify(preset))));
1290
- }
1291
- /**
1292
- * Whether a shader's frame was rendered for its preset at the size `node` has now, so undoing a
1293
- * preset change after reopening the document does not keep a frame of the newer preset.
1294
- */
1295
- function isShaderFrameCurrent(shader, size) {
1296
- const { frame } = shader;
1297
- return frame !== void 0 && frame.preset === shaderPresetKey(shader.preset) && Math.round(frame.width) === Math.round(size.width) && Math.round(frame.height) === Math.round(size.height);
1298
- }
1299
- //#endregion
1300
- //#region src/shaders/still.ts
1301
- /**
1302
- * How a shader paint's still frame is drawn and stored, for every renderer that draws one: the
1303
- * editor's canvas and the tools that prebuild documents. The frame is an image fill in `.fig`
1304
- * files, so Figma must be able to read it, which rules out WebP.
1305
- */
1306
- /** Frames are drawn at twice the layer's size, for sharp high-density displays. */
1307
- const FRAME_SCALE = 2;
1308
- /** The longest side a frame is drawn at, however large the layer. */
1309
- const MAX_FRAME_EDGE = 2048;
1310
- /** JPEG quality for opaque frames: no visible difference from PNG at a fraction of the size. */
1311
- const JPEG_QUALITY = .9;
1312
- /** The pixels a frame for a layer of `size` is drawn at. */
1313
- function shaderFramePixels(size) {
1314
- const scale = Math.min(FRAME_SCALE, MAX_FRAME_EDGE / Math.max(size.width, size.height, 1));
1315
- return {
1316
- width: Math.max(1, Math.round(size.width * scale)),
1317
- height: Math.max(1, Math.round(size.height * scale))
1318
- };
1319
- }
1320
- /**
1321
- * The encoding a frame with these RGBA pixels is stored in: JPEG when every pixel is opaque, which
1322
- * is about 25 times smaller than PNG for a shader, and PNG when any pixel lets the layer behind
1323
- * show through, which JPEG cannot keep.
1324
- */
1325
- function shaderFrameEncoding(rgba) {
1326
- for (let alpha = 3; alpha < rgba.length; alpha += 4) if (rgba[alpha] !== 255) return { type: "image/png" };
1327
- return {
1328
- type: "image/jpeg",
1329
- quality: JPEG_QUALITY
1330
- };
1331
- }
1332
- //#endregion
1333
- //#region src/snap.ts
1334
- const DEFAULT_SNAP_THRESHOLD = 5;
1335
- function getEdges(node) {
1336
- return rotatedBBox(node.x, node.y, node.width, node.height, node.rotation);
1337
- }
1338
- function computeSnap(movingIds, movingBounds, allNodes, threshold = DEFAULT_SNAP_THRESHOLD) {
1339
- const targets = allNodes.filter((n) => !movingIds.has(n.id));
1340
- if (targets.length === 0) return {
1341
- dx: 0,
1342
- dy: 0,
1343
- guides: []
1344
- };
1345
- const m = {
1346
- left: movingBounds.x,
1347
- right: movingBounds.x + movingBounds.width,
1348
- centerX: movingBounds.x + movingBounds.width / 2,
1349
- top: movingBounds.y,
1350
- bottom: movingBounds.y + movingBounds.height,
1351
- centerY: movingBounds.y + movingBounds.height / 2
1352
- };
1353
- let bestDx = Infinity;
1354
- let bestDy = Infinity;
1355
- const guides = [];
1356
- for (const target of targets) {
1357
- const t = getEdges(target);
1358
- const xPairs = [
1359
- [m.left, t.left],
1360
- [m.left, t.right],
1361
- [m.right, t.left],
1362
- [m.right, t.right],
1363
- [m.centerX, t.centerX]
1364
- ];
1365
- for (const [mVal, tVal] of xPairs) {
1366
- const d = tVal - mVal;
1367
- if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDx)) {
1368
- if (Math.abs(d) < Math.abs(bestDx)) {
1369
- bestDx = d;
1370
- guides.length = guides.filter((g) => g.axis === "y").length ? guides.length : guides.length;
1371
- for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "x") guides.splice(i, 1);
1372
- }
1373
- if (Math.abs(d) === Math.abs(bestDx)) {
1374
- const minY = Math.min(m.top, t.top);
1375
- const maxY = Math.max(m.bottom, t.bottom);
1376
- guides.push({
1377
- axis: "x",
1378
- position: tVal,
1379
- from: minY,
1380
- to: maxY
1381
- });
1382
- }
1383
- }
1384
- }
1385
- const yPairs = [
1386
- [m.top, t.top],
1387
- [m.top, t.bottom],
1388
- [m.bottom, t.top],
1389
- [m.bottom, t.bottom],
1390
- [m.centerY, t.centerY]
1391
- ];
1392
- for (const [mVal, tVal] of yPairs) {
1393
- const d = tVal - mVal;
1394
- if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDy)) {
1395
- if (Math.abs(d) < Math.abs(bestDy)) {
1396
- for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "y") guides.splice(i, 1);
1397
- bestDy = d;
1398
- }
1399
- if (Math.abs(d) === Math.abs(bestDy)) {
1400
- const minX = Math.min(m.left, t.left);
1401
- const maxX = Math.max(m.right, t.right);
1402
- guides.push({
1403
- axis: "y",
1404
- position: tVal,
1405
- from: minX,
1406
- to: maxX
1407
- });
1408
- }
1409
- }
1410
- }
1411
- }
1412
- return {
1413
- dx: Math.abs(bestDx) <= threshold ? bestDx : 0,
1414
- dy: Math.abs(bestDy) <= threshold ? bestDy : 0,
1415
- guides
1416
- };
1417
- }
1418
- function computeSelectionBounds(nodes) {
1419
- if (nodes.length === 0) return null;
1420
- let minX = Infinity;
1421
- let minY = Infinity;
1422
- let maxX = -Infinity;
1423
- let maxY = -Infinity;
1424
- for (const n of nodes) {
1425
- const edges = getEdges(n);
1426
- minX = Math.min(minX, edges.left);
1427
- minY = Math.min(minY, edges.top);
1428
- maxX = Math.max(maxX, edges.right);
1429
- maxY = Math.max(maxY, edges.bottom);
1430
- }
1431
- return {
1432
- x: minX,
1433
- y: minY,
1434
- width: maxX - minX,
1435
- height: maxY - minY
1436
- };
1437
- }
1438
- //#endregion
1439
- //#region src/layout/guides.ts
1440
- const MAX_LAYOUT_GUIDE_LINES = 1e4;
1441
- /** Figma's Auto count, as its archive stores it: as many sections as fit. */
1442
- const AUTO_LAYOUT_GRID_COUNT = 2147483647;
1443
- /** Whether a guide's count is Auto: the archive's value, or the plugin API's `Infinity` or `null`. */
1444
- function isAutoGridCount(count) {
1445
- return count === null || count === Infinity || (count ?? 0) >= 2147483647;
1446
- }
1447
- /**
1448
- * A guide's count, set in Figma's plugin shape (`count`) or read from a file (`numSections`); an
1449
- * edit's `count` wins over the count the file had. Auto is {@link AUTO_LAYOUT_GRID_COUNT}.
1450
- */
1451
- function layoutGridCount(grid) {
1452
- const count = grid.count === void 0 ? grid.numSections : grid.count;
1453
- return isAutoGridCount(count) ? AUTO_LAYOUT_GRID_COUNT : count ?? 1;
1454
- }
1455
- function pattern(grid) {
1456
- if (grid.pattern === "GRID" || grid.pattern === "ROWS") return grid.pattern;
1457
- if (grid.axis === "Y") return "ROWS";
1458
- return "COLUMNS";
1459
- }
1460
- function alignment(grid) {
1461
- const value = grid.alignment ?? grid.type;
1462
- if (value === "CENTER" || value === "MAX" || value === "STRETCH") return value;
1463
- return "MIN";
1464
- }
1465
- /**
1466
- * How many sections a guide draws. Auto fits as many fixed sections as the frame holds, counting
1467
- * the offset once from the aligned edge, as Figma desktop 126 draws them.
1468
- */
1469
- function sectionCount(nodeSize, grid) {
1470
- const value = layoutGridCount(grid);
1471
- if (value === 2147483647) {
1472
- const size = grid.sectionSize ?? 0;
1473
- if (alignment(grid) === "STRETCH" || size <= 0) return 0;
1474
- const gutter = grid.gutterSize ?? 0;
1475
- const offset = alignment(grid) === "CENTER" ? 0 : grid.offset ?? 0;
1476
- return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor((nodeSize - offset + gutter) / (size + gutter))));
1477
- }
1478
- if (!Number.isFinite(value)) return 0;
1479
- return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor(value)));
1480
- }
1481
- function sectionSize(nodeSize, grid, count) {
1482
- const fixed = grid.sectionSize ?? 0;
1483
- if (alignment(grid) !== "STRETCH") return fixed;
1484
- const gutter = grid.gutterSize ?? 0;
1485
- return (nodeSize - (grid.offset ?? 0) * 2 - Math.max(0, count - 1) * gutter) / count;
1486
- }
1487
- function start(nodeSize, grid, size, count) {
1488
- const gutter = grid.gutterSize ?? 0;
1489
- const offset = grid.offset ?? 0;
1490
- const span = count * size + Math.max(0, count - 1) * gutter;
1491
- if (alignment(grid) === "CENTER") return (nodeSize - span) / 2 + offset;
1492
- if (alignment(grid) === "MAX") return nodeSize - span - offset;
1493
- return offset;
1494
- }
1495
- function layoutGuideSections(node, grid) {
1496
- if (grid.visible === false || pattern(grid) === "GRID") return [];
1497
- const axis = pattern(grid) === "ROWS" ? "y" : "x";
1498
- const nodeSize = axis === "x" ? node.width : node.height;
1499
- const count = sectionCount(nodeSize, grid);
1500
- const size = sectionSize(nodeSize, grid, count);
1501
- if (count <= 0 || size <= 0) return [];
1502
- const first = start(nodeSize, grid, size, count);
1503
- const step = size + (grid.gutterSize ?? 0);
1504
- return Array.from({ length: count }, (_, index) => {
1505
- const sectionStart = first + index * step;
1506
- return {
1507
- axis,
1508
- start: sectionStart,
1509
- end: sectionStart + size
1510
- };
1511
- });
1512
- }
1513
- function layoutGuideLines(node, grid) {
1514
- if (grid.visible === false) return [];
1515
- const gridPattern = pattern(grid);
1516
- const lines = [];
1517
- if (gridPattern === "GRID") {
1518
- const size = grid.sectionSize ?? 0;
1519
- if (size <= 0) return lines;
1520
- for (let index = 0, x = grid.offset ?? 0; x <= node.width && index < MAX_LAYOUT_GUIDE_LINES; index++, x += size) lines.push({
1521
- axis: "x",
1522
- position: x
1523
- });
1524
- for (let index = 0, y = grid.offset ?? 0; y <= node.height && index < MAX_LAYOUT_GUIDE_LINES; index++, y += size) lines.push({
1525
- axis: "y",
1526
- position: y
1527
- });
1528
- return lines;
1529
- }
1530
- const sections = layoutGuideSections(node, grid);
1531
- for (const section of sections) lines.push({
1532
- axis: section.axis,
1533
- position: section.start
1534
- }, {
1535
- axis: section.axis,
1536
- position: section.end
1537
- });
1538
- return lines;
1539
- }
1540
- //#endregion
1541
- //#region src/text/lists.ts
1542
- /** The marker of an unordered item, at every level. */
1543
- const LIST_BULLET = "•";
1544
- const NUMBER_FORMATS = [
1545
- "DECIMAL",
1546
- "LOWER_ALPHA",
1547
- "LOWER_ROMAN"
1548
- ];
1549
- /** Ordered items count in decimal, then letters, then roman numerals, repeating as they nest. */
1550
- function listNumberFormat(level) {
1551
- return NUMBER_FORMATS[(Math.max(1, level) - 1) % NUMBER_FORMATS.length];
1552
- }
1553
- function alphabetic(value) {
1554
- let letters = "";
1555
- for (let rest = value; rest > 0; rest = Math.floor((rest - 1) / 26)) letters = String.fromCharCode(97 + (rest - 1) % 26) + letters;
1556
- return letters;
1557
- }
1558
- const ROMAN_DIGITS = [
1559
- [1e3, "m"],
1560
- [900, "cm"],
1561
- [500, "d"],
1562
- [400, "cd"],
1563
- [100, "c"],
1564
- [90, "xc"],
1565
- [50, "l"],
1566
- [40, "xl"],
1567
- [10, "x"],
1568
- [9, "ix"],
1569
- [5, "v"],
1570
- [4, "iv"],
1571
- [1, "i"]
1572
- ];
1573
- function roman(value) {
1574
- let rest = value;
1575
- let numeral = "";
1576
- for (const [amount, digits] of ROMAN_DIGITS) for (; rest >= amount; rest -= amount) numeral += digits;
1577
- return numeral;
1578
- }
1579
- /** An ordered item's number as its level writes it, without the period. */
1580
- function formatListNumber(ordinal, format) {
1581
- if (format === "LOWER_ALPHA") return alphabetic(ordinal);
1582
- if (format === "LOWER_ROMAN") return roman(ordinal);
1583
- return String(ordinal);
1584
- }
1585
- /**
1586
- * The list items of a text, numbered as Figma numbers them: each level counts its own items,
1587
- * a deeper item leaves the count above it running, a shallower one restarts the counts below
1588
- * it, and a plain paragraph or an item of the other list type restarts the count.
1589
- */
1590
- function textListItems(text, paragraphs) {
1591
- if (!paragraphs.some((paragraph) => paragraph.listType !== "NONE")) return [];
1592
- const items = [];
1593
- const counts = [];
1594
- let groupStart = -1;
1595
- for (const [paragraph, range] of textParagraphRanges(text).entries()) {
1596
- const style = paragraphStyleAt(paragraphs, paragraph);
1597
- if (style.listType === "NONE") {
1598
- counts.length = 0;
1599
- groupStart = -1;
1600
- continue;
1601
- }
1602
- const level = Math.max(1, style.indentation);
1603
- counts.length = Math.min(counts.length, level);
1604
- const current = counts[level - 1];
1605
- const continues = current?.listType === style.listType;
1606
- const count = continues ? current.count + 1 : 1;
1607
- counts[level - 1] = {
1608
- listType: style.listType,
1609
- count
1610
- };
1611
- const shallower = counts.slice(0, level - 1).some((entry) => entry !== void 0);
1612
- if (groupStart === -1 || !continues && !shallower) groupStart = paragraph;
1613
- const marker = style.listType === "UNORDERED" ? "•" : `${formatListNumber(count, listNumberFormat(level))}.`;
1614
- items.push({
1615
- ...range,
1616
- paragraph,
1617
- listType: style.listType,
1618
- level,
1619
- ordinal: count,
1620
- marker,
1621
- startsList: !continues,
1622
- groupStart
1623
- });
1624
- }
1625
- return items;
1626
- }
1627
- /**
1628
- * Digits in the largest number of a top-level ordered item. Figma widens the indent of every
1629
- * ordered item by the extra digits, so a list's numbers line up past nine.
1630
- */
1631
- function topLevelNumberDigits(items) {
1632
- let largest = 0;
1633
- for (const item of items) if (item.listType === "ORDERED" && item.level === 1) largest = Math.max(largest, item.ordinal);
1634
- return largest === 0 ? 0 : String(largest).length;
1635
- }
1636
- //#endregion
1637
- //#region src/shared-styles.ts
1638
- const STYLE_REF_KEYS = {
1639
- fill: "fillStyleId",
1640
- stroke: "strokeStyleId",
1641
- text: "textStyleId",
1642
- effect: "effectStyleId",
1643
- grid: "gridStyleId"
1644
- };
1645
- const STYLE_TYPES = {
1646
- fill: "FILL",
1647
- stroke: "FILL",
1648
- text: "TEXT",
1649
- effect: "EFFECT",
1650
- grid: "GRID"
1651
- };
1652
- /** The fields a text style gives what uses it; changing one leaves the style. */
1653
- const SHARED_TEXT_STYLE_FIELDS = [
1654
- "fontFamily",
1655
- "fontWeight",
1656
- "italic",
1657
- "fontSize",
1658
- "lineHeight",
1659
- "letterSpacing",
1660
- "textDecoration",
1661
- "textCase",
1662
- "fontFeatures"
1663
- ];
1664
- const TEXT_STYLE_KEYS = new Set(SHARED_TEXT_STYLE_FIELDS);
1665
- function sharedStyleRefKey(kind) {
1666
- return STYLE_REF_KEYS[kind];
1667
- }
1668
- function sharedStyleTypeForKind(kind) {
1669
- return STYLE_TYPES[kind];
1670
- }
1671
- function getSharedStyles(graph, kind) {
1672
- const type = sharedStyleTypeForKind(kind);
1673
- const styles = [];
1674
- for (const node of graph.getAllNodes()) {
1675
- if (node.sharedStyleType !== type || !node.source.id) continue;
1676
- styles.push({
1677
- id: node.source.id,
1678
- nodeId: node.id,
1679
- name: node.name,
1680
- type
1681
- });
1682
- }
1683
- return styles.sort((left, right) => left.name.localeCompare(right.name));
1684
- }
1685
- function styleDetachmentChanges(node, changes) {
1686
- const next = { ...changes };
1687
- if ("fills" in changes && !("fillStyleId" in changes) && node.fillStyleId) next.fillStyleId = null;
1688
- if ("strokes" in changes && !("strokeStyleId" in changes) && node.strokeStyleId) next.strokeStyleId = null;
1689
- if ("effects" in changes && !("effectStyleId" in changes) && node.effectStyleId) next.effectStyleId = null;
1690
- if ("layoutGrids" in changes && !("gridStyleId" in changes) && node.gridStyleId) next.gridStyleId = null;
1691
- if (Object.keys(changes).some((key) => TEXT_STYLE_KEYS.has(key)) && !("textStyleId" in changes) && node.textStyleId) next.textStyleId = null;
1692
- return next;
1693
- }
1694
- //#endregion
1695
- //#region src/text/picture.ts
1696
- /**
1697
- * Invalidate cached Skia textPicture (Paragraph snapshot). Includes width/height
1698
- * because wrapping/layout depends on the box.
1699
- */
1700
- const TEXT_PICTURE_KEYS = /* @__PURE__ */ new Set([
1701
- ...TEXT_SHAPING_FIELDS,
1702
- "textDecoration",
1703
- "fills",
1704
- "width",
1705
- "height"
1706
- ]);
1707
- const GLYPH_AFFECTING_KEYS = new Set(TEXT_SHAPING_FIELDS);
1708
- /**
1709
- * Shared by SceneGraph.updateNode and updateNodePreview (drag hot path) so the
1710
- * two invalidation rules cannot drift. Glyphs are kept when the caller
1711
- * replaces them in the same update (resize supplies scaled copies).
1712
- */
1713
- function textCacheInvalidationChanges(node, changes) {
1714
- const invalidated = {};
1715
- const keys = Object.keys(changes).filter((key) => !isEqual(node[key], changes[key]));
1716
- if (node.textPicture && keys.some((key) => TEXT_PICTURE_KEYS.has(key))) invalidated.textPicture = null;
1717
- const glyphsInvalidated = keys.some((key) => GLYPH_AFFECTING_KEYS.has(key)) || TEXT_LAYOUT_FIELDS.some((key) => keys.includes(key));
1718
- if (glyphsInvalidated && !("derivedLayout" in changes)) invalidated.derivedLayout = null;
1719
- if (node.derivedTextGlyphs && glyphsInvalidated && !changes.derivedTextGlyphs) {
1720
- if (!(!!node.textPathData && keys.every((key) => key === "width" || key === "height"))) {
1721
- invalidated.derivedTextGlyphs = null;
1722
- invalidated.textPathData = null;
1723
- }
1724
- }
1725
- return invalidated;
1726
- }
1727
- function invalidateTextCaches(node, changes) {
1728
- Object.assign(node, textCacheInvalidationChanges(node, changes));
1729
- }
1730
- //#endregion
1731
- //#region src/preview.ts
1732
- const LAYOUT_AFFECTING_KEYS = /* @__PURE__ */ new Set([
1733
- "x",
1734
- "y",
1735
- "width",
1736
- "height",
1737
- "rotation",
1738
- "flipX",
1739
- "flipY",
1740
- "parentId",
1741
- "childIds",
1742
- "layoutMode",
1743
- "layoutDirection",
1744
- "layoutWrap",
1745
- "primaryAxisSizing",
1746
- "counterAxisSizing",
1747
- "itemSpacing",
1748
- "counterAxisSpacing",
1749
- "paddingTop",
1750
- "paddingRight",
1751
- "paddingBottom",
1752
- "paddingLeft",
1753
- "layoutGrow",
1754
- "layoutAlignSelf",
1755
- "layoutPositioning",
1756
- "minWidth",
1757
- "maxWidth",
1758
- "minHeight",
1759
- "maxHeight",
1760
- "visible",
1761
- "text",
1762
- "fontSize",
1763
- "lineHeight",
1764
- "letterSpacing",
1765
- "styleRuns",
1766
- "textAutoResize"
1767
- ]);
1768
- function updateNodePreview(graph, id, changes, beforeUpdate) {
1769
- const node = graph.nodes.get(id);
1770
- if (!node) return null;
1771
- changes = Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== void 0));
1772
- if (Object.keys(changes).every((key) => node[key] === changes[key])) return null;
1773
- if (Object.keys(changes).some((key) => LAYOUT_AFFECTING_KEYS.has(key))) graph.clearAbsPosCache();
1774
- let normalizedChanges = changes;
1775
- if (node.type === "TEXT") normalizedChanges = {
1776
- ...textCacheInvalidationChanges(node, changes),
1777
- ...changes
1778
- };
1779
- if (changes.vectorNetwork) normalizedChanges = {
1780
- ...normalizedChanges,
1781
- vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
1782
- };
1783
- beforeUpdate?.(node, normalizedChanges);
1784
- graph.positionPreviewVersion++;
1785
- Object.assign(node, normalizedChanges);
1786
- return normalizedChanges;
1787
- }
1788
- //#endregion
1789
- //#region src/source-metadata.ts
1790
- function markSourceFieldsEdited(node, changeKeys) {
1791
- if (changeKeys.length === 0) return;
1792
- const editedFields = new Set(node.source.editedFields);
1793
- for (const key of changeKeys) editedFields.add(key);
1794
- node.source.editedFields = [...editedFields];
1795
- }
1796
- //#endregion
1797
- //#region src/index.ts
1798
- /** Figma reads both parts of a GUID as signed 32-bit integers and drops records beyond them. */
1799
- const MAX_ID_SESSION = 2147483647;
1800
- /** Sessions 0 and 1 hold FIG's document and internal-resource records and counter GUIDs. */
1801
- const FIRST_RANDOM_SESSION = 2;
1802
- /** A random session, as Yjs picks each document's `clientID`, so processes never share IDs. */
1803
- function randomIdSession() {
1804
- return FIRST_RANDOM_SESSION + randomIndex(2147483646);
1805
- }
1806
- let idSession = randomIdSession();
1807
- let nextLocalID = 1;
1808
- /**
1809
- * Sets the session part of the IDs this process mints, as in Figma's `sessionID:localID` GUIDs.
1810
- * Every process starts in a random session, so layers that the editor, the CLI, or MCP add to
1811
- * copies of one file never share IDs. Tests and fixtures that need the same IDs on every run
1812
- * set a fixed session or give the graph its own generator. Returns the previous session.
1813
- */
1814
- function setIdSession(sessionId) {
1815
- if (!Number.isInteger(sessionId) || sessionId < 0 || sessionId > MAX_ID_SESSION) throw new RangeError("sessionId must be a non-negative 31-bit integer");
1816
- const previous = idSession;
1817
- idSession = sessionId;
1818
- return previous;
1819
- }
1820
- function generateId() {
1821
- return `${idSession}:${nextLocalID++}`;
1822
- }
1823
- function stripUndefinedProps(obj) {
1824
- const result = {};
1825
- for (const key of Object.keys(obj)) {
1826
- const val = obj[key];
1827
- if (val !== void 0) result[key] = val;
1828
- }
1829
- return result;
1830
- }
1831
- var SceneGraph = class SceneGraph {
1832
- idGenerator;
1833
- nodes = /* @__PURE__ */ new Map();
1834
- images = /* @__PURE__ */ new Map();
1835
- variables = /* @__PURE__ */ new Map();
1836
- variableCollections = /* @__PURE__ */ new Map();
1837
- activeMode = /* @__PURE__ */ new Map();
1838
- rootId;
1839
- figKiwiVersion = null;
1840
- /** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */
1841
- figSchemaDeflated = null;
1842
- documentColorSpace = "srgb";
1843
- enabledLibraries = /* @__PURE__ */ new Map();
1844
- emitter = new BufferedSceneEmitter();
1845
- absPosCache = /* @__PURE__ */ new Map();
1846
- previewMutationDepth = 0;
1847
- previewObservers = [];
1848
- changeObservers = /* @__PURE__ */ new Set();
1849
- sourceMetadataPreservationDepth = 0;
1850
- importedStateApplicationDepth = 0;
1851
- importedIdGenerator;
1852
- layoutMutationDepth = 0;
1853
- derivedLayoutDepth = 0;
1854
- positionPreviewVersion = 0;
1855
- instanceIndex = /* @__PURE__ */ new Map();
1856
- constructor(idGenerator = generateId) {
1857
- this.idGenerator = idGenerator;
1858
- const root = createDefaultNode(this.idGenerator, "FRAME", {
1859
- name: "Document",
1860
- width: 0,
1861
- height: 0
1862
- });
1863
- this.rootId = root.id;
1864
- this.nodes.set(root.id, root);
1865
- this.addPage("Page 1");
1866
- }
1867
- addPage(name) {
1868
- return this.createNode("CANVAS", this.rootId, {
1869
- name,
1870
- width: 0,
1871
- height: 0
1872
- });
1873
- }
1874
- getPages(includeInternal = false) {
1875
- return this.getChildren(this.rootId).filter((n) => n.type === "CANVAS" && (includeInternal || !n.internalOnly));
1876
- }
1877
- getAllNodes() {
1878
- return this.nodes.values();
1879
- }
1880
- getNode(id) {
1881
- return this.nodes.get(id);
1882
- }
1883
- onNodeEvents(handlers) {
1884
- return bindNodeEvents(this.emitter, handlers);
1885
- }
1886
- /**
1887
- * Tells `observer` about each node an edit adds and, before it changes, each node it is about
1888
- * to change, so a recorder can keep the node as it was. Unlike node events these are never
1889
- * buffered. Graph methods report the nodes they change; code that writes into a node directly
1890
- * reports it with `willChangeNode` first.
1891
- */
1892
- observeNodeChanges(observer) {
1893
- this.changeObservers.add(observer);
1894
- return () => this.changeObservers.delete(observer);
1895
- }
1896
- /** Tells `observeNodeChanges` observers that `node` is about to change. */
1897
- willChangeNode(node) {
1898
- if (!node) return;
1899
- for (const observer of this.changeObservers) observer.before(node);
1900
- }
1901
- countDescendants(nodeId) {
1902
- const node = this.nodes.get(nodeId);
1903
- if (!node) return 0;
1904
- let count = 0;
1905
- const stack = [...node.childIds];
1906
- while (stack.length > 0) {
1907
- const id = stack.pop();
1908
- if (id === void 0) break;
1909
- count++;
1910
- const child = this.nodes.get(id);
1911
- if (child) for (const childId of child.childIds) stack.push(childId);
1912
- }
1913
- return count;
1914
- }
1915
- addVariable(variable) {
1916
- addVariable(this, variable);
1917
- }
1918
- removeVariable(id) {
1919
- removeVariable(this, id);
1920
- }
1921
- addCollection(collection) {
1922
- addCollection(this, collection);
1923
- }
1924
- createVariable(name, type, collectionId, value) {
1925
- return createVariable(this, () => this.generateEntityId(), name, type, collectionId, value);
1926
- }
1927
- createCollection(name) {
1928
- const issued = /* @__PURE__ */ new Set();
1929
- return createCollection(this, () => this.generateEntityId(issued), name);
1930
- }
1931
- createMode(collectionId, name, sourceModeId) {
1932
- return createMode(this, () => this.generateEntityId(), collectionId, name, sourceModeId);
1933
- }
1934
- removeCollection(id) {
1935
- removeCollection(this, id);
1936
- }
1937
- getActiveModeId(collectionId) {
1938
- return getActiveModeId(this, collectionId);
1939
- }
1940
- getNodeVariableModeId(nodeId, collectionId) {
1941
- return getNodeVariableModeId(this, nodeId, collectionId);
1942
- }
1943
- setActiveMode(collectionId, modeId) {
1944
- setActiveMode(this, collectionId, modeId);
1945
- }
1946
- addMode(collectionId, modeId, name, sourceMode) {
1947
- addMode(this, collectionId, modeId, name, sourceMode);
1948
- }
1949
- removeMode(collectionId, modeId) {
1950
- removeMode(this, collectionId, modeId);
1951
- }
1952
- renameMode(collectionId, modeId, name) {
1953
- renameMode(this, collectionId, modeId, name);
1954
- }
1955
- setDefaultMode(collectionId, modeId) {
1956
- setDefaultMode(this, collectionId, modeId);
1957
- }
1958
- resolveVariable(variableId, modeId, visited) {
1959
- return resolveVariable(this, variableId, modeId, visited);
1960
- }
1961
- resolveColorVariable(variableId) {
1962
- return resolveColorVariable(this, variableId);
1963
- }
1964
- resolveNumberVariable(variableId) {
1965
- return resolveNumberVariable(this, variableId);
1966
- }
1967
- resolveColorVariableForNode(nodeId, variableId, fallback) {
1968
- return resolveColorVariableForNode(this, nodeId, variableId, fallback);
1969
- }
1970
- resolveNumberVariableForNode(nodeId, variableId, fallback) {
1971
- return resolveNumberVariableForNode(this, nodeId, variableId, fallback);
1972
- }
1973
- resolveVariableForNode(nodeId, variableId, fallback) {
1974
- return resolveVariableForNode(this, nodeId, variableId, fallback);
1975
- }
1976
- resolveStringVariableForNode(nodeId, variableId, fallback) {
1977
- return resolveStringVariableForNode(this, nodeId, variableId, fallback);
1978
- }
1979
- getVariablesForCollection(collectionId) {
1980
- return getVariablesForCollection(this, collectionId);
1981
- }
1982
- getVariablesByType(type) {
1983
- return getVariablesByType(this, type);
1984
- }
1985
- bindVariable(nodeId, field, variableId) {
1986
- bindVariable(this, nodeId, field, variableId);
1987
- }
1988
- unbindVariable(nodeId, field) {
1989
- unbindVariable(this, nodeId, field);
1990
- }
1991
- getChildren(id) {
1992
- const node = this.nodes.get(id);
1993
- if (!node) return [];
1994
- return node.childIds.map((cid) => this.nodes.get(cid)).filter((n) => n !== void 0);
1995
- }
1996
- isContainer(id) {
1997
- const node = this.nodes.get(id);
1998
- return node ? CONTAINER_TYPES.has(node.type) : false;
1999
- }
2000
- isDescendant(childId, ancestorId) {
2001
- return this.closest(childId, (node) => node.id === ancestorId) !== void 0;
2002
- }
2003
- /**
2004
- * The node itself or its nearest ancestor that matches. The walk visits at most as many nodes
2005
- * as the graph holds, so a parent cycle in bad data cannot hang it.
2006
- */
2007
- closest(id, match) {
2008
- let current = this.nodes.get(id);
2009
- for (let steps = 0; current && steps < this.nodes.size; steps++) {
2010
- if (match(current)) return current;
2011
- current = current.parentId ? this.nodes.get(current.parentId) : void 0;
2012
- }
2013
- }
2014
- /**
2015
- * The page a node is on: the node itself for a page, its nearest page ancestor otherwise, and
2016
- * null for the document root or a node on no page.
2017
- */
2018
- pageOf(id) {
2019
- return this.closest(id, (node) => node.type === "CANVAS")?.id ?? null;
2020
- }
2021
- clearAbsPosCache() {
2022
- this.absPosCache.clear();
2023
- }
2024
- getAbsolutePosition(id) {
2025
- const cached = this.absPosCache.get(id);
2026
- if (cached) return cached;
2027
- const node = this.getNode(id);
2028
- if (!node) return {
2029
- x: 0,
2030
- y: 0
2031
- };
2032
- const result = getAbsolutePosition(node, this);
2033
- this.absPosCache.set(id, result);
2034
- return result;
2035
- }
2036
- getAbsoluteBounds(id) {
2037
- const pos = this.getAbsolutePosition(id);
2038
- const node = this.nodes.get(id);
2039
- return {
2040
- x: pos.x,
2041
- y: pos.y,
2042
- width: node?.width ?? 0,
2043
- height: node?.height ?? 0
2044
- };
2045
- }
2046
- /**
2047
- * An ID no entity uses; `issued` also excludes IDs handed out earlier in the same creation.
2048
- * A generator that returns more taken IDs than the graph holds must be repeating itself, so
2049
- * it counts as exhausted then; a fixed cap would reject a sequence walking past a large import.
2050
- */
2051
- generateEntityId(issued) {
2052
- let limit = Infinity;
2053
- for (let attempt = 0; attempt < limit; attempt++) {
2054
- const id = (this.importedIdGenerator ?? this.idGenerator)();
2055
- if (this.isEntityIdTaken(id) || issued?.has(id)) {
2056
- if (limit === Infinity) limit = this.entityIdCount() + (issued?.size ?? 0) + 1;
2057
- continue;
2058
- }
2059
- issued?.add(id);
2060
- return id;
2061
- }
2062
- throw new Error("The ID generator only returned IDs that are in use");
2063
- }
2064
- entityIdCount() {
2065
- let count = this.nodes.size + this.variables.size + this.variableCollections.size;
2066
- for (const collection of this.variableCollections.values()) count += collection.modes.length;
2067
- return count;
2068
- }
2069
- isEntityIdTaken(id) {
2070
- if (this.nodes.has(id) || this.variables.has(id) || this.variableCollections.has(id)) return true;
2071
- for (const collection of this.variableCollections.values()) for (const mode of collection.modes) if (mode.modeId === id) return true;
2072
- return false;
2073
- }
2074
- registerNode(node, parentId) {
2075
- node.parentId = parentId;
2076
- this.nodes.set(node.id, node);
2077
- for (const observer of this.changeObservers) observer.created(node);
2078
- if (node.type === "INSTANCE" && node.componentId) {
2079
- let set = this.instanceIndex.get(node.componentId);
2080
- if (!set) {
2081
- set = /* @__PURE__ */ new Set();
2082
- this.instanceIndex.set(node.componentId, set);
2083
- }
2084
- set.add(node.id);
2085
- }
2086
- this.emitter.emit("node:created", node);
2087
- return node;
2088
- }
2089
- /** Publish synchronous graph events only after the supplied mutation succeeds. */
2090
- withBufferedEvents(action) {
2091
- return this.emitter.batch(action);
2092
- }
2093
- createNode(type, parentId, overrides = {}) {
2094
- const node = createDefaultNode(() => this.generateEntityId(), type, overrides);
2095
- const parent = this.nodes.get(parentId);
2096
- this.willChangeNode(parent);
2097
- parent?.childIds.push(node.id);
2098
- return this.registerNode(node, parentId);
2099
- }
2100
- createNodeWithId(id, type, parentId, overrides = {}) {
2101
- const node = createDefaultNode(() => id, type, overrides);
2102
- node.id = id;
2103
- const parent = parentId ? this.nodes.get(parentId) : void 0;
2104
- if (parent && !parent.childIds.includes(id)) {
2105
- this.willChangeNode(parent);
2106
- parent.childIds.push(id);
2107
- }
2108
- return this.registerNode(node, parentId);
2109
- }
2110
- static TEXT_PICTURE_KEYS = TEXT_PICTURE_KEYS;
2111
- static GLYPH_AFFECTING_KEYS = GLYPH_AFFECTING_KEYS;
2112
- static LAYOUT_AFFECTING_KEYS = /* @__PURE__ */ new Set([
2113
- ...TRANSFORM_FIELDS,
2114
- ...SIZE_FIELDS,
2115
- "layoutMode",
2116
- "layoutDirection",
2117
- "itemSpacing",
2118
- "counterAxisSpacing",
2119
- "paddingLeft",
2120
- "paddingRight",
2121
- "paddingTop",
2122
- "paddingBottom",
2123
- "primaryAxisAlign",
2124
- "counterAxisAlign",
2125
- "counterAxisAlignContent",
2126
- "layoutWrap",
2127
- "primaryAxisSizing",
2128
- "counterAxisSizing",
2129
- "layoutPositioning",
2130
- "layoutGrow",
2131
- "layoutAlignSelf",
2132
- "strokesIncludedInLayout",
2133
- "horizontalConstraint",
2134
- "verticalConstraint",
2135
- "gridTemplateColumns",
2136
- "gridTemplateRows",
2137
- "gridColumnGap",
2138
- "gridRowGap",
2139
- "gridPosition",
2140
- "minWidth",
2141
- "maxWidth",
2142
- "minHeight",
2143
- "maxHeight",
2144
- "targetAspectRatio"
2145
- ]);
2146
- runPreviewUpdates(fn, beforeUpdate) {
2147
- this.previewMutationDepth++;
2148
- if (beforeUpdate) this.previewObservers.push(beforeUpdate);
2149
- try {
2150
- fn();
2151
- } finally {
2152
- if (beforeUpdate) this.previewObservers.pop();
2153
- this.previewMutationDepth--;
2154
- }
2155
- }
2156
- preserveSourceMetadataDuring(fn) {
2157
- this.sourceMetadataPreservationDepth++;
2158
- try {
2159
- return fn();
2160
- } finally {
2161
- this.sourceMetadataPreservationDepth--;
2162
- }
2163
- }
2164
- get isPreservingSourceMetadata() {
2165
- return this.sourceMetadataPreservationDepth > 0;
2166
- }
2167
- applyImportedStateDuring(fn, idGenerator) {
2168
- const previousGenerator = this.importedIdGenerator;
2169
- this.importedIdGenerator = idGenerator ?? previousGenerator;
2170
- this.importedStateApplicationDepth++;
2171
- try {
2172
- return this.preserveSourceMetadataDuring(fn);
2173
- } finally {
2174
- this.importedStateApplicationDepth--;
2175
- this.importedIdGenerator = previousGenerator;
2176
- }
2177
- }
2178
- get isApplyingImportedState() {
2179
- return this.importedStateApplicationDepth > 0;
2180
- }
2181
- /**
2182
- * Lays out what the document already holds: a page as it loads, or again once its fonts
2183
- * arrive. What this writes derives from the document; an edit's own layout is not this.
2184
- */
2185
- applyDerivedLayoutDuring(fn) {
2186
- this.derivedLayoutDepth++;
2187
- try {
2188
- fn();
2189
- } finally {
2190
- this.derivedLayoutDepth--;
2191
- }
2192
- }
2193
- get isApplyingDerivedLayout() {
2194
- return this.derivedLayoutDepth > 0;
2195
- }
2196
- withLayoutMutations(fn) {
2197
- this.layoutMutationDepth++;
2198
- try {
2199
- fn();
2200
- } finally {
2201
- this.layoutMutationDepth--;
2202
- }
2203
- }
2204
- get isApplyingLayout() {
2205
- return this.layoutMutationDepth > 0;
2206
- }
2207
- updateNodePositionPreview(id, x, y) {
2208
- this.updateNodePreview(id, {
2209
- x,
2210
- y
2211
- });
2212
- }
2213
- updateNodePreview(id, changes) {
2214
- const appliedChanges = updateNodePreview(this, id, changes, (node, applied) => {
2215
- for (const observe of this.previewObservers) observe(node, applied);
2216
- });
2217
- if (appliedChanges) this.emitter.emit("node:previewUpdated", id, appliedChanges);
2218
- }
2219
- updateNode(id, changes) {
2220
- if (this.previewMutationDepth > 0) {
2221
- this.updateNodePreview(id, changes);
2222
- return;
2223
- }
2224
- const node = this.nodes.get(id);
2225
- if (!node) return;
2226
- changes = stripUndefinedProps(styleDetachmentChanges(node, stripUndefinedProps(changes)));
2227
- this.applyNodeChanges(node, changes);
2228
- }
2229
- /** Replay captured properties without dropping explicit undefined values or absent keys. */
2230
- restoreNodeProperties(id, changes, absent) {
2231
- const node = this.nodes.get(id);
2232
- if (node) this.applyNodeChanges(node, changes, absent);
2233
- }
2234
- applyNodeChanges(node, changes, absent = []) {
2235
- const { id } = node;
2236
- this.willChangeNode(node);
2237
- if (absent.length) {
2238
- changes = { ...changes };
2239
- for (const key of absent) Reflect.set(changes, key, void 0);
2240
- }
2241
- if (Object.keys(changes).some((k) => SceneGraph.LAYOUT_AFFECTING_KEYS.has(k))) this.absPosCache.clear();
2242
- if (node.type === "INSTANCE" && "componentId" in changes && changes.componentId !== node.componentId) {
2243
- if (node.componentId) this.instanceIndex.get(node.componentId)?.delete(id);
2244
- if (changes.componentId) {
2245
- let set = this.instanceIndex.get(changes.componentId);
2246
- if (!set) {
2247
- set = /* @__PURE__ */ new Set();
2248
- this.instanceIndex.set(changes.componentId, set);
2249
- }
2250
- set.add(id);
2251
- }
2252
- }
2253
- if (node.type === "TEXT") invalidateTextCaches(node, changes);
2254
- if (this.sourceMetadataPreservationDepth === 0 && !this.isApplyingLayout) markSourceFieldsEdited(node, Object.keys(changes));
2255
- if (changes.vectorNetwork) changes = {
2256
- ...changes,
2257
- vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
2258
- };
2259
- Object.assign(node, changes);
2260
- if (changes.fills) removeStaleBindings(node, "fills", changes);
2261
- if (changes.strokes) removeStaleBindings(node, "strokes", changes);
2262
- for (const key of absent) Reflect.deleteProperty(node, key);
2263
- this.emitter.emit("node:updated", id, changes);
2264
- }
2265
- reparentNode(nodeId, newParentId) {
2266
- const node = this.nodes.get(nodeId);
2267
- if (!node || nodeId === this.rootId) return;
2268
- if (this.isDescendant(newParentId, nodeId)) return;
2269
- const oldParent = node.parentId ? this.nodes.get(node.parentId) : void 0;
2270
- const newParent = this.nodes.get(newParentId);
2271
- if (!newParent) return;
2272
- if (node.parentId === newParentId) return;
2273
- const oldParentId = node.parentId;
2274
- this.willChangeNode(node);
2275
- this.willChangeNode(oldParent);
2276
- this.willChangeNode(newParent);
2277
- this.absPosCache.clear();
2278
- const oldParentWorld = this.parentWorldMatrix(oldParent);
2279
- const newParentWorld = this.parentWorldMatrix(newParent);
2280
- if (oldParent) oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId);
2281
- node.parentId = newParentId;
2282
- newParent.childIds.push(nodeId);
2283
- if (isTranslationOnly(oldParentWorld) && isTranslationOnly(newParentWorld)) {
2284
- node.x += oldParentWorld[2] - newParentWorld[2];
2285
- node.y += oldParentWorld[5] - newParentWorld[5];
2286
- } else {
2287
- const world = Matrix.multiply(oldParentWorld, getNodeLocalMatrix(node));
2288
- const local = localTransformFromWorld(node, world, newParentWorld);
2289
- if (local) Object.assign(node, local);
2290
- }
2291
- this.emitter.emit("node:reparented", nodeId, oldParentId, newParentId);
2292
- }
2293
- parentWorldMatrix(parent) {
2294
- return getParentWorldMatrix(parent, this);
2295
- }
2296
- reorderChild(nodeId, parentId, insertIndex) {
2297
- const node = this.nodes.get(nodeId);
2298
- if (!node) return;
2299
- const previousParentId = node.parentId;
2300
- const oldParent = previousParentId ? this.nodes.get(previousParentId) : void 0;
2301
- const newParent = this.nodes.get(parentId);
2302
- if (!newParent || this.isDescendant(parentId, nodeId)) return;
2303
- this.willChangeNode(node);
2304
- this.willChangeNode(oldParent);
2305
- this.willChangeNode(newParent);
2306
- if (oldParent) oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId);
2307
- let idx = insertIndex;
2308
- if (oldParent === newParent && idx > (!oldParent.childIds.includes(nodeId) ? idx : oldParent.childIds.length)) {}
2309
- node.parentId = parentId;
2310
- this.absPosCache.clear();
2311
- idx = Math.min(idx, newParent.childIds.length);
2312
- newParent.childIds.splice(idx, 0, nodeId);
2313
- this.emitter.emit("node:reordered", nodeId, parentId, idx, previousParentId);
2314
- }
2315
- insertChildAt(childId, parentId, index) {
2316
- const node = this.getNode(childId);
2317
- const newParent = this.getNode(parentId);
2318
- if (!node || !newParent || childId === parentId || this.isDescendant(parentId, childId)) return;
2319
- const previousParentId = node.parentId;
2320
- const oldParent = previousParentId ? this.getNode(previousParentId) : void 0;
2321
- this.willChangeNode(node);
2322
- this.willChangeNode(oldParent);
2323
- this.willChangeNode(newParent);
2324
- if (oldParent) oldParent.childIds = oldParent.childIds.filter((id) => id !== childId);
2325
- newParent.childIds = newParent.childIds.filter((id) => id !== childId);
2326
- newParent.childIds.splice(index, 0, childId);
2327
- node.parentId = parentId;
2328
- this.clearAbsPosCache();
2329
- this.emitter.emit("node:reordered", childId, parentId, index, previousParentId);
2330
- }
2331
- deleteNode(id) {
2332
- const node = this.nodes.get(id);
2333
- if (!node || id === this.rootId) return;
2334
- this.willChangeNode(node);
2335
- if (node.parentId) {
2336
- const parent = this.nodes.get(node.parentId);
2337
- this.willChangeNode(parent);
2338
- if (parent) parent.childIds = parent.childIds.filter((cid) => cid !== id);
2339
- }
2340
- for (const childId of Array.from(node.childIds)) this.deleteNode(childId);
2341
- if (node.type === "INSTANCE" && node.componentId) this.instanceIndex.get(node.componentId)?.delete(id);
2342
- this.nodes.delete(id);
2343
- this.emitter.emit("node:deleted", id, node.parentId);
2344
- }
2345
- hitTest(px, py, scopeId) {
2346
- return hitTest(this, px, py, scopeId);
2347
- }
2348
- /** `pad`, in canvas units, grows each shape's box, as Figma takes clicks just outside one. */
2349
- hitTestDeep(px, py, scopeId, pad = 0) {
2350
- return hitTestDeep(this, px, py, scopeId, pad);
2351
- }
2352
- hitTestSelectable(px, py, scopeId, selectedIds, pad = 0) {
2353
- return hitTestSelectable(this, px, py, scopeId, selectedIds, pad);
2354
- }
2355
- hitTestOpenContainer(px, py, scopeId) {
2356
- return hitTestOpenContainer(this, px, py, scopeId);
2357
- }
2358
- isOpenContainer(nodeId) {
2359
- return isOpenContainer(this, nodeId);
2360
- }
2361
- isPointInNode(nodeId, px, py) {
2362
- return isPointInNode(this, nodeId, px, py);
2363
- }
2364
- hitTestDropTarget(px, py, excludeIds, scopeId, options) {
2365
- return hitTestDropTarget(this, px, py, excludeIds, scopeId, options);
2366
- }
2367
- cloneTree(sourceId, parentId, overrides = {}) {
2368
- const src = this.nodes.get(sourceId);
2369
- if (!src) return null;
2370
- const props = cloneNodeProps(src, null);
2371
- props.source = {
2372
- ...props.source,
2373
- id: null,
2374
- orderKey: null
2375
- };
2376
- const clone = this.createNode(src.type, parentId, {
2377
- ...props,
2378
- ...overrides
2379
- });
2380
- for (const childId of src.childIds) this.cloneTree(childId, clone.id);
2381
- return clone;
2382
- }
2383
- createInstance(componentId, parentId, overrides = {}) {
2384
- return createInstance(this, componentId, parentId, overrides);
2385
- }
2386
- populateInstanceChildren(instanceId, componentId, mode = "deep") {
2387
- populateInstanceChildren(this, instanceId, componentId, mode);
2388
- }
2389
- swapInstanceComponent(instanceId, componentId, options) {
2390
- swapInstanceComponent(this, instanceId, componentId, options);
2391
- }
2392
- syncInstances(componentId) {
2393
- syncInstances(this, componentId);
2394
- }
2395
- syncInstancesTogether(componentIds) {
2396
- syncInstancesTogether(this, componentIds);
2397
- }
2398
- syncInstance(instanceId) {
2399
- syncInstance(this, instanceId);
2400
- }
2401
- detachInstance(instanceId) {
2402
- detachInstance(this, instanceId);
2403
- }
2404
- getMainComponent(instanceId) {
2405
- return getMainComponent(this, instanceId);
2406
- }
2407
- getInstances(componentId) {
2408
- return getInstances(this, componentId);
2409
- }
2410
- flattenTree(parentId, depth = 0) {
2411
- const id = parentId ?? this.rootId;
2412
- const parent = this.nodes.get(id);
2413
- if (!parent) return [];
2414
- const result = [];
2415
- for (const childId of parent.childIds) {
2416
- const child = this.nodes.get(childId);
2417
- if (!child) continue;
2418
- result.push({
2419
- node: child,
2420
- depth
2421
- });
2422
- if (child.childIds.length > 0) result.push(...this.flattenTree(childId, depth + 1));
2423
- }
2424
- return result;
2425
- }
2426
- };
2427
- //#endregion
2428
- export { AUTO_LAYOUT_GRID_COUNT, DEFAULT_SLOT_SETTINGS, GLYPH_AFFECTING_KEYS, LIST_BULLET, ROOT_FONT_SIZE_PX, SHARED_TEXT_STYLE_FIELDS, SceneGraph, TEXT_PICTURE_KEYS, addCollection, addMode, addVariable, applyGraphTransfer, assignVariableBindingUnits, bindVariable, canCreateSlot, captureTransferredState, claimSlotContent, clearSlotContent, collectSceneMutation, collectionsBoundIn, computeSelectionBounds, computeSnap, createCollection, createMode, createSceneMutationImpact, createShaderPaint, createSlotProperty, createVariable, formatListNumber, generateId, getActiveModeId, getNodeVariableModeId, getSharedStyles, getVariablesByType, getVariablesForCollection, hasShaderPaint, invalidateTextCaches, isAutoGridCount, isPreferredComponent, isShaderFrameCurrent, layersUsingVariables, layoutGridCount, layoutGuideLines, layoutGuideSections, listNumberFormat, markSourceFieldsEdited, modesDefaultFirst, mutationLayoutScopeIds, nonPreferredLayers, prepareGraphTransfer, prepareNodeTransfer, prepareVariableTransfer, readShaderPaints, reconcileVariableBindings, recordSceneMutations, remapStyleRunReferences, removeCollection, removeGraphTransfer, removeMode, removeVariable, renameMode, rescaleNodeTree, resetSlotContent, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolvedNumericBindings, resolvedPaintBindings, resolvedRunBindings, resolvedValueBindings, setActiveMode, setDefaultMode, setIdSession, shaderFrameEncoding, shaderFramePixels, shaderOfPaint, shaderPresetKey, sharedStyleRefKey, sharedStyleTypeForKind, slotLimitViolations, slotOwner, slotScope, styleDetachmentChanges, styleRunReferences, textCacheInvalidationChanges, textListItems, tokenNumberFromUnit, tokenNumberInUnit, topLevelNumberDigits, unbindVariable, updateNodePreview, updateSlotProperty, variableBindingOwner, variableText, variablesResolvingThrough, withShaderPaints };
2429
-
2430
- //# sourceMappingURL=index.js.map