@moondraft/import 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +34 -0
  3. package/README.md +36 -2
  4. package/SOURCE.md +394 -0
  5. package/dist/adapter/convert.d.ts +144 -0
  6. package/dist/adapter/convert.js +2811 -0
  7. package/dist/adapter/figma-descriptions.d.ts +7 -0
  8. package/dist/adapter/figma-descriptions.js +34 -0
  9. package/dist/adapter/figma-grids.d.ts +12 -0
  10. package/dist/adapter/figma-grids.js +175 -0
  11. package/dist/adapter/figma-handoff.d.ts +12 -0
  12. package/dist/adapter/figma-handoff.js +167 -0
  13. package/dist/adapter/figma-hyperlinks.d.ts +13 -0
  14. package/dist/adapter/figma-hyperlinks.js +77 -0
  15. package/dist/adapter/figma.d.ts +12 -0
  16. package/dist/adapter/figma.js +40 -0
  17. package/dist/adapter/file-components.d.ts +20 -0
  18. package/dist/adapter/file-components.js +352 -0
  19. package/dist/adapter/file-resources.d.ts +29 -0
  20. package/dist/adapter/file-resources.js +851 -0
  21. package/dist/adapter/image-crop.d.ts +18 -0
  22. package/dist/adapter/image-crop.js +30 -0
  23. package/dist/adapter/index.d.ts +6 -0
  24. package/dist/adapter/index.js +9 -0
  25. package/dist/adapter/link.d.ts +49 -0
  26. package/dist/adapter/link.js +892 -0
  27. package/dist/adapter/payload.d.ts +31 -0
  28. package/dist/adapter/payload.js +78 -0
  29. package/dist/adapter/shapes.d.ts +31 -0
  30. package/dist/adapter/shapes.js +75 -0
  31. package/dist/adapter/variables.d.ts +45 -0
  32. package/dist/adapter/variables.js +106 -0
  33. package/dist/figma-file.d.ts +38 -0
  34. package/dist/figma-file.js +97 -0
  35. package/dist/figma-worker.d.ts +11 -0
  36. package/dist/figma-worker.js +12 -0
  37. package/dist/figma.d.ts +26 -0
  38. package/dist/figma.js +230 -0
  39. package/dist/index.d.ts +29 -0
  40. package/dist/index.js +50 -0
  41. package/dist/report.d.ts +42 -0
  42. package/dist/report.js +142 -0
  43. package/dist/serialize.d.ts +7 -0
  44. package/dist/serialize.js +79 -0
  45. package/dist/svg.d.ts +33 -0
  46. package/dist/svg.js +44 -0
  47. package/dist/syntax.d.ts +8 -0
  48. package/dist/syntax.js +19 -0
  49. package/dist/taco/figma-import/clipboard.d.ts +25 -0
  50. package/dist/taco/figma-import/clipboard.js +87 -0
  51. package/dist/taco/figma-import/clipboardSize.d.ts +31 -0
  52. package/dist/taco/figma-import/clipboardSize.js +107 -0
  53. package/dist/taco/figma-import/container/compression.d.ts +9 -0
  54. package/dist/taco/figma-import/container/compression.js +174 -0
  55. package/dist/taco/figma-import/container/error.d.ts +15 -0
  56. package/dist/taco/figma-import/container/error.js +19 -0
  57. package/dist/taco/figma-import/container/kiwiContainer.d.ts +41 -0
  58. package/dist/taco/figma-import/container/kiwiContainer.js +61 -0
  59. package/dist/taco/figma-import/container/limits.d.ts +22 -0
  60. package/dist/taco/figma-import/container/limits.js +22 -0
  61. package/dist/taco/figma-import/container/zip.d.ts +14 -0
  62. package/dist/taco/figma-import/container/zip.js +154 -0
  63. package/dist/taco/figma-import/figFile.d.ts +34 -0
  64. package/dist/taco/figma-import/figFile.js +91 -0
  65. package/dist/taco/figma-import/figFileDocument.d.ts +25 -0
  66. package/dist/taco/figma-import/figFileDocument.js +100 -0
  67. package/dist/taco/figma-import/import/blobs.d.ts +10 -0
  68. package/dist/taco/figma-import/import/blobs.js +23 -0
  69. package/dist/taco/figma-import/import/carry.d.ts +24 -0
  70. package/dist/taco/figma-import/import/carry.js +66 -0
  71. package/dist/taco/figma-import/import/componentProps.d.ts +90 -0
  72. package/dist/taco/figma-import/import/componentProps.js +329 -0
  73. package/dist/taco/figma-import/import/componentSets.d.ts +85 -0
  74. package/dist/taco/figma-import/import/componentSets.js +647 -0
  75. package/dist/taco/figma-import/import/converters/effects.d.ts +31 -0
  76. package/dist/taco/figma-import/import/converters/effects.js +127 -0
  77. package/dist/taco/figma-import/import/converters/ellipse.d.ts +7 -0
  78. package/dist/taco/figma-import/import/converters/ellipse.js +54 -0
  79. package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
  80. package/dist/taco/figma-import/import/converters/exportSettings.js +49 -0
  81. package/dist/taco/figma-import/import/converters/frame.d.ts +21 -0
  82. package/dist/taco/figma-import/import/converters/frame.js +63 -0
  83. package/dist/taco/figma-import/import/converters/gradient.d.ts +74 -0
  84. package/dist/taco/figma-import/import/converters/gradient.js +108 -0
  85. package/dist/taco/figma-import/import/converters/group.d.ts +19 -0
  86. package/dist/taco/figma-import/import/converters/group.js +30 -0
  87. package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
  88. package/dist/taco/figma-import/import/converters/image.js +94 -0
  89. package/dist/taco/figma-import/import/converters/layout.d.ts +33 -0
  90. package/dist/taco/figma-import/import/converters/layout.js +187 -0
  91. package/dist/taco/figma-import/import/converters/line.d.ts +11 -0
  92. package/dist/taco/figma-import/import/converters/line.js +40 -0
  93. package/dist/taco/figma-import/import/converters/rectangle.d.ts +3 -0
  94. package/dist/taco/figma-import/import/converters/rectangle.js +11 -0
  95. package/dist/taco/figma-import/import/converters/section.d.ts +8 -0
  96. package/dist/taco/figma-import/import/converters/section.js +29 -0
  97. package/dist/taco/figma-import/import/converters/shared.d.ts +71 -0
  98. package/dist/taco/figma-import/import/converters/shared.js +372 -0
  99. package/dist/taco/figma-import/import/converters/text.d.ts +54 -0
  100. package/dist/taco/figma-import/import/converters/text.js +707 -0
  101. package/dist/taco/figma-import/import/converters/vector.d.ts +105 -0
  102. package/dist/taco/figma-import/import/converters/vector.js +609 -0
  103. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +114 -0
  104. package/dist/taco/figma-import/import/converters/vectorNetwork.js +503 -0
  105. package/dist/taco/figma-import/import/fields.d.ts +15 -0
  106. package/dist/taco/figma-import/import/fields.js +29 -0
  107. package/dist/taco/figma-import/import/instances.d.ts +184 -0
  108. package/dist/taco/figma-import/import/instances.js +1530 -0
  109. package/dist/taco/figma-import/import/nestingCycles.d.ts +86 -0
  110. package/dist/taco/figma-import/import/nestingCycles.js +488 -0
  111. package/dist/taco/figma-import/import/slots.d.ts +56 -0
  112. package/dist/taco/figma-import/import/slots.js +96 -0
  113. package/dist/taco/figma-import/import/styles.d.ts +48 -0
  114. package/dist/taco/figma-import/import/styles.js +48 -0
  115. package/dist/taco/figma-import/import/tree.d.ts +66 -0
  116. package/dist/taco/figma-import/import/tree.js +194 -0
  117. package/dist/taco/figma-import/import/types.d.ts +232 -0
  118. package/dist/taco/figma-import/import/types.js +33 -0
  119. package/dist/taco/figma-import/import/variables.d.ts +137 -0
  120. package/dist/taco/figma-import/import/variables.js +769 -0
  121. package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
  122. package/dist/taco/figma-import/import/variantTrees.js +520 -0
  123. package/dist/taco/figma-import/import/walk.d.ts +207 -0
  124. package/dist/taco/figma-import/import/walk.js +1464 -0
  125. package/dist/taco/figma-import/index.d.ts +22 -0
  126. package/dist/taco/figma-import/index.js +13 -0
  127. package/dist/taco/figma-import/kiwi/byteReader.d.ts +37 -0
  128. package/dist/taco/figma-import/kiwi/byteReader.js +151 -0
  129. package/dist/taco/figma-import/kiwi/error.d.ts +14 -0
  130. package/dist/taco/figma-import/kiwi/error.js +29 -0
  131. package/dist/taco/figma-import/kiwi/limits.d.ts +18 -0
  132. package/dist/taco/figma-import/kiwi/limits.js +18 -0
  133. package/dist/taco/figma-import/kiwi/message.d.ts +12 -0
  134. package/dist/taco/figma-import/kiwi/message.js +147 -0
  135. package/dist/taco/figma-import/kiwi/schema.d.ts +42 -0
  136. package/dist/taco/figma-import/kiwi/schema.js +206 -0
  137. package/dist/taco/figma-import/kiwi/types.d.ts +46 -0
  138. package/dist/taco/figma-import/kiwi/types.js +18 -0
  139. package/dist/taco/model/agent-hidden-fields.d.ts +20 -0
  140. package/dist/taco/model/agent-hidden-fields.js +29 -0
  141. package/dist/taco/model/asset-users.d.ts +23 -0
  142. package/dist/taco/model/asset-users.js +128 -0
  143. package/dist/taco/model/auto-layout-lines.d.ts +32 -0
  144. package/dist/taco/model/auto-layout-lines.js +70 -0
  145. package/dist/taco/model/codec.d.ts +444 -0
  146. package/dist/taco/model/codec.js +5665 -0
  147. package/dist/taco/model/color.d.ts +11 -0
  148. package/dist/taco/model/color.js +61 -0
  149. package/dist/taco/model/comment-operations.d.ts +102 -0
  150. package/dist/taco/model/comment-operations.js +227 -0
  151. package/dist/taco/model/component-evaluation.d.ts +96 -0
  152. package/dist/taco/model/component-evaluation.js +555 -0
  153. package/dist/taco/model/component-expressions.d.ts +242 -0
  154. package/dist/taco/model/component-expressions.js +1082 -0
  155. package/dist/taco/model/component-properties.d.ts +111 -0
  156. package/dist/taco/model/component-properties.js +339 -0
  157. package/dist/taco/model/component-samples.d.ts +83 -0
  158. package/dist/taco/model/component-samples.js +290 -0
  159. package/dist/taco/model/component-validity.d.ts +85 -0
  160. package/dist/taco/model/component-validity.js +397 -0
  161. package/dist/taco/model/components.d.ts +155 -0
  162. package/dist/taco/model/components.js +505 -0
  163. package/dist/taco/model/connector-ends.d.ts +20 -0
  164. package/dist/taco/model/connector-ends.js +188 -0
  165. package/dist/taco/model/connector-geometry.d.ts +74 -0
  166. package/dist/taco/model/connector-geometry.js +293 -0
  167. package/dist/taco/model/corner-radii.d.ts +26 -0
  168. package/dist/taco/model/corner-radii.js +47 -0
  169. package/dist/taco/model/derivations.d.ts +81 -0
  170. package/dist/taco/model/derivations.js +151 -0
  171. package/dist/taco/model/export-settings.d.ts +53 -0
  172. package/dist/taco/model/export-settings.js +156 -0
  173. package/dist/taco/model/expressions/ast.d.ts +153 -0
  174. package/dist/taco/model/expressions/ast.js +6 -0
  175. package/dist/taco/model/expressions/cache.d.ts +23 -0
  176. package/dist/taco/model/expressions/cache.js +43 -0
  177. package/dist/taco/model/expressions/check.d.ts +72 -0
  178. package/dist/taco/model/expressions/check.js +517 -0
  179. package/dist/taco/model/expressions/completion.d.ts +61 -0
  180. package/dist/taco/model/expressions/completion.js +421 -0
  181. package/dist/taco/model/expressions/evaluate.d.ts +32 -0
  182. package/dist/taco/model/expressions/evaluate.js +519 -0
  183. package/dist/taco/model/expressions/forms.d.ts +84 -0
  184. package/dist/taco/model/expressions/forms.js +200 -0
  185. package/dist/taco/model/expressions/index.d.ts +14 -0
  186. package/dist/taco/model/expressions/index.js +17 -0
  187. package/dist/taco/model/expressions/lexer.d.ts +42 -0
  188. package/dist/taco/model/expressions/lexer.js +213 -0
  189. package/dist/taco/model/expressions/library.d.ts +33 -0
  190. package/dist/taco/model/expressions/library.js +117 -0
  191. package/dist/taco/model/expressions/names.d.ts +43 -0
  192. package/dist/taco/model/expressions/names.js +99 -0
  193. package/dist/taco/model/expressions/parser.d.ts +15 -0
  194. package/dist/taco/model/expressions/parser.js +438 -0
  195. package/dist/taco/model/expressions/rename.d.ts +34 -0
  196. package/dist/taco/model/expressions/rename.js +46 -0
  197. package/dist/taco/model/expressions/source.d.ts +15 -0
  198. package/dist/taco/model/expressions/source.js +161 -0
  199. package/dist/taco/model/expressions/types.d.ts +119 -0
  200. package/dist/taco/model/expressions/types.js +102 -0
  201. package/dist/taco/model/expressions/values.d.ts +97 -0
  202. package/dist/taco/model/expressions/values.js +160 -0
  203. package/dist/taco/model/geometry-limits.d.ts +16 -0
  204. package/dist/taco/model/geometry-limits.js +67 -0
  205. package/dist/taco/model/geometry.d.ts +47 -0
  206. package/dist/taco/model/geometry.js +193 -0
  207. package/dist/taco/model/group-bounds.d.ts +38 -0
  208. package/dist/taco/model/group-bounds.js +144 -0
  209. package/dist/taco/model/id-table.d.ts +37 -0
  210. package/dist/taco/model/id-table.js +80 -0
  211. package/dist/taco/model/index.d.ts +25 -0
  212. package/dist/taco/model/index.js +27 -0
  213. package/dist/taco/model/instance-resolver.d.ts +376 -0
  214. package/dist/taco/model/instance-resolver.js +1778 -0
  215. package/dist/taco/model/layer-syntax.d.ts +340 -0
  216. package/dist/taco/model/layer-syntax.js +3506 -0
  217. package/dist/taco/model/layout/constraints.d.ts +84 -0
  218. package/dist/taco/model/layout/constraints.js +445 -0
  219. package/dist/taco/model/layout/frame-layout.d.ts +46 -0
  220. package/dist/taco/model/layout/frame-layout.js +618 -0
  221. package/dist/taco/model/layout/node-sizing.d.ts +163 -0
  222. package/dist/taco/model/layout/node-sizing.js +486 -0
  223. package/dist/taco/model/legacy-connector-caps.d.ts +15 -0
  224. package/dist/taco/model/legacy-connector-caps.js +70 -0
  225. package/dist/taco/model/linear-call.d.ts +48 -0
  226. package/dist/taco/model/linear-call.js +58 -0
  227. package/dist/taco/model/new-nodes.d.ts +145 -0
  228. package/dist/taco/model/new-nodes.js +277 -0
  229. package/dist/taco/model/node-builder.d.ts +449 -0
  230. package/dist/taco/model/node-builder.js +2294 -0
  231. package/dist/taco/model/node-table-watch.d.ts +36 -0
  232. package/dist/taco/model/node-table-watch.js +63 -0
  233. package/dist/taco/model/node-transform.d.ts +39 -0
  234. package/dist/taco/model/node-transform.js +79 -0
  235. package/dist/taco/model/node-users-index.d.ts +10 -0
  236. package/dist/taco/model/node-users-index.js +82 -0
  237. package/dist/taco/model/operation-references.d.ts +80 -0
  238. package/dist/taco/model/operation-references.js +399 -0
  239. package/dist/taco/model/operations.d.ts +610 -0
  240. package/dist/taco/model/operations.js +2882 -0
  241. package/dist/taco/model/overlay-table.d.ts +71 -0
  242. package/dist/taco/model/overlay-table.js +171 -0
  243. package/dist/taco/model/override-remap.d.ts +69 -0
  244. package/dist/taco/model/override-remap.js +230 -0
  245. package/dist/taco/model/parent-table.d.ts +53 -0
  246. package/dist/taco/model/parent-table.js +193 -0
  247. package/dist/taco/model/problem-collector.d.ts +27 -0
  248. package/dist/taco/model/problem-collector.js +101 -0
  249. package/dist/taco/model/sha256.d.ts +10 -0
  250. package/dist/taco/model/sha256.js +79 -0
  251. package/dist/taco/model/shape-geometry.d.ts +96 -0
  252. package/dist/taco/model/shape-geometry.js +368 -0
  253. package/dist/taco/model/shared-node-table.d.ts +97 -0
  254. package/dist/taco/model/shared-node-table.js +546 -0
  255. package/dist/taco/model/slots.d.ts +113 -0
  256. package/dist/taco/model/slots.js +281 -0
  257. package/dist/taco/model/stroke-settings.d.ts +37 -0
  258. package/dist/taco/model/stroke-settings.js +90 -0
  259. package/dist/taco/model/svg-path-import.d.ts +89 -0
  260. package/dist/taco/model/svg-path-import.js +219 -0
  261. package/dist/taco/model/text-measurement.d.ts +142 -0
  262. package/dist/taco/model/text-measurement.js +846 -0
  263. package/dist/taco/model/text-reads.d.ts +66 -0
  264. package/dist/taco/model/text-reads.js +128 -0
  265. package/dist/taco/model/text-sizer.d.ts +358 -0
  266. package/dist/taco/model/text-sizer.js +996 -0
  267. package/dist/taco/model/theme-users.d.ts +59 -0
  268. package/dist/taco/model/theme-users.js +312 -0
  269. package/dist/taco/model/thumbnail.d.ts +15 -0
  270. package/dist/taco/model/thumbnail.js +34 -0
  271. package/dist/taco/model/types.d.ts +2369 -0
  272. package/dist/taco/model/types.js +366 -0
  273. package/dist/taco/model/unknown-property.d.ts +5 -0
  274. package/dist/taco/model/unknown-property.js +7 -0
  275. package/dist/taco/model/validated-documents.d.ts +22 -0
  276. package/dist/taco/model/validated-documents.js +22 -0
  277. package/dist/taco/model/variable-modes.d.ts +61 -0
  278. package/dist/taco/model/variable-modes.js +438 -0
  279. package/dist/taco/model/variable-references.d.ts +54 -0
  280. package/dist/taco/model/variable-references.js +183 -0
  281. package/dist/taco/model/variables.d.ts +24 -0
  282. package/dist/taco/model/variables.js +151 -0
  283. package/dist/taco/model/vector-network.d.ts +34 -0
  284. package/dist/taco/model/vector-network.js +411 -0
  285. package/dist/taco/svg-import/import-svg.d.ts +36 -0
  286. package/dist/taco/svg-import/import-svg.js +729 -0
  287. package/dist/taco/svg-import/index.d.ts +3 -0
  288. package/dist/taco/svg-import/index.js +3 -0
  289. package/dist/taco/svg-import/limits/limits.d.ts +79 -0
  290. package/dist/taco/svg-import/limits/limits.js +160 -0
  291. package/dist/taco/svg-import/paint/gradients.d.ts +64 -0
  292. package/dist/taco/svg-import/paint/gradients.js +429 -0
  293. package/dist/taco/svg-import/paint/paint.d.ts +32 -0
  294. package/dist/taco/svg-import/paint/paint.js +162 -0
  295. package/dist/taco/svg-import/paths/paths.d.ts +58 -0
  296. package/dist/taco/svg-import/paths/paths.js +205 -0
  297. package/dist/taco/svg-import/public-types.d.ts +279 -0
  298. package/dist/taco/svg-import/public-types.js +56 -0
  299. package/dist/taco/svg-import/report/report.d.ts +44 -0
  300. package/dist/taco/svg-import/report/report.js +79 -0
  301. package/dist/taco/svg-import/reuse/reuse.d.ts +99 -0
  302. package/dist/taco/svg-import/reuse/reuse.js +840 -0
  303. package/dist/taco/svg-import/shapes/shapes.d.ts +35 -0
  304. package/dist/taco/svg-import/shapes/shapes.js +386 -0
  305. package/dist/taco/svg-import/structure/effects.d.ts +26 -0
  306. package/dist/taco/svg-import/structure/effects.js +618 -0
  307. package/dist/taco/svg-import/structure/image.d.ts +24 -0
  308. package/dist/taco/svg-import/structure/image.js +495 -0
  309. package/dist/taco/svg-import/structure/walk.d.ts +85 -0
  310. package/dist/taco/svg-import/structure/walk.js +544 -0
  311. package/dist/taco/svg-import/style/color.d.ts +40 -0
  312. package/dist/taco/svg-import/style/color.js +275 -0
  313. package/dist/taco/svg-import/style/computed.d.ts +214 -0
  314. package/dist/taco/svg-import/style/computed.js +1534 -0
  315. package/dist/taco/svg-import/style/css.d.ts +127 -0
  316. package/dist/taco/svg-import/style/css.js +541 -0
  317. package/dist/taco/svg-import/style/media.d.ts +25 -0
  318. package/dist/taco/svg-import/style/media.js +307 -0
  319. package/dist/taco/svg-import/style/properties.d.ts +43 -0
  320. package/dist/taco/svg-import/style/properties.js +135 -0
  321. package/dist/taco/svg-import/style/selector-reach.d.ts +30 -0
  322. package/dist/taco/svg-import/style/selector-reach.js +169 -0
  323. package/dist/taco/svg-import/style/selector-validity.d.ts +14 -0
  324. package/dist/taco/svg-import/style/selector-validity.js +307 -0
  325. package/dist/taco/svg-import/text/text.d.ts +29 -0
  326. package/dist/taco/svg-import/text/text.js +545 -0
  327. package/dist/taco/svg-import/transform/matrix.d.ts +111 -0
  328. package/dist/taco/svg-import/transform/matrix.js +229 -0
  329. package/dist/taco/svg-import/tree/element-data.d.ts +52 -0
  330. package/dist/taco/svg-import/tree/element-data.js +155 -0
  331. package/dist/taco/svg-import/tree/elements.d.ts +36 -0
  332. package/dist/taco/svg-import/tree/elements.js +121 -0
  333. package/dist/taco/svg-import/units/length.d.ts +43 -0
  334. package/dist/taco/svg-import/units/length.js +125 -0
  335. package/dist/taco/svg-import/units/viewbox.d.ts +35 -0
  336. package/dist/taco/svg-import/units/viewbox.js +77 -0
  337. package/package.json +55 -4
