@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,769 @@
1
+ import { nodeSupportsVariableProperty, VARIABLE_PROPERTY_TYPES, variablePropertiesOfField, } from "../../model/index.js";
2
+ import { field, guidText, isObject } from "./fields.js";
3
+ import { hexColor, readNumbers } from "./converters/shared.js";
4
+ import { fontStyleName } from '@moondraft/editor/core';
5
+ import { fontStyleWeight } from "./converters/text.js";
6
+ import { styleBackedList } from "./styles.js";
7
+ /** Most aliases followed to resolve one value; a longer chain is reported, so a crafted chain cannot overflow the stack. */
8
+ const MAX_ALIAS_CHAIN = 64;
9
+ const TYPES = { COLOR: "color", FLOAT: "number", STRING: "string", BOOLEAN: "boolean" };
10
+ /** Whether Figma `scopes` limit a number variable to layer or color opacity, both of which Figma holds as a percentage. */
11
+ const opacityOnly = (scopes) => scopes.length > 0 && scopes.every((scope) => scope === "OPACITY" || scope === "COLOR_OPACITY");
12
+ /** Reads `ref` (`{guid}` or `{assetRef: {key}}`) as a lookup key: `guid:1:2` or `key:<key>`; undefined when it is neither. */
13
+ function refKey(ref, where) {
14
+ if (!isObject(ref))
15
+ return undefined;
16
+ if (ref["guid"] !== undefined)
17
+ return `guid:${guidText(ref["guid"], where)}`;
18
+ const asset = field(ref, "assetRef", "object", where);
19
+ const key = asset && field(asset, "key", "string", `${where} assetRef`);
20
+ return key === undefined || key === "" ? undefined : `key:${key}`;
21
+ }
22
+ /** Figma's fractional `sortPosition` order; a missing position sorts last, keeping message order. */
23
+ function bySortPosition(items, position) {
24
+ return items.map((item, index) => ({ item, index, at: position(item) }))
25
+ .sort((a, b) => a.at === b.at ? a.index - b.index : a.at === undefined ? 1 : b.at === undefined ? -1 : a.at < b.at ? -1 : 1)
26
+ .map(({ item }) => item);
27
+ }
28
+ const quoted = (text) => JSON.stringify(text);
29
+ // Parsing callbacks belong to the read stage. The returned variable lookups must
30
+ // not retain the walk's report callback (and with it the decoded file and all its caches).
31
+ function leaveOutVariable(known, node, report, why) {
32
+ known.set(node, { missing: `the variable ${quoted(node.name)} is not imported: ${why}` });
33
+ report(node, "node-left-out", `the variable is not imported: ${why}`);
34
+ }
35
+ /**
36
+ * Every `VARIABLE_SET` of the message as a collection, its modes in Figma's order (the first is the default), and
37
+ * every `VARIABLE` in it with a value for each mode. A set or variable Figma marks deleted (`isSoftDeleted`) is left
38
+ * out, as is a variable whose set is not in the message or whose type Taco lacks; each is reported. Taco variables
39
+ * hold no aliases, so an alias takes the value it resolves to: in the same mode within its own collection, else in
40
+ * the other collection's default mode. A mode without a value takes the default mode's. Without `keepAliases`, two
41
+ * collections of one name get a number, so that `var('collection/name')` can tell them apart; with it, each keeps
42
+ * its Figma name. A number variable scoped to opacity alone (layer
43
+ * or color opacity) holds Figma's percentage, so it is imported divided by 100, on Taco's 0 to 1 scale. Ids come from
44
+ * `newId`.
45
+ * @param nodes - Source nodes in file order.
46
+ * @param newId - Allocates local identifiers.
47
+ * @param report - Receives import diagnostics.
48
+ * @param keepAliases - Retain source keys and direct alias targets for native file records.
49
+ * @returns Variable definitions and lookup functions.
50
+ */
51
+ export function readFigmaVariables(nodes, newId, report, keepAliases = false) {
52
+ const sources = new Map();
53
+ const pendingAliases = [];
54
+ const aliases = new Map();
55
+ const sets = [];
56
+ const variables = [];
57
+ const byId = new Map();
58
+ for (const node of nodes) {
59
+ byId.set(node.id, node);
60
+ if (node.type === "VARIABLE_SET")
61
+ sets.push(node);
62
+ else if (node.type === "VARIABLE")
63
+ variables.push(node);
64
+ }
65
+ const deleted = (node) => field(node.change, "isSoftDeleted", "boolean", `node ${node.id}`) === true;
66
+ // Each set and variable under its guid and its library key.
67
+ const setsByKey = new Map();
68
+ const figmaVariables = new Map();
69
+ const collections = {};
70
+ const names = new Set();
71
+ // Each collection's variables, filled in place: copying the record once per variable would be quadratic.
72
+ const setVariables = new Map();
73
+ for (const node of sets) {
74
+ const where = `node ${node.id}`;
75
+ const key = field(node.change, "key", "string", where);
76
+ const keys = [`guid:${node.id}`, ...(key ? [`key:${key}`] : [])];
77
+ if (deleted(node)) {
78
+ report(node, "node-left-out", "the variable collection is deleted in Figma; it and its variables are not imported");
79
+ for (const at of keys)
80
+ setsByKey.set(at, `its collection ${quoted(node.name)} is deleted in Figma`);
81
+ continue;
82
+ }
83
+ const listed = (field(node.change, "variableSetModes", "list", where) ?? []).filter(isObject);
84
+ const modes = bySortPosition(listed, (mode) => field(mode, "sortPosition", "string", `${where} variableSetModes`))
85
+ .map((mode) => ({ figma: guidText(mode["id"], `${where} variableSetModes id`), name: field(mode, "name", "string", `${where} variableSetModes`) ?? "" }));
86
+ if (modes.length === 0) {
87
+ report(node, "node-left-out", "the variable collection has no modes; it and its variables are not imported");
88
+ for (const at of keys)
89
+ setsByKey.set(at, `its collection ${quoted(node.name)} has no modes`);
90
+ continue;
91
+ }
92
+ const id = newId();
93
+ if (keepAliases)
94
+ sources.set(id, node);
95
+ setVariables.set(id, {});
96
+ const modeNames = new Set();
97
+ const namedModes = [];
98
+ for (const [index, mode] of modes.entries()) {
99
+ const base = mode.name || `Mode ${String(index + 1)}`;
100
+ let name = base;
101
+ if (keepAliases) {
102
+ for (let i = 2; modeNames.has(name); i++)
103
+ name = base + " " + String(i);
104
+ if (name !== base)
105
+ report(node, "approximated", `variable mode renamed from ${quoted(base)} to ${quoted(name)}`);
106
+ modeNames.add(name);
107
+ }
108
+ namedModes.push({ ...mode, id: newId(), name });
109
+ }
110
+ const set = { node, id, modes: namedModes };
111
+ for (const at of keys)
112
+ setsByKey.set(at, set);
113
+ const base = node.name || "Collection";
114
+ let name = base;
115
+ // Native file records name collections by id, as Figma does, so only the literal reader numbers a repeated name.
116
+ if (!keepAliases)
117
+ for (let seen = 2; names.has(name); seen++)
118
+ name = `${base} ${String(seen)}`;
119
+ names.add(name);
120
+ if (name !== base)
121
+ report(node, "approximated", `the variable collection is imported as ${quoted(name)}: another collection is named ${quoted(base)}`);
122
+ collections[id] = {
123
+ name, defaultModeId: set.modes[0].id, modeOrder: set.modes.map((mode) => mode.id),
124
+ modes: Object.fromEntries(set.modes.map((mode) => [mode.id, { name: mode.name }])), variables: setVariables.get(id),
125
+ };
126
+ }
127
+ for (const node of variables) {
128
+ figmaVariables.set(`guid:${node.id}`, node);
129
+ const key = field(node.change, "key", "string", `node ${node.id}`);
130
+ if (key)
131
+ figmaVariables.set(`key:${key}`, node);
132
+ }
133
+ const setOf = (node) => {
134
+ const at = refKey(node.change["variableSetID"], `node ${node.id} variableSetID`);
135
+ const set = at === undefined ? undefined : setsByKey.get(at);
136
+ return set ?? "its collection is not in the message";
137
+ };
138
+ // The value of `data` in Figma mode `mode` of `set`, following at most `MAX_ALIAS_CHAIN` aliases; `seen` holds the
139
+ // variables on the way.
140
+ const valueOf = (data, type, set, mode, seen, where, aliases) => {
141
+ if (!isObject(data))
142
+ return { reason: "no value" };
143
+ const dataType = field(data, "dataType", "string", where);
144
+ const value = field(data, "value", "object", where) ?? {};
145
+ if (dataType === "ALIAS") {
146
+ const at = refKey(value["alias"], `${where} alias`);
147
+ const target = at === undefined ? undefined : figmaVariables.get(at);
148
+ if (target === undefined)
149
+ return { reason: "an alias of a variable that is not in the message" };
150
+ if (seen.has(target))
151
+ return { reason: "an alias that leads back to itself" };
152
+ if (aliases.length >= MAX_ALIAS_CHAIN)
153
+ return { reason: `an alias chain longer than ${String(MAX_ALIAS_CHAIN)} variables` };
154
+ const targetSet = setOf(target);
155
+ if (typeof targetSet === "string")
156
+ return { reason: `an alias of ${quoted(target.name)}, whose collection is not imported` };
157
+ const targetMode = targetSet === set ? mode : targetSet.modes[0].figma;
158
+ aliases.push(target.name);
159
+ return valueOf(valuesOf(target).get(targetMode), type, targetSet, targetMode, seen.add(target), `node ${target.id} variableDataValues`, aliases);
160
+ }
161
+ const read = dataType === "COLOR" && type === "color"
162
+ ? (isObject(value["colorValue"]) ? readNumbers(value["colorValue"], ["r", "g", "b", "a"], `${where} colorValue`) : null)
163
+ : undefined;
164
+ if (read !== undefined)
165
+ return read === null ? { reason: "a colour without channels" } : { value: hexColor(read) };
166
+ const plain = dataType === "FLOAT" && type === "number" ? field(value, "floatValue", "number", where)
167
+ : dataType === "STRING" && type === "string" ? field(value, "textValue", "string", where)
168
+ : dataType === "BOOLEAN" && type === "boolean" ? field(value, "boolValue", "boolean", where)
169
+ : null;
170
+ if (plain === null)
171
+ return { reason: `a ${dataType ?? "typeless"} value, which a ${type} variable cannot hold` };
172
+ return plain === undefined ? { reason: `a ${dataType} value without a value` } : { value: plain };
173
+ };
174
+ const valuesCache = new Map();
175
+ const valuesOf = (node) => {
176
+ let values = valuesCache.get(node);
177
+ if (values === undefined) {
178
+ const where = `node ${node.id} variableDataValues`;
179
+ const entries = field(field(node.change, "variableDataValues", "object", where) ?? {}, "entries", "list", where) ?? [];
180
+ values = new Map(entries.filter(isObject).map((entry) => [guidText(entry["modeID"], `${where} modeID`), entry["variableData"]]));
181
+ valuesCache.set(node, values);
182
+ }
183
+ return values;
184
+ };
185
+ const known = new Map();
186
+ let scoped;
187
+ for (const node of bySortPosition(variables, (variable) => field(variable.change, "sortPosition", "string", `node ${variable.id}`))) {
188
+ const where = `node ${node.id}`;
189
+ if (deleted(node)) {
190
+ known.set(node, { missing: `the variable ${quoted(node.name)} is deleted in Figma` });
191
+ report(node, "node-left-out", "the variable is deleted in Figma; it is not imported");
192
+ continue;
193
+ }
194
+ const set = setOf(node);
195
+ if (typeof set === "string") {
196
+ leaveOutVariable(known, node, report, set);
197
+ continue;
198
+ }
199
+ const figmaType = field(node.change, "variableResolvedType", "string", where);
200
+ const type = figmaType === undefined || !Object.hasOwn(TYPES, figmaType) ? undefined : TYPES[figmaType];
201
+ if (type === undefined) {
202
+ leaveOutVariable(known, node, report, `Taco variables have no ${figmaType ?? "typeless"} type`);
203
+ continue;
204
+ }
205
+ const resolved = set.modes.map((mode) => {
206
+ const aliases = [];
207
+ return { mode, aliases, ...valueOf(valuesOf(node).get(mode.figma), type, set, mode.figma, new Set([node]), `${where} variableDataValues`, aliases) };
208
+ });
209
+ const fallback = resolved[0].value !== undefined ? resolved[0] : resolved.find((entry) => entry.value !== undefined);
210
+ if (fallback?.value === undefined) {
211
+ leaveOutVariable(known, node, report, `no mode has a value Taco can hold (${resolved.map(({ mode, reason }) => `${quoted(mode.name)}: ${reason ?? ""}`).join(", ")})`);
212
+ continue;
213
+ }
214
+ const scopes = field(node.change, "variableScopes", "list", where) ?? [];
215
+ const opacity = type === "number" && opacityOnly(scopes);
216
+ const values = Object.fromEntries(resolved.map((entry) => {
217
+ const value = entry.value ?? fallback.value;
218
+ return [entry.mode.id, opacity && typeof value === "number" ? value / 100 : value];
219
+ }));
220
+ const filled = resolved.filter((entry) => entry.value === undefined);
221
+ if (filled.length > 0) {
222
+ report(node, "approximated", `the variable takes its ${quoted(fallback.mode.name)} value in ${filled.map(({ mode, reason }) => `${quoted(mode.name)} (${reason ?? ""})`).join(", ")}`);
223
+ }
224
+ const aliased = resolved.filter((entry) => entry.value !== undefined && entry.aliases.length > 0);
225
+ if (!keepAliases && aliased.length > 0) {
226
+ report(node, "approximated", `aliases are imported as the values they resolve to, so the variable no longer follows them: ${aliased.map(({ mode, aliases }) => `${quoted(mode.name)} → ${aliases.map(quoted).join(" → ")}`).join(", ")}`);
227
+ }
228
+ if (!keepAliases && scopes.some((scope) => scope !== "ALL_SCOPES"))
229
+ scoped = { node: scoped?.node ?? node, count: (scoped?.count ?? 0) + 1 };
230
+ const id = newId();
231
+ if (keepAliases) {
232
+ sources.set(id, node);
233
+ for (const entry of resolved) {
234
+ const chosen = entry.value === undefined ? fallback : entry;
235
+ if (!chosen.aliases.length)
236
+ continue;
237
+ const data = valuesOf(node).get(chosen.mode.figma);
238
+ const target = figmaVariables.get(refKey(data.value.alias, where));
239
+ pendingAliases.push({ source: node, id, mode: entry.mode.id, target: target });
240
+ }
241
+ }
242
+ const variable = { name: node.name || "Variable", type, values };
243
+ setVariables.get(set.id)[id] = variable;
244
+ known.set(node, opacity ? { id, name: variable.name, type, opacity } : { id, name: variable.name, type });
245
+ }
246
+ function reaches(start, end) {
247
+ const seen = new Set(), pending = [start];
248
+ while (pending.length) {
249
+ const id = pending.pop();
250
+ if (id === end)
251
+ return true;
252
+ if (seen.has(id))
253
+ continue;
254
+ seen.add(id);
255
+ for (const target of aliases.get(id)?.values() ?? [])
256
+ pending.push(target);
257
+ }
258
+ return false;
259
+ }
260
+ for (const { source, id, mode, target } of pendingAliases) {
261
+ const from = known.get(source), to = known.get(target);
262
+ if ("id" in from && "id" in to && from.type === to.type && from.opacity === to.opacity) {
263
+ if (reaches(to.id, id)) {
264
+ report(source, "approximated", "variable alias cycle across modes kept as a literal");
265
+ continue;
266
+ }
267
+ const modes = aliases.get(id) ?? new Map();
268
+ modes.set(mode, to.id);
269
+ aliases.set(id, modes);
270
+ }
271
+ else
272
+ report(source, "approximated", "the variable alias keeps its literal because its target is missing or uses different units");
273
+ }
274
+ if (scoped !== undefined) {
275
+ report(scoped.node, "property-left-out", `Figma variable scopes are not imported: ${String(scoped.count)} scoped variable${scoped.count === 1 ? " is" : "s are"} offered for every property of ${scoped.count === 1 ? "its" : "their"} type, first this one`);
276
+ }
277
+ // The value of the variable an `ALIAS` binding `data` of layer `figma` names, in the mode the layer uses (`fontStyleOf`).
278
+ const valueAt = (data, type, figma, where, shownBy) => {
279
+ if (!isObject(data) || field(data, "dataType", "string", where) !== "ALIAS")
280
+ return { missing: "the binding names no variable" };
281
+ const at = refKey((field(data, "value", "object", where) ?? {})["alias"], `${where} alias`);
282
+ const target = at === undefined ? undefined : figmaVariables.get(at);
283
+ if (target === undefined)
284
+ return { missing: "the variable is not in the message" };
285
+ const set = setOf(target);
286
+ if (typeof set === "string")
287
+ return { missing: `the variable ${quoted(target.name)} is not imported: ${set}` };
288
+ let mode = set.modes[0].figma;
289
+ const parentOf = (node) => node.parentId === undefined ? undefined : byId.get(node.parentId);
290
+ const chain = [];
291
+ for (let node = figma; node !== undefined;) {
292
+ if (shownBy !== undefined && node.id === shownBy.symbol.id) {
293
+ chain.push(shownBy.instance, node);
294
+ node = parentOf(shownBy.instance);
295
+ }
296
+ else {
297
+ chain.push(node);
298
+ node = parentOf(node);
299
+ }
300
+ }
301
+ chosen: for (const node of chain) {
302
+ const at = `node ${node.id} variableModeBySetMap`;
303
+ const modes = shownBy?.modes?.get(node.id) ?? node.change["variableModeBySetMap"];
304
+ for (const entry of field(field({ modes }, "modes", "object", at) ?? {}, "entries", "list", at) ?? []) {
305
+ if (!isObject(entry))
306
+ continue;
307
+ const key = refKey(entry["variableSetID"], `${at} variableSetID`);
308
+ if (key === undefined || setsByKey.get(key) !== set)
309
+ continue;
310
+ const id = guidText(entry["variableModeID"], `${at} variableModeID`);
311
+ if (set.modes.some((candidate) => candidate.figma === id)) {
312
+ mode = id;
313
+ break chosen;
314
+ }
315
+ }
316
+ }
317
+ return { ...valueOf(valuesOf(target).get(mode), type, set, mode, new Set([target]), `node ${target.id} variableDataValues`, []), variable: target.name };
318
+ };
319
+ return {
320
+ collections, sources, aliases,
321
+ valuesMatch(id, accepts) {
322
+ if (!keepAliases)
323
+ return true;
324
+ const pending = [[id, undefined]];
325
+ const seen = new Set();
326
+ while (pending.length) {
327
+ const [key, mode] = pending.pop();
328
+ const visit = key + "/" + (mode ?? "*");
329
+ if (seen.has(visit))
330
+ continue;
331
+ seen.add(visit);
332
+ const set = setOf(sources.get(key));
333
+ const values = collections[set.id].variables[key].values;
334
+ for (const m of mode ? [mode] : Object.keys(values)) {
335
+ const alias = aliases.get(key)?.get(m);
336
+ if (alias)
337
+ pending.push([alias, setOf(sources.get(alias)) === set ? m : undefined]);
338
+ else if (!accepts(values[m]))
339
+ return false;
340
+ }
341
+ }
342
+ return true;
343
+ },
344
+ positiveLengthOf(data, where) {
345
+ const v = this.variableOf(data, where);
346
+ return "id" in v && v.type === "number" && !v.opacity && this.valuesMatch(v.id, n => typeof n === "number" && n > 0) ? v.id : null;
347
+ },
348
+ variableOf(data, where) {
349
+ if (!isObject(data))
350
+ return { missing: "the binding names no variable" };
351
+ const type = field(data, "dataType", "string", where);
352
+ if (type !== "ALIAS")
353
+ return { missing: type === undefined ? "the binding names no variable" : `the binding is a Figma ${type.toLowerCase()} value, not a variable` };
354
+ const at = refKey((field(data, "value", "object", where) ?? {})["alias"], `${where} alias`);
355
+ const target = at === undefined ? undefined : figmaVariables.get(at);
356
+ if (target === undefined)
357
+ return { missing: "the variable is not in the message" };
358
+ return known.get(target) ?? { missing: `the variable ${quoted(target.name)} is not imported` };
359
+ },
360
+ modeOf(entry, where) {
361
+ if (!isObject(entry))
362
+ return "the entry names no collection";
363
+ const at = refKey(entry["variableSetID"], `${where} variableSetID`);
364
+ const set = at === undefined ? undefined : setsByKey.get(at);
365
+ if (set === undefined)
366
+ return "its collection is not in the message";
367
+ if (typeof set === "string")
368
+ return set.replace(/^its /, "the ");
369
+ const mode = guidText(entry["variableModeID"], `${where} variableModeID`);
370
+ const found = set.modes.find((candidate) => candidate.figma === mode);
371
+ return found === undefined ? `the mode is not in collection ${quoted(collections[set.id].name)}` : { collectionId: set.id, modeId: found.id };
372
+ },
373
+ fontStyleOf(data, figma, where, shownBy) {
374
+ const inner = isObject(data) && field(data, "dataType", "string", where) === "FONT_STYLE"
375
+ ? field(field(field(data, "value", "object", where) ?? {}, "fontStyleValue", "object", where) ?? {}, "asString", "object", where)
376
+ : undefined;
377
+ if (inner === undefined)
378
+ return { missing: "the binding names no font style" };
379
+ const read = valueAt(inner, "string", figma, where, shownBy);
380
+ if ("missing" in read)
381
+ return read;
382
+ return typeof read.value === "string" ? { style: read.value, variable: read.variable }
383
+ : { missing: `the variable ${quoted(read.variable)} has no style name in the mode used (${read.reason ?? "not a string"})` };
384
+ },
385
+ numberOf(data, figma, where, shownBy) {
386
+ const read = valueAt(data, "number", figma, where, shownBy);
387
+ if ("missing" in read)
388
+ return read;
389
+ return typeof read.value === "number" ? { value: read.value, variable: read.variable }
390
+ : { missing: `the variable ${quoted(read.variable)} has no number in the mode used (${read.reason ?? "not a number"})` };
391
+ },
392
+ colorOf(data, figma, where, shownBy) {
393
+ const read = valueAt(data, "color", figma, where, shownBy);
394
+ if ("missing" in read)
395
+ return read;
396
+ return typeof read.value === "string" ? { value: read.value, variable: read.variable }
397
+ : { missing: `the variable ${quoted(read.variable)} has no colour in the mode used (${read.reason ?? "not a colour"})` };
398
+ },
399
+ };
400
+ }
401
+ /** The Taco property a Figma `variableField` binds, or why Taco has no binding for it. */
402
+ const FIELD_PROPERTIES = {
403
+ CORNER_RADIUS: "cornerRadius",
404
+ STACK_SPACING: "gap",
405
+ STACK_COUNTER_SPACING: "wrapGap",
406
+ STACK_PADDING_LEFT: "paddingLeft",
407
+ STACK_PADDING_TOP: "paddingTop",
408
+ STACK_PADDING_RIGHT: "paddingRight",
409
+ STACK_PADDING_BOTTOM: "paddingBottom",
410
+ GRID_ROW_GAP: "rowGap",
411
+ GRID_COLUMN_GAP: "columnGap",
412
+ WIDTH: "width",
413
+ HEIGHT: "height",
414
+ STROKE_WEIGHT: "strokeWidth",
415
+ FONT_FAMILY: "fontFamily",
416
+ FONT_SIZE: "fontSize",
417
+ FONT_WEIGHT: "fontWeight",
418
+ LETTER_SPACING: "letterSpacing",
419
+ VISIBLE: "visibility",
420
+ OPACITY: "opacity",
421
+ LINE_HEIGHT: { reason: "a Figma line height variable holds pixels, and Taco's line height is a multiple of the font size" },
422
+ // A text layer takes a bound font style's value as a fixed weight instead (`bindLayerVariables`).
423
+ FONT_STYLE: { reason: "Figma binds the font style by name, and Taco binds a numeric font weight" },
424
+ MIN_WIDTH: { reason: "Taco has no variable binding for a minimum or maximum size" },
425
+ MAX_WIDTH: { reason: "Taco has no variable binding for a minimum or maximum size" },
426
+ MIN_HEIGHT: { reason: "Taco has no variable binding for a minimum or maximum size" },
427
+ MAX_HEIGHT: { reason: "Taco has no variable binding for a minimum or maximum size" },
428
+ TEXT_DATA: { reason: "Taco has no variable binding for text content" },
429
+ };
430
+ /** Figma fields Taco binds only together, all to one variable, as one property. */
431
+ const FIELD_GROUPS = [
432
+ {
433
+ fields: ["RECTANGLE_TOP_LEFT_CORNER_RADIUS", "RECTANGLE_TOP_RIGHT_CORNER_RADIUS", "RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS", "RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS"],
434
+ property: "cornerRadius", what: "Taco binds one radius for all four corners, and these corners are not all bound to one variable",
435
+ },
436
+ {
437
+ fields: ["BORDER_TOP_WEIGHT", "BORDER_RIGHT_WEIGHT", "BORDER_BOTTOM_WEIGHT", "BORDER_LEFT_WEIGHT"],
438
+ property: "strokeWidth", what: "Taco binds one stroke width for all four sides, and these sides are not all bound to one variable",
439
+ },
440
+ ];
441
+ /** The text run field each text property sets, to check that every run holds one value. */
442
+ const RUN_FIELDS = {
443
+ fontFamily: "fontFamily", fontSize: "fontSize", fontWeight: "fontWeight", letterSpacing: "letterSpacing", textColor: "color",
444
+ };
445
+ /** The Figma field a styled text range sets each text property with, and the variable field that binds it there. */
446
+ const RANGE_FIELDS = {
447
+ fontFamily: { field: "fontName", variableField: "FONT_FAMILY" }, fontWeight: { field: "fontName", variableField: "FONT_WEIGHT" },
448
+ fontSize: { field: "fontSize", variableField: "FONT_SIZE" }, letterSpacing: { field: "letterSpacing", variableField: "LETTER_SPACING" },
449
+ textColor: { field: "fillPaints" },
450
+ };
451
+ /**
452
+ * Whether the styled text range `entry` keeps the layer's binding `data` of `property`: it sets no value of its own,
453
+ * or binds that field to the same variable. A range with its own value would follow the layer's variable once bound.
454
+ */
455
+ function rangeSharesBinding(entry, property, data, where) {
456
+ const range = RANGE_FIELDS[property];
457
+ return range === undefined || rangeShares(entry, range, data, where);
458
+ }
459
+ /** `rangeSharesBinding` for the field `range` names. */
460
+ function rangeShares(entry, range, data, where) {
461
+ const same = (other) => other !== undefined && JSON.stringify(other) === JSON.stringify(data);
462
+ if (range.variableField === undefined) {
463
+ const paints = field(entry, "fillPaints", "list", where);
464
+ if (paints === undefined)
465
+ return true;
466
+ const shown = paints.reduce((top, paint) => isObject(paint) && paint["visible"] !== false && paint["type"] === "SOLID" ? paint : top, undefined);
467
+ return isObject(shown) && same(shown["colorVar"]);
468
+ }
469
+ const map = field(entry, "variableConsumptionMap", "object", where);
470
+ const bound = (map && field(map, "entries", "list", `${where} variableConsumptionMap`) || [])
471
+ .find((item) => isObject(item) && item["variableField"] === range.variableField);
472
+ if (isObject(bound))
473
+ return same(bound["variableData"]);
474
+ return !Object.hasOwn(entry, range.field);
475
+ }
476
+ /**
477
+ * Sets the variable bindings and variable modes of `layer`, converted from `figma`. A paint's `colorVar` binds
478
+ * `fillColor` or `strokeColor` when it is the bottom fill or the first stroke and solid (a text layer's colour is its
479
+ * top visible solid fill, bound as `textColor`); `variableConsumptionMap` entries bind by `FIELD_PROPERTIES` and
480
+ * `FIELD_GROUPS`. A binding the layer cannot take keeps the imported value and is named, with why, in one entry
481
+ * for the layer. With `variables` undefined (the host adds no variables) every binding is reported so. `overridden`
482
+ * names the binding fields an instance copy dropped because its instance overrides them; they join the same entry.
483
+ * `shownBy` reads a bound font style in the modes that instance shows the layer in (`FigmaVariables.fontStyleOf`).
484
+ * No reason names the layer: the entry's node is the layer, so that a host can count one reason over many layers.
485
+ * `styleList` reads the paints of the fill and stroke styles the layer names (`styleBackedList`), whose bindings it takes.
486
+ */
487
+ export function bindLayerVariables(layer, figma, variables, report, overridden = [], shownBy, styleList) {
488
+ const where = `node ${figma.id}`;
489
+ const change = figma.change;
490
+ const candidates = [];
491
+ const left = [];
492
+ if (overridden.length > 0)
493
+ left.push(`${overridden.join(", ")} (the instance overrides ${overridden.length === 1 ? "it" : "them"})`);
494
+ const paintBindings = (list, what) => {
495
+ // A layer that names a fill or stroke style is drawn by the style's paints, so their bindings are the ones it takes.
496
+ const paints = styleBackedList(change, list, styleList, where) ?? [];
497
+ // A text layer shows its top visible solid fill; Taco binds a frame's or shape's bottom fill and first stroke.
498
+ const shown = layer.type === "text" && list === "fillPaints"
499
+ ? paints.reduce((top, paint, index) => isObject(paint) && paint["visible"] !== false && paint["type"] === "SOLID" ? index : top, -1)
500
+ : 0;
501
+ paints.forEach((paint, index) => {
502
+ if (!isObject(paint) || paint["colorVar"] === undefined)
503
+ return;
504
+ const label = `${what} ${String(index + 1)}`;
505
+ if (index !== shown) {
506
+ left.push(`${label} (${layer.type === "text" && list === "fillPaints" ? "a text layer binds only its top visible solid fill" : `Taco binds only the ${list === "fillPaints" ? "bottom fill" : "first stroke"}`})`);
507
+ }
508
+ else if (paint["type"] !== "SOLID") {
509
+ left.push(`${label} (only a solid paint's colour can be bound)`);
510
+ }
511
+ else if (!isObject(paint["color"]) || readNumbers(paint["color"], ["r", "g", "b", "a"], `${where} ${list} color`) === null) {
512
+ // `nodePaints` leaves this paint out, so the Taco paint at its place is another Figma paint.
513
+ left.push(`${label} (the paint has no colour Taco can read, so it was not imported)`);
514
+ }
515
+ else {
516
+ // Figma keeps a bound paint's colour opaque and copies the variable's alpha into the paint's opacity, which
517
+ // cannot be set apart from the variable. The variable's colour carries that alpha in Taco, so it is folded back.
518
+ const opacity = field(paint, "opacity", "number", where) ?? 1;
519
+ const folded = opacity !== 1 && foldsVariableAlpha(paint, opacity, figma, variables, `${where} ${list}`, shownBy);
520
+ if (layer.type === "text" && opacity !== 1 && !folded) {
521
+ left.push(`${label} (the text colour carries the paint's opacity, which the variable's colour would replace)`);
522
+ }
523
+ else {
524
+ const property = layer.type === "text" ? list === "fillPaints" ? "textColor" : "strokeColor" : list === "fillPaints" ? "fillColor" : "strokeColor";
525
+ candidates.push({ label, property, data: paint["colorVar"], ...(folded ? { folded: true } : {}) });
526
+ }
527
+ }
528
+ });
529
+ };
530
+ paintBindings("fillPaints", "fill");
531
+ paintBindings("strokePaints", "stroke");
532
+ const map = field(change, "variableConsumptionMap", "object", where);
533
+ const entries = (map && field(map, "entries", "list", `${where} variableConsumptionMap`) || []).filter(isObject);
534
+ const byField = new Map(entries.map((entry) => [field(entry, "variableField", "string", `${where} variableConsumptionMap`) ?? "", entry["variableData"]]));
535
+ // Taco has no binding for a font style name, so a text layer takes the bound style as a fixed weight, below.
536
+ const styleBound = layer.type === "text" && variables !== undefined && byField.has("FONT_STYLE");
537
+ const styleData = styleBound ? byField.get("FONT_STYLE") : undefined;
538
+ if (styleBound)
539
+ byField.delete("FONT_STYLE");
540
+ // The native adapter binds each corner separately when a corner overrides the overall radius.
541
+ // Baking the overall value here would replace an unbindable corner's stored literal.
542
+ if (variables?.sources.size && [...byField.keys()].some(name => name.startsWith("RECTANGLE_") && name.endsWith("_CORNER_RADIUS")))
543
+ byField.delete("CORNER_RADIUS");
544
+ for (const group of FIELD_GROUPS) {
545
+ const bound = group.fields.filter((name) => byField.has(name));
546
+ if (bound.length === 0)
547
+ continue;
548
+ // Saved files install these fields independently from their original records in the native adapter.
549
+ if (variables?.sources.size) {
550
+ for (const name of bound)
551
+ byField.delete(name);
552
+ continue;
553
+ }
554
+ const keys = bound.map((name) => JSON.stringify(byField.get(name)));
555
+ if (bound.length === group.fields.length && keys.every((key) => key === keys[0])) {
556
+ candidates.push({ label: bound.join(", "), property: group.property, data: byField.get(bound[0]) });
557
+ }
558
+ else
559
+ left.push(`${bound.join(", ")} (${group.what})`);
560
+ for (const name of bound)
561
+ byField.delete(name);
562
+ }
563
+ for (const [name, data] of byField) {
564
+ const mapped = Object.hasOwn(FIELD_PROPERTIES, name) ? FIELD_PROPERTIES[name] : { reason: "Taco has no variable binding for it" };
565
+ if (typeof mapped === "string")
566
+ candidates.push({ label: name, property: mapped, data });
567
+ else
568
+ left.push(`${name || "an unnamed field"} (${mapped.reason})`);
569
+ }
570
+ // Text styles under the layer's own (`styleOverrideTable`) may bind their fills too; Taco binds the whole layer.
571
+ const textData = layer.type === "text" ? field(change, "textData", "object", where) : undefined;
572
+ const runOverrides = (textData && field(textData, "styleOverrideTable", "list", `${where} textData`) || []).filter(isObject);
573
+ const layerColor = JSON.stringify(candidates.find((candidate) => candidate.property === "textColor")?.data);
574
+ const layerFields = new Map(entries.map((entry) => [entry["variableField"], JSON.stringify(entry["variableData"])]));
575
+ const runBound = runOverrides.filter((entry) => (field(entry, "fillPaints", "list", where) ?? [])
576
+ .some((paint) => isObject(paint) && paint["colorVar"] !== undefined && JSON.stringify(paint["colorVar"]) !== layerColor)
577
+ || (field(field(entry, "variableConsumptionMap", "object", where) ?? {}, "entries", "list", where) ?? [])
578
+ .some((item) => !isObject(item) || JSON.stringify(item["variableData"]) !== layerFields.get(item["variableField"]))).length;
579
+ if (styleBound && layer.type === "text") {
580
+ const resolved = variables.fontStyleOf(styleData, figma, `${where} FONT_STYLE`, shownBy);
581
+ const weight = "style" in resolved ? fontStyleWeight(resolved.style) : undefined;
582
+ if ("missing" in resolved)
583
+ left.push(`FONT_STYLE (${resolved.missing})`);
584
+ else if (runOverrides.some((entry) => !rangeShares(entry, { field: "fontName", variableField: "FONT_STYLE" }, styleData, `${where} textData styleOverrideTable`)
585
+ // A range that names the bound style itself keeps it once the style is fixed.
586
+ && field(field(entry, "fontName", "object", where) ?? {}, "style", "string", `${where} fontName`) !== resolved.style)) {
587
+ left.push("FONT_STYLE (a styled text range does not share this binding, and Taco would set one font style for all the text)");
588
+ }
589
+ else if (weight?.fontWeight === undefined) {
590
+ left.push(`FONT_STYLE (the variable ${quoted(resolved.variable)} holds ${quoted(resolved.style)}, which names no known weight)`);
591
+ }
592
+ else {
593
+ const { fontWeight, italic } = weight;
594
+ const paragraphs = layer.paragraphs.map((paragraph) => ({
595
+ ...paragraph,
596
+ runs: paragraph.runs.map((run) => {
597
+ const { italic: _italic, ...rest } = run.overrides ?? {};
598
+ return { ...run, overrides: { ...rest, fontStyle: fontStyleName(fontWeight, italic), fontWeight, ...(italic || run.styleId ? { italic } : {}) } };
599
+ }),
600
+ }));
601
+ Object.assign(layer, { paragraphs });
602
+ report("approximated", `the font style is bound to the variable ${quoted(resolved.variable)}, and Taco binds only a numeric font weight, so the text takes its value ${quoted(resolved.style)} as a fixed style`);
603
+ }
604
+ }
605
+ if (runBound > 0)
606
+ left.push(`the variable bindings of ${String(runBound)} styled text range${runBound === 1 ? "" : "s"} (Taco binds a text layer's properties for all its text)`);
607
+ const bindings = {};
608
+ for (const { label, property, data, folded } of candidates) {
609
+ const variable = candidateBinding(layer, change, runOverrides, property, data, `${where} ${label}`, variables);
610
+ if ("why" in variable)
611
+ left.push(`${label} (${variable.why})`);
612
+ else if (bindings[property] !== undefined && bindings[property] !== variable.id)
613
+ left.push(`${label} (${property} is bound already, by another field)`);
614
+ else {
615
+ bindings[property] = variable.id;
616
+ if (folded)
617
+ foldPaintOpacity(layer, property);
618
+ }
619
+ }
620
+ const modes = figmaVariableModes(figma, variables, left);
621
+ // Without variables nothing binds, so one reason for every layer, which the paste notice can count.
622
+ if (variables === undefined && left.length > 0)
623
+ left.splice(0, left.length, "this import adds no variables to the document");
624
+ if (Object.keys(bindings).length > 0)
625
+ Object.assign(layer, { variableBindings: { ...layer.variableBindings, ...bindings } });
626
+ if (Object.keys(modes).length > 0)
627
+ Object.assign(layer, { variableModes: { ...layer.variableModes, ...modes } });
628
+ if (left.length > 0)
629
+ report("property-left-out", `variable bindings left out, their values kept: ${left.join("; ")}`);
630
+ }
631
+ /**
632
+ * Whether the opacity `opacity` of Figma solid paint `paint` on layer `figma` is its colour variable's alpha, copied
633
+ * there by Figma: the paint's own colour is opaque, and the opacity rounds to the variable's 8-bit alpha in the mode
634
+ * the layer uses. For a saved file, match the paint's stored RGBA against the reachable variable colours.
635
+ * @param paint - Original solid paint.
636
+ * @param opacity - Stored paint opacity.
637
+ * @param figma - Consuming layer.
638
+ * @param variables - Imported variable definitions.
639
+ * @param where - Source location for diagnostics.
640
+ * @param shownBy - Instance displaying the layer.
641
+ * @returns Whether the variable colour already includes this opacity.
642
+ */
643
+ export function foldsVariableAlpha(paint, opacity, figma, variables, where, shownBy) {
644
+ const color = readNumbers(paint["color"], ["r", "g", "b", "a"], `${where} color`);
645
+ if (variables === undefined || color === null || color.a !== 1)
646
+ return false;
647
+ if (variables.sources.size) {
648
+ const v = variables.variableOf(paint["colorVar"], where);
649
+ const stored = hexColor({ ...color, a: opacity });
650
+ return "id" in v && v.type === "color" && !variables.valuesMatch(v.id, value => value !== stored);
651
+ }
652
+ const read = variables.colorOf(paint["colorVar"], figma, `${where} colorVar`, shownBy);
653
+ return "value" in read && read.value.slice(7) === hexColor({ ...color, a: opacity }).slice(7);
654
+ }
655
+ /**
656
+ * Moves the opacity of the paint `layer` binds `property` to (a frame's or shape's bottom fill or first stroke) into
657
+ * its colour's alpha, so that the bound variable's colour, which holds that alpha, replaces it instead of multiplying
658
+ * with it. A text colour holds its paint's opacity already.
659
+ */
660
+ function foldPaintOpacity(layer, property) {
661
+ if (layer.type !== "frame" && layer.type !== "shape")
662
+ return;
663
+ const style = layer.style;
664
+ const fold = (paint) => {
665
+ if (paint.kind !== "solid" || paint.opacity === undefined)
666
+ return paint;
667
+ const { opacity, ...rest } = paint;
668
+ const channel = (at) => parseInt(paint.color.slice(at, at + 2), 16) / 255;
669
+ return { ...rest, color: hexColor({ r: channel(1), g: channel(3), b: channel(5), a: opacity * (paint.color.length === 9 ? channel(7) : 1) }) };
670
+ };
671
+ if (property === "fillColor" && style?.fills?.[0] !== undefined) {
672
+ Object.assign(layer, { style: { ...style, fills: [fold(style.fills[0]), ...style.fills.slice(1)] } });
673
+ }
674
+ else if (property === "strokeColor" && style?.strokes?.[0] !== undefined) {
675
+ const [first, ...others] = style.strokes;
676
+ Object.assign(layer, { style: { ...style, strokes: [{ ...first, paint: fold(first.paint) }, ...others] } });
677
+ }
678
+ }
679
+ /**
680
+ * The variable `layer` (converted from Figma fields `change`, with styled text ranges `runOverrides`) binds `property`
681
+ * to for the binding `data`, or why it binds none. `bindLayerVariables` and `keptFontSize` both decide by it.
682
+ */
683
+ function candidateBinding(layer, change, runOverrides, property, data, where, variables) {
684
+ const spacing = property === "letterSpacing" ? field(change, "letterSpacing", "object", where) : undefined;
685
+ const expressionProperties = new Set(Object.keys("expressions" in layer && layer.expressions ? layer.expressions : {}).flatMap(variablePropertiesOfField));
686
+ const why = runOverrides.some((entry) => !rangeSharesBinding(entry, property, data, `${where} textData styleOverrideTable`))
687
+ ? `a styled text range does not share this binding, and Taco binds ${property} for all the text`
688
+ : spacing !== undefined && field(spacing, "units", "string", `${where} letterSpacing`) !== "PIXELS"
689
+ ? "the text's letter spacing is a percentage of its font size, and Taco binds letter spacing in pixels"
690
+ : whyNotBound(layer, property, expressionProperties);
691
+ if (why !== undefined)
692
+ return { why };
693
+ const variable = variables?.variableOf(data, where);
694
+ if (variable === undefined)
695
+ return { why: "this import adds no variables to the document" };
696
+ if ("missing" in variable)
697
+ return { why: variable.missing };
698
+ if (variable.type !== VARIABLE_PROPERTY_TYPES[property])
699
+ return { why: `${quoted(variable.name)} is a ${variable.type} variable, and ${property} takes a ${VARIABLE_PROPERTY_TYPES[property]}` };
700
+ if (property === "opacity" && variable.opacity !== true) {
701
+ return { why: `${quoted(variable.name)} is not scoped to opacity alone, so it holds Figma's percentage unconverted, and Taco's opacity runs from 0 to 1` };
702
+ }
703
+ if (property !== "opacity" && variable.opacity === true) {
704
+ return { why: `${quoted(variable.name)} is scoped to opacity, so it is imported on Taco's 0 to 1 opacity scale, not as ${property}` };
705
+ }
706
+ if (property === "fontSize" && !variables.positiveLengthOf(data, where)
707
+ || ["width", "height", "strokeWidth", "cornerRadius", "opacity"].includes(property)
708
+ && !variables.valuesMatch(variable.id, n => typeof n === "number" && n >= 0 && (property !== "opacity" || n <= 1)))
709
+ return { why: "a mode is outside the field's range" };
710
+ return { id: variable.id };
711
+ }
712
+ /**
713
+ * The font size Taco draws text `layer`, converted from `figma`, at when `bindLayerVariables` keeps its own `FONT_SIZE`
714
+ * binding: the variable's value in the mode the layer uses (with `shownBy`, as that instance shows it); else `undefined`,
715
+ * and each run is drawn at its own size.
716
+ */
717
+ export function keptFontSize(layer, figma, variables, shownBy) {
718
+ const where = `node ${figma.id}`;
719
+ const map = field(figma.change, "variableConsumptionMap", "object", where);
720
+ const entry = (map && field(map, "entries", "list", `${where} variableConsumptionMap`) || []).find((item) => isObject(item) && item["variableField"] === "FONT_SIZE");
721
+ if (!isObject(entry) || variables === undefined)
722
+ return undefined;
723
+ const textData = field(figma.change, "textData", "object", where);
724
+ const runOverrides = (textData && field(textData, "styleOverrideTable", "list", `${where} textData`) || []).filter(isObject);
725
+ if ("why" in candidateBinding(layer, figma.change, runOverrides, "fontSize", entry["variableData"], `${where} FONT_SIZE`, variables))
726
+ return undefined;
727
+ const read = variables.numberOf(entry["variableData"], figma, `${where} FONT_SIZE`, shownBy);
728
+ return "value" in read && read.value > 0 ? read.value : undefined;
729
+ }
730
+ /**
731
+ * The variable modes `figma` chooses (`variableModeBySetMap`), by collection id; a choice that names no imported
732
+ * collection or mode is added to `left`.
733
+ */
734
+ export function figmaVariableModes(figma, variables, left) {
735
+ const where = `node ${figma.id}`;
736
+ const modes = {};
737
+ const modeMap = field(figma.change, "variableModeBySetMap", "object", where);
738
+ for (const entry of (modeMap && field(modeMap, "entries", "list", `${where} variableModeBySetMap`) || [])) {
739
+ const mode = variables?.modeOf(entry, `${where} variableModeBySetMap`) ?? "this import adds no variables to the document";
740
+ if (typeof mode === "string")
741
+ left.push(`the chosen variable mode (${mode})`);
742
+ else
743
+ modes[mode.collectionId] = mode.modeId;
744
+ }
745
+ return modes;
746
+ }
747
+ /** Why `layer` cannot bind `property`, or undefined when it can. */
748
+ function whyNotBound(layer, property, expressionProperties) {
749
+ if (!nodeSupportsVariableProperty(layer, property)) {
750
+ const layout = layer.type === "frame" ? layer.layout.kind : undefined;
751
+ return layout === "absolute" && /^(gap|wrapGap|rowGap|columnGap|padding)/.test(property)
752
+ ? `the frame has no auto layout in Taco, so it has no ${property}`
753
+ : `a Taco ${layer.type === "shape" ? `${layer.shape} shape` : layer.type} layer cannot bind ${property}`;
754
+ }
755
+ if (expressionProperties.has(property))
756
+ return `the layer computes ${property} with an expression`;
757
+ if ((property === "fillColor" || property === "strokeColor") && (layer.type === "frame" || layer.type === "shape")) {
758
+ const paint = property === "fillColor" ? layer.style?.fills?.[0] : layer.style?.strokes?.[0]?.paint;
759
+ if (paint?.kind !== "solid")
760
+ return `the layer's ${property === "fillColor" ? "bottom fill" : "first stroke"} was not imported as a solid paint`;
761
+ }
762
+ const run = RUN_FIELDS[property];
763
+ if (layer.type === "text" && run !== undefined) {
764
+ const values = new Set(layer.paragraphs.flatMap((paragraph) => paragraph.runs.map((entry) => JSON.stringify(entry.overrides?.[run]))));
765
+ if (values.size > 1)
766
+ return `the text's ranges differ in ${run}, and Taco binds it for all the text`;
767
+ }
768
+ return undefined;
769
+ }