@@ -0,0 +1,438 @@
1
+ import { deepFreeze } from "./codec.js";
2
+ import { getRequestedAutoSizedTextFrame } from "./text-measurement.js";
3
+ import { textMeasurementPaused } from "./text-reads.js";
4
+ import { isContainerNode, } from "./types.js";
5
+ import { findVariable, locatedVariableValue, nodeSupportsVariableProperty, variableSupportsProperty, } from "./variables.js";
6
+ import { entryOf } from "./id-table.js";
7
+ import { isFrozenNodeMap } from "./derivations.js";
8
+ import { overlayParts } from "./overlay-table.js";
9
+ import { parentMapOf } from "./parent-table.js";
10
+ // ---------------------------------------------------------------------------
11
+ // Inheritance
12
+ /**
13
+ * The modes a layer uses: its parent's modes with the layer's own choices on
14
+ * top. A collection the layer leaves out (Auto) keeps the parent's mode.
15
+ * Returns `parent` itself when `own` chooses nothing.
16
+ * @since 0.26.0
17
+ */
18
+ export function inheritVariableModes(parent, own) {
19
+ if (own === undefined || Object.keys(own).length === 0)
20
+ return parent;
21
+ if (parent === undefined)
22
+ return own;
23
+ return { ...parent, ...own };
24
+ }
25
+ /**
26
+ * The mode a collection shows under `modes`: the inherited choice, else the
27
+ * collection's `activeModeId`, else its `defaultModeId`.
28
+ * @since 0.26.0
29
+ */
30
+ export function variableModeFor(collectionId, collection, modes) {
31
+ const chosen = entryOf(modes, collectionId);
32
+ if (chosen !== undefined && entryOf(collection.modes, chosen) !== undefined)
33
+ return chosen;
34
+ return collection.activeModeId ?? collection.defaultModeId;
35
+ }
36
+ /**
37
+ * A stable text form of `modes` for cache keys: the collections in sorted
38
+ * order. Modes that match a collection's active mode are left out, so Auto
39
+ * and an explicit choice of the active mode give the same key.
40
+ * @since 0.26.0
41
+ */
42
+ export function variableModesKey(theme, modes) {
43
+ if (modes === undefined)
44
+ return "";
45
+ const collections = theme.variableCollections ?? {};
46
+ // JSON keeps IDs that hold separators such as `=` or `;` apart.
47
+ const entries = Object.keys(modes)
48
+ .sort()
49
+ .filter((collectionId) => {
50
+ const collection = entryOf(collections, collectionId);
51
+ return collection !== undefined
52
+ && variableModeFor(collectionId, collection, modes) !== (collection.activeModeId ?? collection.defaultModeId);
53
+ })
54
+ .map((collectionId) => [collectionId, entryOf(modes, collectionId)]);
55
+ return entries.length === 0 ? "" : JSON.stringify(entries);
56
+ }
57
+ const pageModeIndexes = new WeakMap();
58
+ /**
59
+ * The parent table of each node record that is not frozen, built once per
60
+ * record object as before: such a record is a working copy that is read
61
+ * many times while it is not written in between.
62
+ */
63
+ const unfrozenParentTables = new WeakMap();
64
+ /** The parent table of a node record: `parentMapOf`'s for a frozen record, else one built once per record object. */
65
+ function parentsOfRecord(nodes) {
66
+ if (isFrozenNodeMap(nodes))
67
+ return parentMapOf(nodes);
68
+ let parents = unfrozenParentTables.get(nodes);
69
+ if (parents === undefined) {
70
+ parents = parentMapOf(nodes);
71
+ unfrozenParentTables.set(nodes, parents);
72
+ }
73
+ return parents;
74
+ }
75
+ /** Whether `node` has the children list `before` has. */
76
+ function keepsChildList(node, before) {
77
+ const children = node !== undefined && isContainerNode(node) ? node.children : undefined;
78
+ const childrenBefore = before !== undefined && isContainerNode(before) ? before.children : undefined;
79
+ if (children === childrenBefore)
80
+ return true;
81
+ if (children === undefined || childrenBefore === undefined || children.length !== childrenBefore.length)
82
+ return false;
83
+ return children.every((childId, index) => childId === childrenBefore[index]);
84
+ }
85
+ /**
86
+ * For each overlay table read so far: how many of its writes were checked,
87
+ * and the written entries whose children list differs from the base's.
88
+ */
89
+ const childListChecks = new WeakMap();
90
+ /**
91
+ * Whether every entry written over an overlay table keeps the children list
92
+ * its base has, so no node changes parent. Only the writes since the last
93
+ * call are checked, so a pass that reads modes between its writes checks
94
+ * each write once.
95
+ */
96
+ function keepsEveryChildList(overlay) {
97
+ let check = childListChecks.get(overlay.written);
98
+ if (check === undefined) {
99
+ check = { checked: 0, changed: new Set() };
100
+ childListChecks.set(overlay.written, check);
101
+ }
102
+ const { writes, written, base } = overlay;
103
+ for (; check.checked < writes.length; check.checked += 1) {
104
+ const id = writes[check.checked];
105
+ if (keepsChildList(written.get(id), entryOf(base, id)))
106
+ check.changed.delete(id);
107
+ else
108
+ check.changed.add(id);
109
+ }
110
+ return check.changed.size === 0;
111
+ }
112
+ /**
113
+ * The parent table and the page modes of `document`. The parents are the
114
+ * table `parentMapOf` keeps for the node record, so a document an edit made
115
+ * reads the table derived from the one before it instead of reading every
116
+ * node. A working record written over a document's (`overlayTable`), as the
117
+ * layout passes and the component cascade use, has the document's parents
118
+ * while its writes keep every children list.
119
+ */
120
+ function treeIndex(document) {
121
+ const overlay = overlayParts(document.nodes);
122
+ const parents = overlay !== undefined && keepsEveryChildList(overlay)
123
+ ? parentsOfRecord(overlay.base)
124
+ : parentsOfRecord(document.nodes);
125
+ let pageModesByRoot = pageModeIndexes.get(document.pages);
126
+ if (pageModesByRoot === undefined) {
127
+ const modes = new Map();
128
+ for (const page of Object.values(document.pages))
129
+ modes.set(page.rootId, page.variableModes);
130
+ pageModesByRoot = modes;
131
+ pageModeIndexes.set(document.pages, modes);
132
+ }
133
+ return { parents, pageModesByRoot };
134
+ }
135
+ /**
136
+ * The modes in effect at a stored node: the page's modes, then each
137
+ * ancestor's, then the node's own. A layer of a component (outside any
138
+ * page) starts from the document's active modes at the component root; an
139
+ * instance applies its own modes on top when it is resolved. Undefined
140
+ * means every collection shows its active mode.
141
+ * @since 0.26.0
142
+ */
143
+ export function variableModesAt(document, nodeId) {
144
+ return inheritVariableModes(inheritedVariableModes(document, nodeId), entryOf(document.nodes, nodeId)?.variableModes);
145
+ }
146
+ /**
147
+ * The modes a stored node inherits: `variableModesAt` its parent, or the
148
+ * page's modes for a page root. The node's own choices are not included.
149
+ * @since 0.26.0
150
+ */
151
+ export function inheritedVariableModes(document, nodeId) {
152
+ const { parents, pageModesByRoot } = treeIndex(document);
153
+ const chain = [];
154
+ for (let current = parents.get(nodeId); current !== undefined; current = parents.get(current)) {
155
+ chain.push(current);
156
+ }
157
+ let modes = pageModesByRoot.get(chain.length === 0 ? nodeId : chain[chain.length - 1]);
158
+ for (let index = chain.length - 1; index >= 0; index -= 1) {
159
+ modes = inheritVariableModes(modes, entryOf(document.nodes, chain[index])?.variableModes);
160
+ }
161
+ return modes;
162
+ }
163
+ /**
164
+ * Whether a node's variable bindings read any collection in a mode other
165
+ * than its active mode under `modes`. Stored values are written for the
166
+ * active modes, so only such a node needs `applyVariableBindings`.
167
+ * @since 0.26.0
168
+ */
169
+ export function bindingsDependOnModes(theme, node, modes) {
170
+ if (modes === undefined || node.variableBindings === undefined)
171
+ return false;
172
+ for (const id of Object.values(node.variableBindings)) {
173
+ if (id === undefined)
174
+ continue;
175
+ const located = findVariable(theme, id);
176
+ if (located === undefined)
177
+ continue;
178
+ const { collectionId, collection } = located;
179
+ if (variableModeFor(collectionId, collection, modes) !== (collection.activeModeId ?? collection.defaultModeId)) {
180
+ return true;
181
+ }
182
+ }
183
+ return false;
184
+ }
185
+ // ---------------------------------------------------------------------------
186
+ // Writing variable values into fields
187
+ /** The fills and strokes a node paints, its own or its shared style's. */
188
+ function sharedStyle(theme, style) {
189
+ const shared = style?.styleId === undefined ? undefined : entryOf(theme.nodeStyles, style.styleId);
190
+ return { fills: style?.fills ?? shared?.fills, strokes: style?.strokes ?? shared?.strokes };
191
+ }
192
+ function recolorPaint(paint, color) {
193
+ if (paint.kind === "solid")
194
+ return { ...paint, color };
195
+ // A color variable cannot recolor an image paint.
196
+ if (paint.kind === "image")
197
+ return paint;
198
+ return { ...paint, stops: paint.stops.map((stop) => ({ ...stop, color })) };
199
+ }
200
+ /** A single painted side takes the width; custom sides all take it. */
201
+ function strokeWithWidth(stroke, width) {
202
+ const sides = stroke.sides;
203
+ if (sides === undefined)
204
+ return { ...stroke, width };
205
+ const painted = ["top", "right", "bottom", "left"].filter((side) => sides[side] > 0);
206
+ if (painted.length === 1) {
207
+ return { ...stroke, width, sides: { top: 0, right: 0, bottom: 0, left: 0, [painted[0]]: width } };
208
+ }
209
+ return { ...stroke, width, sides: { top: width, right: width, bottom: width, left: width } };
210
+ }
211
+ function strokeValue(stroke, property, value) {
212
+ if (property === "strokeColor" && typeof value === "string") {
213
+ return { ...stroke, paint: recolorPaint(stroke.paint, value) };
214
+ }
215
+ if (property === "strokeWidth" && typeof value === "number")
216
+ return strokeWithWidth(stroke, Math.max(0, value));
217
+ return stroke;
218
+ }
219
+ /**
220
+ * Writes one variable value into the node field it is bound to, the way the
221
+ * editor does when a variable is applied: a color drives the bottom fill or
222
+ * the first stroke, a radius sets every corner, a text property restyles
223
+ * every run. Sizes and opacity are clamped. A value of the wrong type
224
+ * changes nothing.
225
+ * @since 0.26.0
226
+ */
227
+ export function withVariableValue(theme, node, property, value) {
228
+ if (property === "visibility")
229
+ return typeof value === "boolean" ? { ...node, visible: value } : node;
230
+ if (property === "opacity") {
231
+ return typeof value === "number" ? { ...node, opacity: Math.min(1, Math.max(0, value)) } : node;
232
+ }
233
+ if (property === "width" || property === "height") {
234
+ if (typeof value !== "number" || !("frame" in node))
235
+ return node;
236
+ if (node.type === "connector") {
237
+ // As the editor's binding writer does: the endpoints scale with the frame.
238
+ const width = property === "width" ? Math.max(0, value) : node.frame.width;
239
+ const height = property === "height" ? Math.max(0, value) : node.frame.height;
240
+ const scaleX = node.frame.width === 0 ? 1 : width / node.frame.width;
241
+ const scaleY = node.frame.height === 0 ? 1 : height / node.frame.height;
242
+ return {
243
+ ...node,
244
+ frame: { ...node.frame, width, height },
245
+ start: {
246
+ ...node.start,
247
+ x: node.frame.width === 0 ? 0 : node.start.x * scaleX,
248
+ y: node.frame.height === 0 ? 0 : node.start.y * scaleY,
249
+ },
250
+ end: {
251
+ ...node.end,
252
+ x: node.frame.width === 0 ? width : node.end.x * scaleX,
253
+ y: node.frame.height === 0 ? height : node.end.y * scaleY,
254
+ },
255
+ };
256
+ }
257
+ return { ...node, frame: { ...node.frame, [property]: Math.max(0, value) } };
258
+ }
259
+ if (node.type === "shape" || node.type === "frame") {
260
+ const style = sharedStyle(theme, node.style);
261
+ if (property === "cornerRadius" && typeof value === "number") {
262
+ const { cornerRadii: _cornerRadii, ...rest } = node.style ?? {};
263
+ return { ...node, style: { ...rest, cornerRadius: Math.max(0, value) } };
264
+ }
265
+ if (property === "fillColor" && typeof value === "string") {
266
+ const fills = style.fills ?? [];
267
+ const bottom = fills[0];
268
+ return {
269
+ ...node,
270
+ style: {
271
+ ...node.style,
272
+ fills: bottom === undefined
273
+ ? [{ kind: "solid", color: value }, ...fills]
274
+ : [recolorPaint(bottom, value), ...fills.slice(1)],
275
+ },
276
+ };
277
+ }
278
+ const first = style.strokes?.[0];
279
+ if ((property === "strokeColor" || property === "strokeWidth") && first !== undefined) {
280
+ return {
281
+ ...node,
282
+ style: { ...node.style, strokes: [strokeValue(first, property, value), ...(style.strokes ?? []).slice(1)] },
283
+ };
284
+ }
285
+ }
286
+ if ((node.type === "connector" || (node.type === "code" && node.stroke !== undefined))
287
+ && (property === "strokeColor" || property === "strokeWidth")) {
288
+ return { ...node, stroke: strokeValue(node.stroke, property, value) };
289
+ }
290
+ if (node.type === "frame" && node.layout.kind !== "absolute" && typeof value === "number") {
291
+ const layout = node.layout;
292
+ if ((property === "gap" || property === "wrapGap") && layout.kind !== "grid") {
293
+ return { ...node, layout: { ...layout, [property]: value } };
294
+ }
295
+ if ((property === "columnGap" || property === "rowGap") && layout.kind === "grid") {
296
+ return { ...node, layout: { ...layout, [property]: value } };
297
+ }
298
+ const edge = { paddingTop: "top", paddingRight: "right", paddingBottom: "bottom", paddingLeft: "left" }[property];
299
+ if (edge !== undefined) {
300
+ return { ...node, layout: { ...layout, padding: { ...layout.padding, [edge]: Math.max(0, value) } } };
301
+ }
302
+ }
303
+ if (node.type === "text") {
304
+ const key = property === "textColor" ? "color" : property;
305
+ if (!["fontFamily", "fontSize", "fontWeight", "lineHeight", "letterSpacing", "color"].includes(key))
306
+ return node;
307
+ // Keep sizes, line heights and weights in the range the document accepts;
308
+ // a font weight is at least 1. The limits match the web app's
309
+ // `MIN_FONT_SIZE` and `MIN_LINE_HEIGHT`.
310
+ const minimum = key === "fontSize"
311
+ ? 1
312
+ : key === "lineHeight" ? 0.01 : key === "fontWeight" ? 1 : undefined;
313
+ const textValue = minimum !== undefined && typeof value === "number" ? Math.max(minimum, value) : value;
314
+ return {
315
+ ...node,
316
+ paragraphs: node.paragraphs.map((paragraph) => ({
317
+ ...paragraph,
318
+ runs: paragraph.runs.map((run) => ({ ...run, overrides: { ...run.overrides, [key]: textValue } })),
319
+ })),
320
+ };
321
+ }
322
+ if (node.type === "code") {
323
+ if (property === "fontFamily" && typeof value === "string")
324
+ return { ...node, fontFamily: value };
325
+ if (property === "fontSize" && typeof value === "number")
326
+ return { ...node, fontSize: Math.max(1, value) };
327
+ if ((property === "lineHeight" || property === "letterSpacing") && typeof value === "number") {
328
+ return {
329
+ ...node,
330
+ codeStyleOverrides: {
331
+ ...node.codeStyleOverrides,
332
+ [property]: property === "lineHeight" ? Math.max(0.01, value) : value,
333
+ },
334
+ };
335
+ }
336
+ }
337
+ return node;
338
+ }
339
+ /**
340
+ * Writes each of the node's variable bindings in the modes `modes` into
341
+ * the bound field (see `withVariableValue`). A binding to a missing
342
+ * variable, or one the node cannot take, is skipped. A text layer that
343
+ * sizes itself is measured again. Returns `node` itself when it has no
344
+ * bindings.
345
+ * @since 0.26.0
346
+ */
347
+ export function applyVariableBindings(document, node, modes) {
348
+ const bindings = node.variableBindings;
349
+ if (bindings === undefined)
350
+ return node;
351
+ const { theme } = document;
352
+ // A frozen node is bound the same way again for the same theme and modes,
353
+ // as every instance of a component binds its stored layers.
354
+ const memo = Object.isFrozen(node) ? boundNodeMemo(node, theme) : undefined;
355
+ const modesKey = modes ?? NO_MODES;
356
+ const known = memo?.get(modesKey);
357
+ if (known !== undefined)
358
+ return known;
359
+ const bound = bindNode(document, node, bindings, modes);
360
+ if (memo !== undefined && bound.memoizable) {
361
+ if (memo.size >= MAX_MODES_PER_NODE)
362
+ memo.clear();
363
+ memo.set(modesKey, bound.node);
364
+ }
365
+ return bound.node;
366
+ }
367
+ function bindNode(document, node, bindings, modes) {
368
+ const { theme } = document;
369
+ let next = node;
370
+ for (const [property, id] of Object.entries(bindings)) {
371
+ if (id === undefined)
372
+ continue;
373
+ const located = findVariable(theme, id);
374
+ const variableProperty = property;
375
+ if (located === undefined
376
+ || !variableSupportsProperty(located.variable, variableProperty)
377
+ || !nodeSupportsVariableProperty(next, variableProperty))
378
+ continue;
379
+ const value = locatedVariableValue(located, modes);
380
+ if (value === undefined)
381
+ continue;
382
+ next = withVariableValue(theme, next, variableProperty, value);
383
+ }
384
+ // Stored values are usually already written for these modes.
385
+ if (next === node || sameJsonValue(next, node))
386
+ return { node, memoizable: true };
387
+ // A measured size follows the text sizes, which the memo does not track.
388
+ if (next.type === "text" && next.autoResize !== "none") {
389
+ // A resolution without layout keeps the stored frame (`withoutTextMeasurement`).
390
+ if (textMeasurementPaused())
391
+ return { node: next, memoizable: false };
392
+ // Many texts can be bound at once, so the renderer is asked later, together; the estimate holds until then.
393
+ return { node: { ...next, frame: getRequestedAutoSizedTextFrame(document, next) }, memoizable: false };
394
+ }
395
+ return { node: deepFreeze(next), memoizable: true };
396
+ }
397
+ /** The key of `undefined` modes in a node's memo. */
398
+ const NO_MODES = Object.freeze({});
399
+ const MAX_MODES_PER_NODE = 8;
400
+ /**
401
+ * Bound copies of frozen nodes, by theme and then by the modes object. A
402
+ * node's bound fields read only the theme's variables and the modes, and the
403
+ * modes object a layer gets is the one its parent passes on unless the layer
404
+ * sets modes of its own, so the same object comes again.
405
+ */
406
+ const boundNodes = new WeakMap();
407
+ function boundNodeMemo(node, theme) {
408
+ const entry = boundNodes.get(node);
409
+ if (entry !== undefined && entry.theme === theme)
410
+ return entry.byModes;
411
+ const byModes = new Map();
412
+ boundNodes.set(node, { theme, byModes });
413
+ return byModes;
414
+ }
415
+ /**
416
+ * Whether two JSON values are equal as `canonicalJson` writes them: object
417
+ * keys in any order, and a key whose value is `undefined` the same as no key.
418
+ * Values shared by both sides are equal without being read, so a binding that
419
+ * rewrites one property compares only that property.
420
+ */
421
+ function sameJsonValue(a, b) {
422
+ if (a === b)
423
+ return true;
424
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
425
+ return false;
426
+ if (Array.isArray(a) || Array.isArray(b)) {
427
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
428
+ return false;
429
+ return a.every((entry, index) => sameJsonValue(entry, b[index]));
430
+ }
431
+ const left = a;
432
+ const right = b;
433
+ const definedKeys = (record) => Object.keys(record).filter((key) => record[key] !== undefined);
434
+ const keys = definedKeys(left);
435
+ if (keys.length !== definedKeys(right).length)
436
+ return false;
437
+ return keys.every((key) => Object.hasOwn(right, key) && sameJsonValue(left[key], right[key]));
438
+ }
@@ -0,0 +1,54 @@
1
+ import type { BuildValue } from "./node-builder.ts";
2
+ import type { DocumentTheme, SceneNode, VariableId, VariableProperty, VariableValue } from "./types.ts";
3
+ import { type LocatedVariable } from "./variables.ts";
4
+ /** The value `var('name')` reads as. */
5
+ export declare function variableReference(name: string): BuildValue;
6
+ /** Whether `value` is a `var('…')`. */
7
+ export declare function isVariableReference(value: unknown): value is {
8
+ readonly var: string;
9
+ };
10
+ /** Whether `value` holds a `var('…')` at any depth. */
11
+ export declare function holdsVariableReference(value: unknown, depth?: number): boolean;
12
+ /** A `var('…')` that names no variable, more than one, or one that does not fit where it is written. */
13
+ export declare class VariableReferenceError extends Error {
14
+ constructor(message: string);
15
+ }
16
+ /**
17
+ * The properties an argument of a layer of `kind` (its model type, as `text`) binds when it is written as
18
+ * `var('…')`, or undefined when it takes no variable.
19
+ */
20
+ export declare function variableArgumentProperties(kind: string, argument: string): readonly VariableProperty[] | undefined;
21
+ /** The arguments of `names` (a shorthand's arguments and model fields) that take a variable, for a refusal. */
22
+ export declare function variableArgumentsOf(kind: string, names: readonly string[]): string[];
23
+ /** `var('name')` as the tool spelling writes it. */
24
+ export declare const variableCall: (name: string) => string;
25
+ /**
26
+ * The variable `name` gives in `theme`. Refuses a name of no variable, listing variables with a like name, and a name
27
+ * of several, listing the form that names each.
28
+ */
29
+ export declare function variableNamed(theme: DocumentTheme, name: string, properties?: readonly VariableProperty[]): LocatedVariable;
30
+ /**
31
+ * The name `var('…')` writes for the variable `id`: its name when that names it alone, else its collection's name, `/`
32
+ * and its name when that does; undefined when neither does, the document has no such variable, or the name holds a
33
+ * backslash, which the layer syntax cannot write (the binding then prints by its id).
34
+ */
35
+ export declare function variableNameFor(theme: DocumentTheme, id: string): string | undefined;
36
+ /** A variable read for an argument: the value it writes and the properties it binds. */
37
+ export interface VariableArgument {
38
+ readonly value: VariableValue;
39
+ readonly variableId: VariableId;
40
+ readonly properties: readonly VariableProperty[];
41
+ }
42
+ /**
43
+ * Reads `var('name')` written for `argument` of a layer of `kind` (`properties` when it is a key of variableBindings):
44
+ * refuses an argument that takes no variable, a name of no variable or of several, and a variable whose type or
45
+ * scopes do not fit the property.
46
+ */
47
+ export declare function readVariableArgument(theme: DocumentTheme, kind: string, argument: string, name: string, properties?: readonly VariableProperty[] | undefined): VariableArgument;
48
+ /** The property names a key of variableBindings may be. */
49
+ export declare function isVariableProperty(key: string): key is VariableProperty;
50
+ /**
51
+ * Binds `bindings` on `node` and writes each bound variable's value in its active mode into the field it drives, as
52
+ * the editor does when a variable is applied (`withVariableValue`). Refuses a property the layer cannot bind.
53
+ */
54
+ export declare function withBoundVariables(theme: DocumentTheme, node: SceneNode, bindings: ReadonlyMap<VariableProperty, VariableArgument>): SceneNode;
@@ -0,0 +1,183 @@
1
+ import { findVariable, locatedVariableValue, nodeSupportsVariableProperty, VARIABLE_PROPERTY_TYPES } from "./variables.js";
2
+ import { withVariableValue } from "./variable-modes.js";
3
+ /*
4
+ * `var('brand/primary')` in the layer syntax: a value that names one of the document's variables. Written as an
5
+ * argument that drives a bindable property (`fill:var('brand/primary')`, `gap:var('space/m')`), it writes the
6
+ * variable's value in its collection's active mode (the value the document stores for a bound field) and binds the
7
+ * property to the variable, in `variableBindings`, by the variable's id. Inside `variableBindings:{fillColor:var(...)}`
8
+ * it binds the property named by the key. A variable is named by its name, or by its collection's name, `/` and its
9
+ * name where two collections hold a variable of that name.
10
+ */
11
+ /** A `var('…')` the reader made; told apart from an object value by this set, not by its shape. */
12
+ const REFERENCES = new WeakSet();
13
+ /** The value `var('name')` reads as. */
14
+ export function variableReference(name) {
15
+ const reference = Object.freeze({ var: name });
16
+ REFERENCES.add(reference);
17
+ return reference;
18
+ }
19
+ /** Whether `value` is a `var('…')`. */
20
+ export function isVariableReference(value) {
21
+ return typeof value === "object" && value !== null && REFERENCES.has(value);
22
+ }
23
+ /** Whether `value` holds a `var('…')` at any depth. */
24
+ export function holdsVariableReference(value, depth = 0) {
25
+ if (depth > 64)
26
+ throw new VariableReferenceError("a value is nested more than 64 deep.");
27
+ if (isVariableReference(value))
28
+ return true;
29
+ if (Array.isArray(value))
30
+ return value.some((item) => holdsVariableReference(item, depth + 1));
31
+ if (typeof value === "object" && value !== null)
32
+ return Object.values(value).some((item) => holdsVariableReference(item, depth + 1));
33
+ return false;
34
+ }
35
+ /** A `var('…')` that names no variable, more than one, or one that does not fit where it is written. */
36
+ export class VariableReferenceError extends Error {
37
+ constructor(message) {
38
+ super(message);
39
+ this.name = "VariableReferenceError";
40
+ }
41
+ }
42
+ /** The arguments that take a variable, by shorthand kind, and the properties each binds. */
43
+ const COMMON_ARGUMENTS = {
44
+ fill: ["fillColor"], stroke: ["strokeColor"], radius: ["cornerRadius"], gap: ["gap"],
45
+ pad: ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"], opacity: ["opacity"], w: ["width"], h: ["height"], visible: ["visibility"],
46
+ };
47
+ const TEXT_ARGUMENTS = {
48
+ color: ["textColor"], size: ["fontSize"], weight: ["fontWeight"], font: ["fontFamily"],
49
+ };
50
+ const CODE_ARGUMENTS = { size: ["fontSize"], font: ["fontFamily"] };
51
+ /**
52
+ * The properties an argument of a layer of `kind` (its model type, as `text`) binds when it is written as
53
+ * `var('…')`, or undefined when it takes no variable.
54
+ */
55
+ export function variableArgumentProperties(kind, argument) {
56
+ const own = kind === "text" ? TEXT_ARGUMENTS : kind === "code" ? CODE_ARGUMENTS : {};
57
+ return Object.hasOwn(own, argument) ? own[argument] : Object.hasOwn(COMMON_ARGUMENTS, argument) ? COMMON_ARGUMENTS[argument] : undefined;
58
+ }
59
+ /** The arguments of `names` (a shorthand's arguments and model fields) that take a variable, for a refusal. */
60
+ export function variableArgumentsOf(kind, names) {
61
+ return names.filter((name) => variableArgumentProperties(kind, name) !== undefined);
62
+ }
63
+ const quoted = (name) => `'${name.replaceAll("'", "''")}'`;
64
+ /** `var('name')` as the tool spelling writes it. */
65
+ export const variableCall = (name) => `var(${quoted(name)})`;
66
+ const LISTED = 8;
67
+ function namedVariables(theme) {
68
+ const all = [];
69
+ for (const [collectionId, collection] of Object.entries(theme.variableCollections ?? {})) {
70
+ for (const [variableId, variable] of Object.entries(collection.variables)) {
71
+ all.push({ collectionId, collection, variableId: variableId, variable, qualified: `${collection.name}/${variable.name}` });
72
+ }
73
+ }
74
+ return all;
75
+ }
76
+ /** The variables a name gives: those of that name, or else those whose collection's name, `/` and name it is. */
77
+ function variablesNamed(all, name) {
78
+ const exact = all.filter((entry) => entry.variable.name === name);
79
+ return exact.length > 0 ? exact : all.filter((entry) => entry.qualified === name);
80
+ }
81
+ /**
82
+ * The variable `name` gives in `theme`. Refuses a name of no variable, listing variables with a like name, and a name
83
+ * of several, listing the form that names each.
84
+ */
85
+ export function variableNamed(theme, name, properties = []) {
86
+ const all = namedVariables(theme);
87
+ // A variable var('…') cannot name is written by its id, bound to the properties the argument drives.
88
+ // An id with a backslash cannot be written either: the variable is named by its id for apply_changes instead.
89
+ const byId = (id) => id.includes("\\") ? `the variable ${JSON.stringify(id)}, which the layer syntax cannot name (bind it by that id with apply_changes)`
90
+ : `variableBindings:{${(properties.length === 0 ? ["<property>"] : properties).map((property) => `${property}:${quoted(id)}`).join(", ")}}`;
91
+ const found = variablesNamed(all, name);
92
+ if (found.length === 1)
93
+ return found[0];
94
+ if (found.length > 1) {
95
+ const forms = found.map((entry) => {
96
+ const form = variableNameFor(theme, entry.variableId);
97
+ return form === undefined ? `${byId(entry.variableId)} (${`${entry.collection.name}/${entry.variable.name}`.includes("\\")
98
+ ? "its name holds a backslash, which var('…') cannot write" : `two collections are called ${quoted(entry.collection.name)}`})` : variableCall(form);
99
+ });
100
+ throw new VariableReferenceError(`${found.length} variables are named ${quoted(name)}, in ${[...new Set(found.map((entry) => quoted(entry.collection.name)))].join(" and ")}: `
101
+ + `write the collection's name first, as ${forms.join(" or ")}.`);
102
+ }
103
+ if (all.length === 0)
104
+ throw new VariableReferenceError(`There is no variable ${quoted(name)}: the document has no variables.`);
105
+ const words = name.toLowerCase().split(/[/\s]+/).filter((word) => word !== "");
106
+ const like = all.filter((entry) => words.some((word) => entry.qualified.toLowerCase().includes(word)));
107
+ const shown = (like.length > 0 ? like : all).slice(0, LISTED).map((entry) => {
108
+ // A name var('…') cannot write (a backslash, or no form names it alone) is suggested by its id, so a pasted
109
+ // suggestion is always valid syntax.
110
+ const form = variableNameFor(theme, entry.variableId);
111
+ return form === undefined ? byId(entry.variableId) : variableCall(form);
112
+ });
113
+ const more = (like.length > 0 ? like : all).length - shown.length;
114
+ throw new VariableReferenceError(`There is no variable ${quoted(name)}. ${like.length > 0 ? "Variables with a name like it" : "Variables of the document"}: `
115
+ + `${shown.join(", ")}${more > 0 ? ` and ${more} more` : ""}.`);
116
+ }
117
+ /**
118
+ * The name `var('…')` writes for the variable `id`: its name when that names it alone, else its collection's name, `/`
119
+ * and its name when that does; undefined when neither does, the document has no such variable, or the name holds a
120
+ * backslash, which the layer syntax cannot write (the binding then prints by its id).
121
+ */
122
+ export function variableNameFor(theme, id) {
123
+ const located = findVariable(theme, id);
124
+ if (located === undefined)
125
+ return undefined;
126
+ const all = namedVariables(theme);
127
+ for (const form of [located.variable.name, `${located.collection.name}/${located.variable.name}`]) {
128
+ if (form.includes("\\"))
129
+ continue;
130
+ const found = variablesNamed(all, form);
131
+ if (found.length === 1 && found[0].variableId === id)
132
+ return form;
133
+ }
134
+ return undefined;
135
+ }
136
+ /**
137
+ * Reads `var('name')` written for `argument` of a layer of `kind` (`properties` when it is a key of variableBindings):
138
+ * refuses an argument that takes no variable, a name of no variable or of several, and a variable whose type or
139
+ * scopes do not fit the property.
140
+ */
141
+ export function readVariableArgument(theme, kind, argument, name, properties = variableArgumentProperties(kind, argument)) {
142
+ if (properties === undefined) {
143
+ const takes = variableArgumentsOf(kind, [...Object.keys(COMMON_ARGUMENTS), ...Object.keys(kind === "text" ? TEXT_ARGUMENTS : kind === "code" ? CODE_ARGUMENTS : {})]);
144
+ throw new VariableReferenceError(`${argument} takes no variable. A ${kind} binds one in ${[...new Set(takes)].join(", ")} `
145
+ + `(as fill:${variableCall(name)}), or any property in variableBindings:{<property>:${variableCall(name)}}.`);
146
+ }
147
+ const located = variableNamed(theme, name, properties);
148
+ const { variable } = located;
149
+ for (const property of properties) {
150
+ const wanted = VARIABLE_PROPERTY_TYPES[property];
151
+ if (variable.type !== wanted) {
152
+ throw new VariableReferenceError(`${variableCall(name)} is a ${variable.type} variable, and ${argument} takes a ${wanted} one.`);
153
+ }
154
+ if (variable.scopes !== undefined && !variable.scopes.includes(property)) {
155
+ throw new VariableReferenceError(`${variableCall(name)} is not for ${property}: it is scoped to ${variable.scopes.join(", ") || "nothing"}.`);
156
+ }
157
+ }
158
+ const value = locatedVariableValue(located);
159
+ if (value === undefined)
160
+ throw new VariableReferenceError(`${variableCall(name)} has no value in its collection's active mode.`);
161
+ return { value, variableId: located.variableId, properties };
162
+ }
163
+ /** The property names a key of variableBindings may be. */
164
+ export function isVariableProperty(key) {
165
+ return Object.hasOwn(VARIABLE_PROPERTY_TYPES, key);
166
+ }
167
+ /**
168
+ * Binds `bindings` on `node` and writes each bound variable's value in its active mode into the field it drives, as
169
+ * the editor does when a variable is applied (`withVariableValue`). Refuses a property the layer cannot bind.
170
+ */
171
+ export function withBoundVariables(theme, node, bindings) {
172
+ if (bindings.size === 0)
173
+ return node;
174
+ let next = { ...node, variableBindings: { ...node.variableBindings } };
175
+ for (const [property, bound] of bindings) {
176
+ if (!nodeSupportsVariableProperty(next, property)) {
177
+ throw new VariableReferenceError(`a ${next.type === "shape" ? next.shape : next.type} cannot bind ${property} to a variable.`);
178
+ }
179
+ next = { ...next, variableBindings: { ...next.variableBindings, [property]: bound.variableId } };
180
+ next = withVariableValue(theme, next, property, bound.value);
181
+ }
182
+ return next;
183
+ }