@moondraft/import 0.0.0-stage → 0.1.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 (323) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +34 -0
  3. package/README.md +36 -2
  4. package/SOURCE.md +169 -0
  5. package/dist/adapter/convert.d.ts +122 -0
  6. package/dist/adapter/convert.js +2302 -0
  7. package/dist/adapter/figma.d.ts +9 -0
  8. package/dist/adapter/figma.js +30 -0
  9. package/dist/adapter/file-components.d.ts +14 -0
  10. package/dist/adapter/file-components.js +262 -0
  11. package/dist/adapter/file-resources.d.ts +29 -0
  12. package/dist/adapter/file-resources.js +562 -0
  13. package/dist/adapter/index.d.ts +6 -0
  14. package/dist/adapter/index.js +9 -0
  15. package/dist/adapter/link.d.ts +45 -0
  16. package/dist/adapter/link.js +688 -0
  17. package/dist/adapter/payload.d.ts +31 -0
  18. package/dist/adapter/payload.js +78 -0
  19. package/dist/adapter/shapes.d.ts +31 -0
  20. package/dist/adapter/shapes.js +75 -0
  21. package/dist/adapter/variables.d.ts +44 -0
  22. package/dist/adapter/variables.js +103 -0
  23. package/dist/figma-file.d.ts +38 -0
  24. package/dist/figma-file.js +97 -0
  25. package/dist/figma-worker.d.ts +11 -0
  26. package/dist/figma-worker.js +12 -0
  27. package/dist/figma.d.ts +26 -0
  28. package/dist/figma.js +96 -0
  29. package/dist/index.d.ts +28 -0
  30. package/dist/index.js +49 -0
  31. package/dist/report.d.ts +15 -0
  32. package/dist/report.js +69 -0
  33. package/dist/svg.d.ts +33 -0
  34. package/dist/svg.js +44 -0
  35. package/dist/syntax.d.ts +8 -0
  36. package/dist/syntax.js +19 -0
  37. package/dist/taco/figma-import/clipboard.d.ts +25 -0
  38. package/dist/taco/figma-import/clipboard.js +87 -0
  39. package/dist/taco/figma-import/clipboardSize.d.ts +31 -0
  40. package/dist/taco/figma-import/clipboardSize.js +107 -0
  41. package/dist/taco/figma-import/container/compression.d.ts +9 -0
  42. package/dist/taco/figma-import/container/compression.js +174 -0
  43. package/dist/taco/figma-import/container/error.d.ts +15 -0
  44. package/dist/taco/figma-import/container/error.js +19 -0
  45. package/dist/taco/figma-import/container/kiwiContainer.d.ts +38 -0
  46. package/dist/taco/figma-import/container/kiwiContainer.js +61 -0
  47. package/dist/taco/figma-import/container/limits.d.ts +22 -0
  48. package/dist/taco/figma-import/container/limits.js +22 -0
  49. package/dist/taco/figma-import/container/zip.d.ts +14 -0
  50. package/dist/taco/figma-import/container/zip.js +154 -0
  51. package/dist/taco/figma-import/figFile.d.ts +34 -0
  52. package/dist/taco/figma-import/figFile.js +91 -0
  53. package/dist/taco/figma-import/figFileDocument.d.ts +25 -0
  54. package/dist/taco/figma-import/figFileDocument.js +100 -0
  55. package/dist/taco/figma-import/import/blobs.d.ts +10 -0
  56. package/dist/taco/figma-import/import/blobs.js +23 -0
  57. package/dist/taco/figma-import/import/carry.d.ts +11 -0
  58. package/dist/taco/figma-import/import/carry.js +33 -0
  59. package/dist/taco/figma-import/import/componentProps.d.ts +84 -0
  60. package/dist/taco/figma-import/import/componentProps.js +313 -0
  61. package/dist/taco/figma-import/import/componentSets.d.ts +83 -0
  62. package/dist/taco/figma-import/import/componentSets.js +647 -0
  63. package/dist/taco/figma-import/import/converters/effects.d.ts +31 -0
  64. package/dist/taco/figma-import/import/converters/effects.js +127 -0
  65. package/dist/taco/figma-import/import/converters/ellipse.d.ts +7 -0
  66. package/dist/taco/figma-import/import/converters/ellipse.js +54 -0
  67. package/dist/taco/figma-import/import/converters/frame.d.ts +21 -0
  68. package/dist/taco/figma-import/import/converters/frame.js +55 -0
  69. package/dist/taco/figma-import/import/converters/gradient.d.ts +72 -0
  70. package/dist/taco/figma-import/import/converters/gradient.js +106 -0
  71. package/dist/taco/figma-import/import/converters/group.d.ts +21 -0
  72. package/dist/taco/figma-import/import/converters/group.js +39 -0
  73. package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
  74. package/dist/taco/figma-import/import/converters/image.js +83 -0
  75. package/dist/taco/figma-import/import/converters/layout.d.ts +34 -0
  76. package/dist/taco/figma-import/import/converters/layout.js +168 -0
  77. package/dist/taco/figma-import/import/converters/line.d.ts +11 -0
  78. package/dist/taco/figma-import/import/converters/line.js +40 -0
  79. package/dist/taco/figma-import/import/converters/rectangle.d.ts +3 -0
  80. package/dist/taco/figma-import/import/converters/rectangle.js +11 -0
  81. package/dist/taco/figma-import/import/converters/section.d.ts +9 -0
  82. package/dist/taco/figma-import/import/converters/section.js +35 -0
  83. package/dist/taco/figma-import/import/converters/shared.d.ts +68 -0
  84. package/dist/taco/figma-import/import/converters/shared.js +362 -0
  85. package/dist/taco/figma-import/import/converters/text.d.ts +41 -0
  86. package/dist/taco/figma-import/import/converters/text.js +576 -0
  87. package/dist/taco/figma-import/import/converters/vector.d.ts +84 -0
  88. package/dist/taco/figma-import/import/converters/vector.js +468 -0
  89. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +98 -0
  90. package/dist/taco/figma-import/import/converters/vectorNetwork.js +385 -0
  91. package/dist/taco/figma-import/import/fields.d.ts +15 -0
  92. package/dist/taco/figma-import/import/fields.js +29 -0
  93. package/dist/taco/figma-import/import/instances.d.ts +163 -0
  94. package/dist/taco/figma-import/import/instances.js +1323 -0
  95. package/dist/taco/figma-import/import/nestingCycles.d.ts +86 -0
  96. package/dist/taco/figma-import/import/nestingCycles.js +488 -0
  97. package/dist/taco/figma-import/import/slots.d.ts +56 -0
  98. package/dist/taco/figma-import/import/slots.js +96 -0
  99. package/dist/taco/figma-import/import/styles.d.ts +46 -0
  100. package/dist/taco/figma-import/import/styles.js +42 -0
  101. package/dist/taco/figma-import/import/tree.d.ts +66 -0
  102. package/dist/taco/figma-import/import/tree.js +194 -0
  103. package/dist/taco/figma-import/import/types.d.ts +232 -0
  104. package/dist/taco/figma-import/import/types.js +33 -0
  105. package/dist/taco/figma-import/import/variables.d.ts +136 -0
  106. package/dist/taco/figma-import/import/variables.js +762 -0
  107. package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
  108. package/dist/taco/figma-import/import/variantTrees.js +480 -0
  109. package/dist/taco/figma-import/import/walk.d.ts +159 -0
  110. package/dist/taco/figma-import/import/walk.js +1297 -0
  111. package/dist/taco/figma-import/index.d.ts +22 -0
  112. package/dist/taco/figma-import/index.js +13 -0
  113. package/dist/taco/figma-import/kiwi/byteReader.d.ts +37 -0
  114. package/dist/taco/figma-import/kiwi/byteReader.js +151 -0
  115. package/dist/taco/figma-import/kiwi/error.d.ts +14 -0
  116. package/dist/taco/figma-import/kiwi/error.js +29 -0
  117. package/dist/taco/figma-import/kiwi/limits.d.ts +18 -0
  118. package/dist/taco/figma-import/kiwi/limits.js +18 -0
  119. package/dist/taco/figma-import/kiwi/message.d.ts +10 -0
  120. package/dist/taco/figma-import/kiwi/message.js +145 -0
  121. package/dist/taco/figma-import/kiwi/schema.d.ts +42 -0
  122. package/dist/taco/figma-import/kiwi/schema.js +206 -0
  123. package/dist/taco/figma-import/kiwi/types.d.ts +46 -0
  124. package/dist/taco/figma-import/kiwi/types.js +18 -0
  125. package/dist/taco/model/agent-hidden-fields.d.ts +20 -0
  126. package/dist/taco/model/agent-hidden-fields.js +29 -0
  127. package/dist/taco/model/asset-users.d.ts +23 -0
  128. package/dist/taco/model/asset-users.js +128 -0
  129. package/dist/taco/model/auto-layout-lines.d.ts +32 -0
  130. package/dist/taco/model/auto-layout-lines.js +70 -0
  131. package/dist/taco/model/codec.d.ts +444 -0
  132. package/dist/taco/model/codec.js +5635 -0
  133. package/dist/taco/model/color.d.ts +11 -0
  134. package/dist/taco/model/color.js +61 -0
  135. package/dist/taco/model/comment-operations.d.ts +102 -0
  136. package/dist/taco/model/comment-operations.js +227 -0
  137. package/dist/taco/model/component-evaluation.d.ts +94 -0
  138. package/dist/taco/model/component-evaluation.js +548 -0
  139. package/dist/taco/model/component-expressions.d.ts +242 -0
  140. package/dist/taco/model/component-expressions.js +1082 -0
  141. package/dist/taco/model/component-properties.d.ts +111 -0
  142. package/dist/taco/model/component-properties.js +339 -0
  143. package/dist/taco/model/component-samples.d.ts +83 -0
  144. package/dist/taco/model/component-samples.js +290 -0
  145. package/dist/taco/model/component-validity.d.ts +85 -0
  146. package/dist/taco/model/component-validity.js +397 -0
  147. package/dist/taco/model/components.d.ts +155 -0
  148. package/dist/taco/model/components.js +505 -0
  149. package/dist/taco/model/connector-ends.d.ts +20 -0
  150. package/dist/taco/model/connector-ends.js +188 -0
  151. package/dist/taco/model/connector-geometry.d.ts +74 -0
  152. package/dist/taco/model/connector-geometry.js +293 -0
  153. package/dist/taco/model/corner-radii.d.ts +26 -0
  154. package/dist/taco/model/corner-radii.js +47 -0
  155. package/dist/taco/model/derivations.d.ts +81 -0
  156. package/dist/taco/model/derivations.js +151 -0
  157. package/dist/taco/model/export-settings.d.ts +53 -0
  158. package/dist/taco/model/export-settings.js +156 -0
  159. package/dist/taco/model/expressions/ast.d.ts +153 -0
  160. package/dist/taco/model/expressions/ast.js +6 -0
  161. package/dist/taco/model/expressions/cache.d.ts +23 -0
  162. package/dist/taco/model/expressions/cache.js +43 -0
  163. package/dist/taco/model/expressions/check.d.ts +72 -0
  164. package/dist/taco/model/expressions/check.js +517 -0
  165. package/dist/taco/model/expressions/completion.d.ts +61 -0
  166. package/dist/taco/model/expressions/completion.js +421 -0
  167. package/dist/taco/model/expressions/evaluate.d.ts +32 -0
  168. package/dist/taco/model/expressions/evaluate.js +519 -0
  169. package/dist/taco/model/expressions/forms.d.ts +84 -0
  170. package/dist/taco/model/expressions/forms.js +200 -0
  171. package/dist/taco/model/expressions/index.d.ts +14 -0
  172. package/dist/taco/model/expressions/index.js +17 -0
  173. package/dist/taco/model/expressions/lexer.d.ts +42 -0
  174. package/dist/taco/model/expressions/lexer.js +213 -0
  175. package/dist/taco/model/expressions/library.d.ts +33 -0
  176. package/dist/taco/model/expressions/library.js +117 -0
  177. package/dist/taco/model/expressions/names.d.ts +43 -0
  178. package/dist/taco/model/expressions/names.js +99 -0
  179. package/dist/taco/model/expressions/parser.d.ts +15 -0
  180. package/dist/taco/model/expressions/parser.js +438 -0
  181. package/dist/taco/model/expressions/rename.d.ts +34 -0
  182. package/dist/taco/model/expressions/rename.js +46 -0
  183. package/dist/taco/model/expressions/source.d.ts +15 -0
  184. package/dist/taco/model/expressions/source.js +161 -0
  185. package/dist/taco/model/expressions/types.d.ts +119 -0
  186. package/dist/taco/model/expressions/types.js +102 -0
  187. package/dist/taco/model/expressions/values.d.ts +97 -0
  188. package/dist/taco/model/expressions/values.js +160 -0
  189. package/dist/taco/model/geometry-limits.d.ts +16 -0
  190. package/dist/taco/model/geometry-limits.js +67 -0
  191. package/dist/taco/model/geometry.d.ts +47 -0
  192. package/dist/taco/model/geometry.js +193 -0
  193. package/dist/taco/model/group-bounds.d.ts +38 -0
  194. package/dist/taco/model/group-bounds.js +144 -0
  195. package/dist/taco/model/id-table.d.ts +37 -0
  196. package/dist/taco/model/id-table.js +80 -0
  197. package/dist/taco/model/index.d.ts +25 -0
  198. package/dist/taco/model/index.js +27 -0
  199. package/dist/taco/model/instance-resolver.d.ts +372 -0
  200. package/dist/taco/model/instance-resolver.js +1748 -0
  201. package/dist/taco/model/layer-syntax.d.ts +340 -0
  202. package/dist/taco/model/layer-syntax.js +3506 -0
  203. package/dist/taco/model/layout/constraints.d.ts +84 -0
  204. package/dist/taco/model/layout/constraints.js +445 -0
  205. package/dist/taco/model/layout/frame-layout.d.ts +46 -0
  206. package/dist/taco/model/layout/frame-layout.js +618 -0
  207. package/dist/taco/model/layout/node-sizing.d.ts +163 -0
  208. package/dist/taco/model/layout/node-sizing.js +486 -0
  209. package/dist/taco/model/legacy-connector-caps.d.ts +15 -0
  210. package/dist/taco/model/legacy-connector-caps.js +70 -0
  211. package/dist/taco/model/linear-call.d.ts +48 -0
  212. package/dist/taco/model/linear-call.js +58 -0
  213. package/dist/taco/model/new-nodes.d.ts +145 -0
  214. package/dist/taco/model/new-nodes.js +277 -0
  215. package/dist/taco/model/node-builder.d.ts +449 -0
  216. package/dist/taco/model/node-builder.js +2294 -0
  217. package/dist/taco/model/node-table-watch.d.ts +36 -0
  218. package/dist/taco/model/node-table-watch.js +63 -0
  219. package/dist/taco/model/node-transform.d.ts +39 -0
  220. package/dist/taco/model/node-transform.js +79 -0
  221. package/dist/taco/model/node-users-index.d.ts +10 -0
  222. package/dist/taco/model/node-users-index.js +82 -0
  223. package/dist/taco/model/operation-references.d.ts +80 -0
  224. package/dist/taco/model/operation-references.js +399 -0
  225. package/dist/taco/model/operations.d.ts +610 -0
  226. package/dist/taco/model/operations.js +2882 -0
  227. package/dist/taco/model/overlay-table.d.ts +71 -0
  228. package/dist/taco/model/overlay-table.js +171 -0
  229. package/dist/taco/model/override-remap.d.ts +69 -0
  230. package/dist/taco/model/override-remap.js +230 -0
  231. package/dist/taco/model/parent-table.d.ts +53 -0
  232. package/dist/taco/model/parent-table.js +193 -0
  233. package/dist/taco/model/problem-collector.d.ts +27 -0
  234. package/dist/taco/model/problem-collector.js +101 -0
  235. package/dist/taco/model/sha256.d.ts +10 -0
  236. package/dist/taco/model/sha256.js +74 -0
  237. package/dist/taco/model/shape-geometry.d.ts +96 -0
  238. package/dist/taco/model/shape-geometry.js +368 -0
  239. package/dist/taco/model/shared-node-table.d.ts +97 -0
  240. package/dist/taco/model/shared-node-table.js +546 -0
  241. package/dist/taco/model/slots.d.ts +113 -0
  242. package/dist/taco/model/slots.js +281 -0
  243. package/dist/taco/model/stroke-settings.d.ts +37 -0
  244. package/dist/taco/model/stroke-settings.js +90 -0
  245. package/dist/taco/model/svg-path-import.d.ts +89 -0
  246. package/dist/taco/model/svg-path-import.js +219 -0
  247. package/dist/taco/model/text-measurement.d.ts +142 -0
  248. package/dist/taco/model/text-measurement.js +846 -0
  249. package/dist/taco/model/text-reads.d.ts +66 -0
  250. package/dist/taco/model/text-reads.js +128 -0
  251. package/dist/taco/model/text-sizer.d.ts +358 -0
  252. package/dist/taco/model/text-sizer.js +996 -0
  253. package/dist/taco/model/theme-users.d.ts +59 -0
  254. package/dist/taco/model/theme-users.js +312 -0
  255. package/dist/taco/model/thumbnail.d.ts +15 -0
  256. package/dist/taco/model/thumbnail.js +34 -0
  257. package/dist/taco/model/types.d.ts +2347 -0
  258. package/dist/taco/model/types.js +366 -0
  259. package/dist/taco/model/unknown-property.d.ts +5 -0
  260. package/dist/taco/model/unknown-property.js +7 -0
  261. package/dist/taco/model/validated-documents.d.ts +22 -0
  262. package/dist/taco/model/validated-documents.js +22 -0
  263. package/dist/taco/model/variable-modes.d.ts +61 -0
  264. package/dist/taco/model/variable-modes.js +438 -0
  265. package/dist/taco/model/variable-references.d.ts +54 -0
  266. package/dist/taco/model/variable-references.js +183 -0
  267. package/dist/taco/model/variables.d.ts +24 -0
  268. package/dist/taco/model/variables.js +151 -0
  269. package/dist/taco/model/vector-network.d.ts +34 -0
  270. package/dist/taco/model/vector-network.js +411 -0
  271. package/dist/taco/svg-import/import-svg.d.ts +36 -0
  272. package/dist/taco/svg-import/import-svg.js +729 -0
  273. package/dist/taco/svg-import/index.d.ts +3 -0
  274. package/dist/taco/svg-import/index.js +3 -0
  275. package/dist/taco/svg-import/limits/limits.d.ts +79 -0
  276. package/dist/taco/svg-import/limits/limits.js +160 -0
  277. package/dist/taco/svg-import/paint/gradients.d.ts +64 -0
  278. package/dist/taco/svg-import/paint/gradients.js +429 -0
  279. package/dist/taco/svg-import/paint/paint.d.ts +32 -0
  280. package/dist/taco/svg-import/paint/paint.js +162 -0
  281. package/dist/taco/svg-import/paths/paths.d.ts +58 -0
  282. package/dist/taco/svg-import/paths/paths.js +205 -0
  283. package/dist/taco/svg-import/public-types.d.ts +279 -0
  284. package/dist/taco/svg-import/public-types.js +56 -0
  285. package/dist/taco/svg-import/report/report.d.ts +44 -0
  286. package/dist/taco/svg-import/report/report.js +79 -0
  287. package/dist/taco/svg-import/reuse/reuse.d.ts +99 -0
  288. package/dist/taco/svg-import/reuse/reuse.js +840 -0
  289. package/dist/taco/svg-import/shapes/shapes.d.ts +35 -0
  290. package/dist/taco/svg-import/shapes/shapes.js +386 -0
  291. package/dist/taco/svg-import/structure/effects.d.ts +26 -0
  292. package/dist/taco/svg-import/structure/effects.js +618 -0
  293. package/dist/taco/svg-import/structure/image.d.ts +24 -0
  294. package/dist/taco/svg-import/structure/image.js +495 -0
  295. package/dist/taco/svg-import/structure/walk.d.ts +85 -0
  296. package/dist/taco/svg-import/structure/walk.js +544 -0
  297. package/dist/taco/svg-import/style/color.d.ts +40 -0
  298. package/dist/taco/svg-import/style/color.js +275 -0
  299. package/dist/taco/svg-import/style/computed.d.ts +214 -0
  300. package/dist/taco/svg-import/style/computed.js +1534 -0
  301. package/dist/taco/svg-import/style/css.d.ts +127 -0
  302. package/dist/taco/svg-import/style/css.js +541 -0
  303. package/dist/taco/svg-import/style/media.d.ts +25 -0
  304. package/dist/taco/svg-import/style/media.js +307 -0
  305. package/dist/taco/svg-import/style/properties.d.ts +43 -0
  306. package/dist/taco/svg-import/style/properties.js +135 -0
  307. package/dist/taco/svg-import/style/selector-reach.d.ts +30 -0
  308. package/dist/taco/svg-import/style/selector-reach.js +169 -0
  309. package/dist/taco/svg-import/style/selector-validity.d.ts +14 -0
  310. package/dist/taco/svg-import/style/selector-validity.js +307 -0
  311. package/dist/taco/svg-import/text/text.d.ts +29 -0
  312. package/dist/taco/svg-import/text/text.js +545 -0
  313. package/dist/taco/svg-import/transform/matrix.d.ts +111 -0
  314. package/dist/taco/svg-import/transform/matrix.js +229 -0
  315. package/dist/taco/svg-import/tree/element-data.d.ts +52 -0
  316. package/dist/taco/svg-import/tree/element-data.js +155 -0
  317. package/dist/taco/svg-import/tree/elements.d.ts +36 -0
  318. package/dist/taco/svg-import/tree/elements.js +121 -0
  319. package/dist/taco/svg-import/units/length.d.ts +43 -0
  320. package/dist/taco/svg-import/units/length.js +125 -0
  321. package/dist/taco/svg-import/units/viewbox.d.ts +35 -0
  322. package/dist/taco/svg-import/units/viewbox.js +77 -0
  323. package/package.json +54 -4
@@ -0,0 +1,2302 @@
1
+ // Converts one page of a taco document (schemaVersion 0.44.0, as taco's figma-import and svg-import write it) into a
2
+ // Moondraft document (DocumentJSON). Instances are expanded from their component's root subtree; which overrides and
3
+ // slot fills apply to each layer is taco's instance resolver's call, and conditions and expressions read component
4
+ // properties and the effective mode's theme values. Whatever is not carried
5
+ // over is counted by kind in the report. Auto-layout frames are laid out after expansion; stored instance sizes remain
6
+ // authoritative. Then link.ts links each expanded instance its component's main can show to that main (an instance
7
+ // with overrides); { link: false } leaves them expanded. Moved from tools/host_doc/convert.mjs, whose CLI is now a
8
+ // wrapper over toDocument.
9
+ //
10
+ // The taco records are read as JSON, field by field and loosely (any): the converter reads fields of several schema
11
+ // versions and of the HeroUI kit export that taco's model types do not declare, so the source side is untyped and the
12
+ // result is checked against DocumentJSON where it leaves.
13
+ import { fontStyleName, layoutFrame, layoutData, localBox, mul, pathBounds, resize, scalePath, wrapped } from '@moondraft/editor/core';
14
+ import { shapes } from '@moondraft/editor/core';
15
+ import { paintBox, resolveLinearCall } from '../taco/model/linear-call.js';
16
+ import { arcCubics, arcNetwork, ellipseNetwork, network } from './shapes.js';
17
+ import { expressionCollections, variableResolver } from './variables.js';
18
+ import { BLEND_MODES } from '../taco/model/types.js';
19
+ import { applyComputedFields, checkComponentProgram, evaluateComponentProgram, filledPropertyValues } from '../taco/model/component-evaluation.js';
20
+ import { componentExpressionEnvironment, componentValueEnvironment, computableFieldType, storedFieldValue } from '../taco/model/component-expressions.js';
21
+ import { ExpressionCache } from '../taco/model/expressions/cache.js';
22
+ import { evaluateExpression } from '../taco/model/expressions/evaluate.js';
23
+ import { EXPRESSION_TYPES } from '../taco/model/expressions/types.js';
24
+ import { expressionColorToHex } from '../taco/model/expressions/values.js';
25
+ import { withoutTextMeasurement } from '../taco/model/text-reads.js';
26
+ import { createInstanceResolveCache, resolveComponent, resolveInstance } from '../taco/model/instance-resolver.js';
27
+ import { linkWithLayers, unmark } from './link.js';
28
+ /** Converts a reader colour to the RGBA precision used by imported paints.
29
+ * @param hex - Source hex colour or expression colour.
30
+ * @returns Normalized channels, or null for a non-colour value.
31
+ * @internal
32
+ */
33
+ export function rgba(hex) {
34
+ hex = hex?.hex ?? hex;
35
+ if (typeof hex !== 'string' || hex[0] !== '#')
36
+ return null;
37
+ let h = hex.slice(1);
38
+ if (h.length === 3 || h.length === 4)
39
+ h = [...h].map((c) => c + c).join('');
40
+ if (h.length === 6)
41
+ h += 'ff';
42
+ if (!/^[\da-f]{8}$/i.test(h))
43
+ return null;
44
+ return [0, 2, 4, 6].map((i) => +(parseInt(h.slice(i, i + 2), 16) / 255).toFixed(4));
45
+ }
46
+ /** Converts reader typography to a native palette entry.
47
+ * @param s - Resolved source run style.
48
+ * @returns Native face, metrics, decoration and colour.
49
+ * @internal
50
+ */
51
+ export function runStyle(s) {
52
+ const size = s.fontSize ?? 16, weight = s.fontWeight ?? 400;
53
+ return {
54
+ family: s.fontFamily ?? 'Inter', style: s.fontStyle ?? fontStyleName(weight, !!s.italic),
55
+ ...(s.fontVariations && { variations: s.fontVariations }), size, lineHeight: +(size * (s.lineHeight ?? 1.2)).toFixed(3),
56
+ weight, italic: !!s.italic, underline: !!s.underline, ...(s.strikethrough ? { strikethrough: true } : {}),
57
+ color: rgba(s.color) ?? [0, 0, 0, 1], letterSpacing: s.letterSpacing ?? 0,
58
+ };
59
+ }
60
+ const EXPORT_QUALITY = { low: 0.5, medium: 0.75, high: 0.92 };
61
+ /** A source layer's export rows as the editor's `exports`: the format, the constraint as a scale, a width or a
62
+ * height, the suffix, and for JPEG the quality as a number. The rest of a row (resampling, overlapping layers, id
63
+ * attributes) has no counterpart. */
64
+ function exportsOf(rows) {
65
+ if (!rows?.length)
66
+ return undefined;
67
+ return rows.slice(0, 32).map(({ format, constraint, suffix, quality }) => ({
68
+ format, [constraint.type]: constraint.value, suffix,
69
+ ...(format === 'jpeg' && { quality: EXPORT_QUALITY[quality] }),
70
+ }));
71
+ }
72
+ /**
73
+ * Converts one page of a Taco document to Moondraft records.
74
+ * @param doc - Source document.
75
+ * @param pageRef - Page name or zero-based index.
76
+ * @param options - Conversion settings.
77
+ * @returns Converted document and report.
78
+ */
79
+ export function toDocument(doc, pageRef, options = {}) {
80
+ const pages = doc.pageOrder.map((id) => doc.pages[id]);
81
+ const page = typeof pageRef === 'number' ? pages[pageRef] : pages.find((p) => p.name === pageRef);
82
+ if (!page)
83
+ throw new Error(`no page ${pageRef}; pages: ${pages.map((p) => p.name).join(', ')}`);
84
+ return convert(doc, [page], options, false);
85
+ }
86
+ /** Converts all file pages and keeps the appearance of each linked occurrence.
87
+ * @param doc - Source document.
88
+ * @param options - Asset and conversion settings.
89
+ * @returns Linked document, conversion report and the pre-link instance literals.
90
+ * @internal
91
+ */
92
+ export function allPages(doc, options) {
93
+ const expanded = new Map();
94
+ return { ...convert(doc, doc.pageOrder.map((id) => doc.pages[id]), options, true, expanded), expanded };
95
+ }
96
+ function convert(doc, pages, options, explicit, expanded) {
97
+ const kitFixes = options.kitFixes ?? false;
98
+ const dropped = new Map(), notes = new Map(), approximations = new Map();
99
+ const affected = new Map();
100
+ let active, probing = 0;
101
+ function mark(kind, what, layer = active) {
102
+ if (!layer || probing)
103
+ return;
104
+ const key = `${kind}:${what}`;
105
+ let layers = affected.get(key);
106
+ if (!layers)
107
+ affected.set(key, layers = new Set());
108
+ layers.add(layer);
109
+ }
110
+ const drop = (what, n = 1) => { dropped.set(what, (dropped.get(what) ?? 0) + n); mark('dropped', what); };
111
+ const note = (what, n = 1, layer = active) => { notes.set(what, (notes.get(what) ?? 0) + n); mark('note', what, layer); };
112
+ const approximate = (what, n = 1, layer = active) => {
113
+ note(what, n, layer);
114
+ approximations.set(what, (approximations.get(what) ?? 0) + n);
115
+ };
116
+ const rootOf = new Map(Object.values(doc.components).map((c) => [c.rootId, c]));
117
+ // Children of slot frames: an instance fills a slot by re-pointing them, hidden ones included (below).
118
+ const slotChildren = new Set(Object.values(doc.nodes).flatMap((n) => (n.slot ? n.children ?? [] : [])));
119
+ // An expanded instance of a component with variant properties names its set (link.ts names its hidden main
120
+ // "Button/variant=primary, size=sm" with it, so the editor groups a set's variants and no other's).
121
+ // It names its variant too (its variant properties' values, "variant=primary, size=sm"): link.ts makes one hidden
122
+ // main per variant used, so an instance's main is its own variant and its overrides are its own changes alone.
123
+ const markSet = (model, comp, props) => {
124
+ const enums = (comp.properties ?? []).filter((p) => p.kind === 'enum');
125
+ if (!comp.name || !enums.length)
126
+ return;
127
+ model.setOf = comp.name;
128
+ model.variant = enums.map((p) => `${p.name}=${props.get(p.name)}`).join(', ');
129
+ };
130
+ // ---- Expressions: taco's own evaluator (taco/model/component-evaluation.ts), as the instance resolver uses it. A
131
+ // component's expressions and conditions are parsed and checked once (its program); its layers are evaluated once per
132
+ // set of property values and variable modes, when a layer's field or condition is first read, and a field is read
133
+ // back from the computed layer. A field that does not check, that these values make invalid or that its layer ignores
134
+ // (a layout field on a frame without auto layout, which Figma does not show either) keeps its stored value and is
135
+ // counted. Override conditions (and expressions an override sets) are checked against their component's properties
136
+ // and evaluated alone, without evaluating the component. Bound variables (variableBindings) and expressions read a
137
+ // variable in the same mode (variables.ts).
138
+ const collections = doc.theme?.variableCollections ?? {};
139
+ const resolveVariable = variableResolver(collections);
140
+ const expressionVariables = expressionCollections(collections);
141
+ // The evaluator reads text fields through the theme's default text style: a document that defines none gets the
142
+ // converter's own text defaults (Inter 16 px, 400, line height 1.2, black).
143
+ const theme = { ...doc.theme, variableCollections: expressionVariables.at() }, defaultStyle = theme.defaultTextStyleId ?? '';
144
+ const model = (theme.textStyles?.[defaultStyle] ? { ...doc, assets: doc.assets ?? {}, theme } : { ...doc, assets: doc.assets ?? {}, theme: { ...theme, defaultTextStyleId: defaultStyle, textStyles: {
145
+ ...theme.textStyles, [defaultStyle]: { name: 'Default', fontFamily: 'Inter', fontSize: 16, fontWeight: 400, lineHeight: 1.2, letterSpacing: 0, color: '#000000' }
146
+ } } });
147
+ // The model whose variables the evaluator reads in `modes`: with aliases, followed in those modes (one per mode set).
148
+ const modeModels = new Map();
149
+ const modelIn = (modes, modesKey) => {
150
+ if (!expressionVariables.aliased)
151
+ return model;
152
+ let found = modeModels.get(modesKey);
153
+ if (!found)
154
+ modeModels.set(modesKey, found = { ...model, theme: { ...model.theme, variableCollections: expressionVariables.at(modes) } });
155
+ return found;
156
+ };
157
+ // ---- Resolved instances: which overrides and slot fills apply to a layer of an instance is taco's call
158
+ // (resolveInstance; resolveComponent for a component met on the page). Each layer takes from its ResolvedLayer what
159
+ // overrides set apart from sizes: visibility (conditions included), paints, effects, opacity, name, blend mode, text
160
+ // content, colour and alignment, the component an instance shows (swaps) and its property values, and the content
161
+ // a slot frame shows. The resolver lays its layers out again; their sizes and positions are not read here. The
162
+ // converter's own override maps (overridesFor) still feed its size rules: sizing, padding, line boxes, scale and
163
+ // variant sizes. Computed texts keep their stored frames (withoutTextMeasurement), as in `evaluated` below.
164
+ const resolveCache = createInstanceResolveCache();
165
+ function resolvedLayer(n, definition) {
166
+ try {
167
+ return withoutTextMeasurement(() => definition ? resolveComponent(model, definition.id, { cache: resolveCache }) : resolveInstance(model, n.id, { cache: resolveCache }).root);
168
+ }
169
+ catch (e) {
170
+ // Counted by kind; taco's message (a refused document or an evaluator failure alike) is the detail.
171
+ notApplied("instance not resolved (the converter's own overrides used)", e instanceof Error ? e.message : String(e));
172
+ return false;
173
+ }
174
+ }
175
+ // A layer's node in the document: a nested instance layer stands for its instance node, any other for its source.
176
+ const layerNodeId = (layer) => layer.instance?.instanceId ?? layer.sourceNodeId;
177
+ // Override fields the size rules read; the rest of an override map comes from the resolved layer.
178
+ const SIZE_OVERRIDES = new Set(['sizing', 'padding', 'textStyle', 'lineBoxOnly', 'frame', 'x', 'y', 'width', 'height', 'resizing', 'layoutPositioning', 'constraints', 'layout', 'variableModes', 'variableBindings', 'expressions']);
179
+ const SIZE_BINDINGS = new Set(['width', 'height', 'gap', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontFamily']);
180
+ function sizeOverrides(o) {
181
+ const out = {};
182
+ for (const [k, v] of Object.entries(o)) {
183
+ if (!SIZE_OVERRIDES.has(k))
184
+ continue;
185
+ if (k === 'textStyle') {
186
+ const { color, ...metrics } = v;
187
+ if (Object.keys(metrics).length)
188
+ out.textStyle = metrics;
189
+ continue;
190
+ }
191
+ if (k === 'variableBindings') {
192
+ const kept = Object.fromEntries(Object.entries(v).filter(([b]) => SIZE_BINDINGS.has(b)));
193
+ if (Object.keys(kept).length)
194
+ out.variableBindings = kept;
195
+ continue;
196
+ }
197
+ out[k] = v;
198
+ }
199
+ return out;
200
+ }
201
+ // Expressions whose result the resolved layer holds (with any override over it): the converter evaluates the rest.
202
+ const RESOLVED_FIELDS = new Set(['visible', 'opacity', 'fills', 'strokes', 'shadows', 'effects', 'cornerRadii', 'characters', 'textColor', 'componentId']);
203
+ const resolvedField = (key) => RESOLVED_FIELDS.has(key) || key.startsWith('propertyValues.');
204
+ const programs = new Map();
205
+ function programOf(comp) {
206
+ let entry = programs.get(comp.id);
207
+ if (!entry) {
208
+ const cache = new ExpressionCache(), program = checkComponentProgram(model, comp, cache);
209
+ // The fields and conditions that do not check ("node id\nfield").
210
+ const failed = new Map(program.errors.map((e) => [`${e.nodeId}\n${e.field}`, e.errors[0]?.message ?? 'invalid']));
211
+ entry = { program, cache, environments: new Map(), failed, results: new Map() };
212
+ programs.set(comp.id, entry);
213
+ }
214
+ return entry;
215
+ }
216
+ // An evaluation's key: the property values (once per props) and the modes (once per modes object).
217
+ const valuesKeys = new WeakMap(), modesKeys = new WeakMap();
218
+ function keysOf(props, modes) {
219
+ let values = valuesKeys.get(props);
220
+ if (values === undefined)
221
+ valuesKeys.set(props, values = JSON.stringify(filledPropertyValues(props.comp, props.values)));
222
+ let modesKey = modes ? modesKeys.get(modes) : '{}';
223
+ if (modesKey === undefined)
224
+ modesKeys.set(modes, modesKey = JSON.stringify(modes));
225
+ return { values, modesKey };
226
+ }
227
+ // The component `props` belong to (see propsOf), for them in `modes`: its layers (computed(), evaluated on first call:
228
+ // the computed layers, what was left out and the fields whose value the model refused, "node id\nfield"; null when a
229
+ // variable it reads has no value in these modes, as taco's evaluator then throws, and its fields are read alone), the
230
+ // value environment, and the reads made so far.
231
+ function evaluated(props, modes) {
232
+ const comp = props.comp, entry = programOf(comp), { values, modesKey } = keysOf(props, modes), key = `${values}|${modesKey}`;
233
+ let result = entry.results.get(key);
234
+ if (!result) {
235
+ const inModes = modelIn(modes, modesKey);
236
+ let layers, environment;
237
+ result = {
238
+ entry, layerReads: new Map(), sourceReads: new Map(),
239
+ computed: () => {
240
+ if (layers !== undefined)
241
+ return layers;
242
+ try {
243
+ // Computed texts keep their stored frames: this converter lays text out itself.
244
+ const computed = withoutTextMeasurement(() => evaluateComponentProgram(inModes, comp, entry.program, props.values, modes));
245
+ layers = { computed, refused: new Set(computed.errors.map((e) => `${e.nodeId}\n${e.field}`)) };
246
+ }
247
+ catch {
248
+ layers = null;
249
+ }
250
+ return layers;
251
+ },
252
+ environment: () => (environment ??= componentValueEnvironment(inModes, comp, props.values, undefined, modes)),
253
+ };
254
+ entry.results.set(key, result);
255
+ }
256
+ return result;
257
+ }
258
+ // A computed value as plain JSON, in the model's own shapes (colours as hex, enum options and components by name
259
+ // and id, effects as shadows or { kind: 'background-blur' | 'layer-blur', radius }).
260
+ const plain = (v) => {
261
+ switch (v.kind) {
262
+ case 'list': return v.items.map(plain);
263
+ case 'enum': return v.option;
264
+ case 'color': return expressionColorToHex(v.value);
265
+ case 'component': return v.id;
266
+ case 'size': return { width: v.width, height: v.height };
267
+ case 'point': return { x: v.x, y: v.y };
268
+ case 'effect': return v.value.kind === 'shadow' ? v.value.shadow : { kind: v.value.kind.replace('_', '-'), radius: v.value.radius };
269
+ default: return v.value;
270
+ }
271
+ };
272
+ const asValue = (read) => read.error !== undefined ? { error: read.error } : { value: read.on ?? plain(read.raw) };
273
+ // Layout fields the model writes only on an auto-layout frame of their kind (taco's applyComputedFields): on a frame
274
+ // without auto layout Figma shows no gap, padding or hug either.
275
+ const STACK_ONLY = new Set(['gap', 'wrapGap', 'direction', 'align', 'justify', 'wrap']), ANY_LAYOUT = new Set(['padding', 'layout.widthSizing', 'layout.heightSizing']);
276
+ function layoutIgnored(node, field) {
277
+ const kind = node?.layout?.kind;
278
+ if (ANY_LAYOUT.has(field))
279
+ return kind === undefined || kind === 'absolute';
280
+ if (STACK_ONLY.has(field))
281
+ return kind === undefined || kind === 'absolute' || kind === 'grid';
282
+ if (field === 'columnGap' || field === 'rowGap')
283
+ return kind !== 'grid';
284
+ return false;
285
+ }
286
+ // Field `field` of `node`, a layer of the component `props` belong to, as its expression computes it for them:
287
+ // { value }, or { error } when it is not computed (there is none, it does not check or its layer ignores it).
288
+ function layerValue(props, modes, node, field) {
289
+ const src = node.expressions?.[field];
290
+ if (src === undefined)
291
+ return { error: 'no expression' };
292
+ if (!props?.comp)
293
+ return sourceValue(onPage, modes, field, src, node);
294
+ const result = evaluated(props, modes), readKey = `${node.id}\n${field}`;
295
+ let read = result.layerReads.get(readKey);
296
+ if (!read)
297
+ result.layerReads.set(readKey, read = layerRead(result, props, modes, node, field, src));
298
+ return asValue(read);
299
+ }
300
+ function layerRead(result, props, modes, node, field, src) {
301
+ const { entry } = result, readKey = `${node.id}\n${field}`, error = entry.failed.get(readKey);
302
+ if (error !== undefined)
303
+ return { error };
304
+ if (layoutIgnored(node, field))
305
+ return { error: `${field} on a frame without auto layout` };
306
+ const layers = result.computed(), layer = layers?.computed.nodes.get(node.id);
307
+ const checked = entry.program.layers.get(node.id)?.fields.find((f) => f.field === field);
308
+ // A layer that is not one of the component's own (or one its program did not reach), or a component that could not
309
+ // be evaluated as a whole, reads its properties alone.
310
+ if (!layer || !checked)
311
+ return sourceRead(props, modes, field, src, node);
312
+ // A value the model refuses to store is still the expression's: a font family with no font asset (the kit's JSON
313
+ // carries none; this converter picks faces by family itself), or a transform that is not six numbers.
314
+ if (layers.refused.has(readKey)) {
315
+ const stored = storedFieldValue(model, node, field), base = result.environment();
316
+ return { raw: evaluateExpression(checked.expression, { ...base, stored, paintBox: () => paintBox(node) }) };
317
+ }
318
+ const value = storedFieldValue(model, layer, field);
319
+ return value === undefined ? { error: 'no value' } : { raw: value };
320
+ }
321
+ // Whether `node`'s condition shows it for `props`: true or false, or undefined when it has none that is checked.
322
+ function layerShown(props, modes, node) {
323
+ if (node.condition === undefined)
324
+ return undefined;
325
+ if (props?.comp) {
326
+ const result = evaluated(props, modes), { entry } = result;
327
+ if (entry.failed.has(`${node.id}\ncondition`))
328
+ return undefined;
329
+ const layers = result.computed();
330
+ if (layers && entry.program.layers.get(node.id)?.condition)
331
+ return !layers.computed.leftOut.has(node.id);
332
+ }
333
+ // A component root's condition (its program leaves it out), a layer outside a component, or a component that could
334
+ // not be evaluated as a whole: read alone.
335
+ return sourceValue(props?.comp ? props : onPage, modes, 'condition', node.condition).value;
336
+ }
337
+ // What a layer outside every component reads: no properties.
338
+ const onPage = new Map();
339
+ onPage.comp = { id: '', properties: [] };
340
+ onPage.values = {};
341
+ // Source `src` of field `field` (or a condition) that is not a component layer's own: an override's condition or
342
+ // expression, read with the properties `props` and evaluated alone, with `node` the layer it sets.
343
+ function sourceValue(props, modes, field, src, node) {
344
+ return props?.comp ? asValue(sourceRead(props, modes, field, src, node)) : { error: 'outside a component' };
345
+ }
346
+ function sourceRead(props, modes, field, src, node) {
347
+ const result = evaluated(props, modes), readKey = `${field}\n${node?.id ?? ''}\n${src}`;
348
+ let read = result.sourceReads.get(readKey);
349
+ if (!read)
350
+ result.sourceReads.set(readKey, read = evaluateSource(result, props, field, src, node));
351
+ return read;
352
+ }
353
+ function evaluateSource(result, props, field, src, node) {
354
+ const comp = props.comp, { entry } = result, condition = field === 'condition';
355
+ if (!condition && layoutIgnored(node, field))
356
+ return { error: `${field} on a frame without auto layout` };
357
+ const expected = condition ? EXPRESSION_TYPES.boolean : computableFieldType(model, node, field);
358
+ if (!expected)
359
+ return { error: `the field ${field} cannot be computed on this layer` };
360
+ const typeKey = condition ? '' : JSON.stringify(expected);
361
+ let environment = entry.environments.get(typeKey);
362
+ if (!environment)
363
+ entry.environments.set(typeKey, environment = componentExpressionEnvironment(model, comp, condition ? undefined : expected));
364
+ const checked = entry.cache.check(src, expected, environment, 0);
365
+ if (!checked.result.ok || !checked.expression)
366
+ return { error: checked.result.ok ? 'unparsed' : checked.result.errors[0]?.message ?? 'invalid' };
367
+ const base = result.environment(), stored = condition ? undefined : storedFieldValue(model, node, field);
368
+ let value;
369
+ // taco's evaluator throws on a variable with no value in these modes.
370
+ try {
371
+ value = evaluateExpression(checked.expression, { ...base, stored, paintBox: () => paintBox(node) });
372
+ }
373
+ catch (e) {
374
+ return { error: e instanceof Error ? e.message : String(e) };
375
+ }
376
+ if (condition)
377
+ return value.kind === 'boolean' ? { on: value.value } : { error: 'not a boolean' };
378
+ let refused = false;
379
+ const layer = withoutTextMeasurement(() => applyComputedFields(model, node, [{ field: field, value }], () => { refused = true; }));
380
+ // As in layerValue, a value the model refuses to store is still the expression's.
381
+ const back = refused ? value : storedFieldValue(model, layer, field);
382
+ return back === undefined ? { error: 'no value' } : { raw: back };
383
+ }
384
+ // An expression or condition that is not applied: counted once, by a stable kind; taco's message (or the converter's
385
+ // reason) is the detail, in the report's expressionErrors.
386
+ const expressionErrors = new Map();
387
+ const notApplied = (kind, error) => { drop(kind); expressionErrors.set(error, (expressionErrors.get(error) ?? 0) + 1); mark('expression', error); };
388
+ // A variant root's opacity in the stored variant (its properties `props`), or undefined when it cannot be evaluated.
389
+ function storedOpacity(n, props, modes) {
390
+ if (n.variableBindings?.opacity) {
391
+ const v = resolveVariable(n.variableBindings.opacity, modes);
392
+ return typeof v === 'number' ? v : undefined;
393
+ }
394
+ if (n.expressions?.opacity === undefined)
395
+ return n.opacity ?? 1;
396
+ const { value } = layerValue(props, modes, n, 'opacity');
397
+ return typeof value === 'number' ? value : undefined;
398
+ }
399
+ // ---- Component properties: defaults overlaid with propertyValues (by property id), as name → value, where an
400
+ // enum value is its option name, a boolean stays boolean, text is a string and an instance swap a component id.
401
+ // The map also keeps its component (comp) and the values by property id (values, an enum's as its option id), which
402
+ // expressions read.
403
+ function propsOf(comp, ...values) {
404
+ const out = new Map(), ids = {};
405
+ for (const p of comp.properties ?? []) {
406
+ let v = p.defaultValue;
407
+ for (const vals of values)
408
+ if (vals && p.id in vals)
409
+ v = vals[p.id];
410
+ if (p.kind === 'enum' && typeof v === 'string') {
411
+ const name = p.options?.find((o) => o.id === v)?.name ?? (v.includes('=') ? v.slice(v.indexOf('=') + 1) : v);
412
+ ids[p.id] = p.options?.find((o) => o.name === name)?.id ?? v;
413
+ v = name;
414
+ }
415
+ else
416
+ ids[p.id] = v;
417
+ out.set(p.name, v);
418
+ }
419
+ out.comp = comp;
420
+ out.values = ids;
421
+ return out;
422
+ }
423
+ // ---- Overrides: the enclosing instances' override maps (innermost first; outer ones win) keyed by source node id. Conditional
424
+ // entries name the component whose properties they read; the nearest enclosing instance of it supplies them.
425
+ function overridesFor(id, ctx) {
426
+ const out = {};
427
+ // Merged innermost first, so an outer instance's override wins (as in Figma).
428
+ const recorded = [];
429
+ for (let k = 0; k < ctx.ovr.length; k++) {
430
+ let o = ctx.ovr[k]?.[id];
431
+ if (!o)
432
+ continue;
433
+ if (o.shadows && recorded.length)
434
+ o = { ...o, shadows: boundShadowColours(o.shadows, recorded) };
435
+ for (const e of o.conditional ?? [])
436
+ if (e.value?.shadows)
437
+ recorded.push(e.value.shadows);
438
+ mergeOverride(out, o, ctx, false, ctx.comps[ctx.comps.length - 2 - k]);
439
+ }
440
+ return out;
441
+ }
442
+ // The kit exporter writes an outer instance's shadow override as a plain colour and drops the colour variable that
443
+ // the component's own (conditional) override binds (p0/p1/p8/p75 AvatarGroup rings: #ffffff on the page; #f5f5f5,
444
+ // bound to the card fill, in the component and in Figma). An outer plain shadow list that matches an inner
445
+ // conditional one in everything but colour (kind, offset, blur, spread) is that same effect, so it keeps the inner
446
+ // colour, whether or not the inner condition holds for the selected variant (Figma keeps the bound colour across the
447
+ // variant swap). The real fix belongs in the exporter: keep the binding in the instance override.
448
+ const sameShadowGeometry = (a, b) => a.length === b.length && a.every((s, i) => s.kind === b[i].kind && s.x === b[i].x && s.y === b[i].y && s.blur === b[i].blur && (s.spread ?? 0) === (b[i].spread ?? 0) && (s.visible ?? true) === (b[i].visible ?? true));
449
+ function boundShadowColours(shadows, recorded) {
450
+ const inner = recorded.findLast((r) => sameShadowGeometry(shadows, r) && r.some((s, i) => s.color !== shadows[i].color));
451
+ if (!inner)
452
+ return shadows;
453
+ approximate('outer shadow colours kept from the inner conditional override');
454
+ return shadows.map((s, i) => ({ ...s, color: inner[i].color }));
455
+ }
456
+ // Imported nested-instance overrides use paths such as "iconInstance;iconPath".
457
+ // Advance outer maps when entering that instance, keeping direct node-id overrides.
458
+ function descendOverrides(overrides, instanceId) {
459
+ const out = {}, prefix = `${instanceId};`;
460
+ for (const [key, value] of Object.entries(overrides ?? {}))
461
+ if (!key.includes(';'))
462
+ out[key] = value;
463
+ for (const [key, value] of Object.entries(overrides ?? {}))
464
+ if (key.startsWith(prefix))
465
+ out[key.slice(prefix.length)] = value;
466
+ return out;
467
+ }
468
+ function descendSlots(map, instanceId) {
469
+ const out = {}, prefix = `${instanceId};`;
470
+ for (const [key, value] of Object.entries(map))
471
+ if (key === instanceId)
472
+ out[''] = value;
473
+ else if (key.startsWith(prefix))
474
+ out[key.slice(prefix.length)] = value;
475
+ return out;
476
+ }
477
+ // Whether an instance's overrides set a (variant) line height anywhere inside it.
478
+ const hasLineBox = (o) => !!o && JSON.stringify(o).includes('"lineHeight"');
479
+ // A variant's conditional line-height override records the stale line box Figma stored for it. Figma keeps that box
480
+ // where the component's own layout is: on its page, and in an instance still at the component's size (or at its
481
+ // selected variant's, below); an instance it re-laid out (another size) has the glyph line height (p68 TimeField: 20
482
+ // px labels in the component set and 24 px in its resized Information instances; p15 calendar days stay 20 px).
483
+ // In such a resized instance Figma keeps the box line of auto-size text, wrapping (height: p14/p0 Card headers keep 16
484
+ // px descriptions in resized Cards) or single-line (width-and-height: p0's "$250" tooltip label is 16 px in a 24 px
485
+ // bubble, p63 Tabs labels 20 px; single-line text heights match Figma on 12,463 of the kit's texts, 11,603 before;
486
+ // p64 Table cells lose 72). An instance on the page (its stored size is the
487
+ // one Figma laid out) that comes out shorter with the stored line boxes than its stored size was re-laid out with
488
+ // glyph line heights everywhere inside (relaid: p67 TextField and p68 TimeField 88 px instances whose variants lay
489
+ // out at 80 or 84 px with a 16 px description; Figma draws the description 20 px). Nested instances keep their
490
+ // definition's sizes (p35 DropdownItem: 56 px in the ListBox component, 36 or 48 px in Figma), so they are not judged.
491
+ // A resized instance in slot content whose stored height only the stored line boxes lay out keeps them (kept: p34
492
+ // Drawer TextFields, below).
493
+ // An instance at its selected variant's size is at the component's size too: the variant's height expression (p7
494
+ // Autocomplete: 302 px open, 160 px empty, 328 px selected; the default variant is 60 px) gives its height, and its
495
+ // width is the component's, or any width when the variant is a fixed-width column (280 px closed Autocompletes keep
496
+ // the 20 px labels). Width matters elsewhere: p63 Tabs instances at a variant's height but another width were re-laid
497
+ // out. Nested instances inside such a variant-sized instance keep theirs, at any size (the selected Autocomplete's 86 px
498
+ // search field and its tags); inside an instance at the component's own size they do not (p28: the DatePicker's 64 px
499
+ // DateFields draw 24 px labels).
500
+ const asStored = (a, b) => !!a && !!b && Math.abs(a.width - b.width) < 0.01 && Math.abs(a.height - b.height) < 0.01;
501
+ // The size of the variant `props` select: the root's (or a hug wrapper root's one visual frame's) size expressions.
502
+ // An instance at that size also kept its component's layout (p53 RangeCalendarPopover .empty and .multi at 528 px,
503
+ // though the component root is stored at .filled's 544: Figma draws their 20 px time labels and 16 px tags).
504
+ const variantSource = (root) => !root.expressions?.width && !root.expressions?.height && root.children?.length === 1 ? doc.nodes[root.children[0]] ?? root : root;
505
+ function variantFrame(root, props, modes) {
506
+ const src = variantSource(root);
507
+ const out = { width: src.frame?.width, height: src.frame?.height };
508
+ for (const k of ['width', 'height']) {
509
+ if (!src.expressions?.[k])
510
+ continue;
511
+ const { value } = layerValue(props, modes, src, k);
512
+ if (typeof value === 'number')
513
+ out[k] = value;
514
+ }
515
+ return out;
516
+ }
517
+ // Whether the variant `props` select has a fixed width: the root's, or (in a hug wrapper root) that of the one visual
518
+ // frame its conditions keep (an icon-only Button or ToggleButton is a fixed 32, 36 or 40 px square).
519
+ function variantFixedWidth(root, props, modes) {
520
+ const kept = (root.children ?? []).map((id) => doc.nodes[id]).filter((c) => c && c.visible !== false && (!c.condition || layerShown(props, modes, c) === true));
521
+ const src = root.layout?.widthSizing === 'hug' && !root.expressions?.width && kept.length === 1 && kept[0].layout ? kept[0] : root;
522
+ const width = src.expressions?.['layout.widthSizing'] ? layerValue(props, modes, src, 'layout.widthSizing') : { value: src.layout?.widthSizing };
523
+ return width.value === 'fixed';
524
+ }
525
+ // An instance at its selected variant's size (variantFrame), or at that variant's height in a fixed-width vertical
526
+ // column at another width (p7's 280 px closed Autocompletes).
527
+ function atVariantSize(frame, root, props, modes) {
528
+ if (!frame || !root.frame)
529
+ return false;
530
+ const size = variantFrame(root, props, modes);
531
+ if (asStored(frame, size))
532
+ return true;
533
+ if (Math.abs(frame.height - size.height) >= 0.01)
534
+ return false;
535
+ // The selected variant's layout: its expressions (direction, layout.kind, layout.widthSizing) over the stored one.
536
+ const src = variantSource(root), ex = src.expressions ?? {};
537
+ const value = (key, fallback) => { if (!ex[key])
538
+ return fallback; const { value: v } = layerValue(props, modes, src, key); return typeof v === 'string' ? v : fallback; };
539
+ const kind = value(ex.direction ? 'direction' : 'layout.kind', src.layout?.kind);
540
+ return kind === 'vertical' && value('layout.widthSizing', src.layout?.widthSizing) === 'fixed';
541
+ }
542
+ // A plain (unconditional) line-height override is a line box Figma laid out and drew with where the instance that
543
+ // carries it sits (p44 Modal and p6 AlertDialog variants draw 20 px description lines), so it applies, except in an
544
+ // instance of the enclosing component that Figma re-laid out (the page's taller Modal and AlertDialog instances draw
545
+ // the style's 24 px lines, and wrap them afresh: a fill description stored 288 px wide and 3 lines tall is one line in
546
+ // a 640 px Modal, so such a text is measured, not kept). 'within' is the component that holds the overriding instance
547
+ // (undefined on the page).
548
+ const lineBoxOf = (within) => within?.definition === 'relaid' ? 'remeasure' : false;
549
+ function mergeOverride(out, o, ctx, conditional = false, within) {
550
+ if (o.textStyle?.lineHeight !== undefined)
551
+ out.lineBoxOnly = conditional || lineBoxOf(within);
552
+ for (const e of o.conditional ?? []) {
553
+ const scope = [...ctx.comps].reverse().find((c) => c.componentId === e.componentId);
554
+ if (!scope) {
555
+ drop('override condition: component not in scope');
556
+ continue;
557
+ }
558
+ const { value: on, error } = sourceValue(scope.props, ctx.modes, 'condition', e.condition), ok = error === undefined;
559
+ if (!ok)
560
+ notApplied('override condition not evaluated', error);
561
+ // A condition of plain `true` holds in every variant: an ordinary override, not a variant's stale line box
562
+ // (p53 RangeCalendarPopover's TagList labels are 16 px, the override's line height, in Figma).
563
+ if (ok && on && e.condition.trim() === 'true')
564
+ mergeOverride(out, e.value, ctx, conditional, within);
565
+ else if (ok && on)
566
+ mergeOverride(out, e.value, ctx, scope.definition === 'relaid' || conditional === 'relaid' ? 'relaid' : scope.definition || conditional === true ? true
567
+ // A resized instance nested in one at its component's size, whose line box reaches into a further nested instance
568
+ // (a Label): Figma laid it out in that component and re-hugged the Label around re-measured single-line text (p28
569
+ // DatePicker: its DateField's label draws 24 px, not the 20 px box line; p15 calendar days keep theirs).
570
+ : ctx.comps.slice(0, ctx.comps.indexOf(scope)).some((c) => c.definition === true) && ctx.comps.at(-1) !== scope ? 'nested' : 'instance');
571
+ }
572
+ for (const [k, v] of Object.entries(o)) {
573
+ if (k === 'conditional' || k === 'lineBoxOnly')
574
+ continue; // a name (a layer renamed in an instance) is kept
575
+ if (k === 'propertyValues')
576
+ out.propertyValues = { ...out.propertyValues, ...v };
577
+ else if (['textStyle', 'variableBindings', 'variableModes', 'expressions', 'style', 'sizing', 'padding'].includes(k))
578
+ out[k] = { ...out[k], ...v };
579
+ else
580
+ out[k] = v;
581
+ // Text set as characters or as paragraphs: the later (outer) one wins.
582
+ if (k === 'characters')
583
+ delete out.paragraphs;
584
+ else if (k === 'paragraphs')
585
+ delete out.characters;
586
+ }
587
+ }
588
+ // ---- Paints and colours.
589
+ const stops = (s) => s.map((x) => [Math.min(1, Math.max(0, x.offset)), rgba(x.color) ?? [0, 0, 0, 1]]);
590
+ // Whether a model draws a fill: its compact one, or a shown paint in look.fills.
591
+ const shownFills = (m) => !!m.fill || !!m.look?.fills?.some((p) => p.visible !== false);
592
+ // A paint for the wire (packages/editor/src/renderer/wire.ts paint()), or null when dropped. A hidden paint keeps its
593
+ // place in the list (visible: false), as Figma keeps it; one that would be dropped is left out without counting.
594
+ // tile: the scale of an image fill Figma tiles (figma-import's metadata.figma.tiles, see taco/.../carry.ts).
595
+ function paint(p, tile) {
596
+ if (p.visible === false) {
597
+ const had = new Map(dropped), q = paint({ ...p, visible: true }, tile);
598
+ dropped.clear();
599
+ for (const [k, v] of had)
600
+ dropped.set(k, v);
601
+ return q && { ...q, visible: false };
602
+ }
603
+ const o = p.opacity ?? 1;
604
+ if (p.kind === 'image' && tile !== undefined && tile > 0) {
605
+ const q = paint({ ...p, fit: 'cover' });
606
+ return q && { ...q, fit: 3, scale: tile };
607
+ }
608
+ if (p.kind === 'solid') {
609
+ const c = rgba(p.color);
610
+ if (!c) {
611
+ drop('paint: colour not a hex');
612
+ return null;
613
+ }
614
+ return { k: 'solid', c, o };
615
+ }
616
+ if (p.kind === 'linear-gradient') {
617
+ if (!p.from || !p.to)
618
+ throw new Error('Linear gradient requires from and to endpoints');
619
+ return { k: 'linear', from: [p.from.x, p.from.y], to: [p.to.x, p.to.y], stops: stops(p.stops), o };
620
+ }
621
+ if (p.kind === 'radial-gradient')
622
+ return { k: 'radial', cx: p.center?.x ?? 0.5, cy: p.center?.y ?? 0.5, rx: p.radius?.x || 0.5, ry: p.radius?.y || 0.5, stops: stops(p.stops), o };
623
+ if (p.kind === 'angular-gradient')
624
+ return { k: 'angular', cx: p.center?.x ?? 0.5, cy: p.center?.y ?? 0.5, start: p.angle ?? 0, stops: stops(p.stops), o };
625
+ // Image fills: the source keeps only the asset and its fit (none = Figma FILL, i.e. cover; 'fill' = STRETCH).
626
+ // Figma's crop transform and tile mode are not in the source, so CROP draws stretched and TILE draws as cover, unless
627
+ // supplement.mjs supplies them from the plugin export (a tile becomes fit 3 with its scale, wire.ts paint()).
628
+ if (p.kind === 'image') {
629
+ const asset = doc.assets?.[p.assetId];
630
+ if (asset?.kind !== 'image' || asset.source?.kind !== 'data') {
631
+ drop('image fill: asset missing or not inline data');
632
+ return null;
633
+ }
634
+ return { k: 'image', asset: p.assetId, fit: { contain: 0, fit: 0, cover: 1, fill: 2, stretch: 2 }[p.fit] ?? 1, o };
635
+ }
636
+ drop(`paint ${p.kind}`);
637
+ return null;
638
+ }
639
+ // ---- Nodes.
640
+ const models = [];
641
+ // Instance roots that are bare hug wrappers, with their variant root and padding (see the check after conversion).
642
+ const wrappers = [];
643
+ let serial = 0, depthMax = 0;
644
+ const newId = () => `h${(serial++).toString(36)}`;
645
+ // The source's rotation turns clockwise on screen (y down) for positive degrees: p23's vertical ColorSlider at -90°
646
+ // has its thumb at the top and the gradient's orange end above, as Figma draws it; p34's TextArea grip at 45° leans /.
647
+ const turn = (deg) => { const r = (deg * Math.PI) / 180; return [Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r)]; };
648
+ // The source's x, y place a rotated node's box as if unrotated; it turns about the box's centre (p63 Tabs scroll
649
+ // shadows at -90° land where Figma draws them; p59 Spinner rings at 178° keep x, y near 0).
650
+ const transformOf = (f, rotation) => {
651
+ if (!rotation)
652
+ return [1, 0, 0, 1, f.x, f.y].map((v) => +v.toFixed(4));
653
+ const [a, b, c, d] = turn(rotation), cx = (f.width ?? 0) / 2, cy = (f.height ?? 0) / 2;
654
+ return [a, b, c, d, f.x + cx - (a * cx + c * cy), f.y + cy - (b * cx + d * cy)].map((v) => +v.toFixed(4));
655
+ };
656
+ // Visits source node n under harness parent `parent`. ctx: owner (the property map the node's own conditions and
657
+ // expressions read), comps (enclosing instances: { componentId, props }), ovr (their override maps, innermost first).
658
+ // place: an instance's frame and rotation, for a component root expanded in its place.
659
+ // rs: how the parent's size changed from its stored one ({ dw, dh, sx, sy }), when it has no auto layout: the node
660
+ // follows its constraints (an instance sized unlike its component, or a frame resized by that).
661
+ const STYLE_KEYS = ['fills', 'strokes', 'shadows', 'cornerRadii', 'cornerRadius'];
662
+ // The style keys a component's `effects` expression computes.
663
+ const EFFECT_KINDS = ['shadows', 'backgroundBlur', 'layerBlur'];
664
+ // A Figma mask (mask: true; maskType alpha, the default, vector or luminance) becomes the renderer's mask flag (SPEC
665
+ // 4.4): an alpha mask over the later siblings. A vector mask masks with its outline, so it is sent opaque, without
666
+ // strokes or effects (a .fig import carries an outline mask as metadata.figma.maskType "vector"). The renderer has no
667
+ // luminance mask: such a mask is dropped and its siblings drawn unmasked.
668
+ // Sibling ranges are settled by applyMasks once the parent's children are converted.
669
+ // layer: n's ResolvedLayer; undefined outside every resolved instance (one met there is resolved), false where the
670
+ // converter's own overrides apply (a trial layout of another variant, or an instance the resolver refused).
671
+ function visit(n, parent, ctx, place = null, depth = 0, rs = null, layer) {
672
+ const previous = active;
673
+ active = {};
674
+ try {
675
+ if (!n.mask && !n.isMask)
676
+ return visitNode(n, parent, ctx, place, depth, rs, layer);
677
+ const type = String(n.maskType ?? n.metadata?.figma?.maskType ?? 'alpha').toLowerCase();
678
+ if (type === 'luminance') {
679
+ drop('luminance mask (no renderer equivalent; mask skipped, siblings unmasked)');
680
+ return;
681
+ }
682
+ const item = visitNode(n, parent, ctx, place, depth, rs, layer);
683
+ if (!item)
684
+ return item;
685
+ item.model.mask = true;
686
+ note('masks');
687
+ if (type === 'vector') {
688
+ const m = item.model;
689
+ if (m.kind === 'text')
690
+ drop('vector mask on text (masked by its glyph alpha)');
691
+ else {
692
+ m.fill = [0, 0, 0, 1];
693
+ delete m.stroke;
694
+ delete m.strokeWidth;
695
+ delete m.look;
696
+ note('vector masks sent opaque');
697
+ }
698
+ }
699
+ return item;
700
+ }
701
+ finally {
702
+ active = previous;
703
+ }
704
+ }
705
+ // Figma masks every later sibling with a mask, later masks included (masks nest); the renderer's range ends at the
706
+ // next mask (SPEC 4.4). So a later mask and the siblings after it move into a plain, unfilled, unclipped frame that
707
+ // the earlier mask masks. A mask with nothing after it draws nothing in Figma but stays visible in the renderer
708
+ // (SPEC 5.13 quirk), so it is not sent. Runs after layout: the wrapper changes no positions.
709
+ function applyMasks(m, children) {
710
+ const at = children.findIndex((c) => c.model.mask);
711
+ if (at < 0)
712
+ return;
713
+ const rest = children.slice(at + 1);
714
+ if (!rest.length) {
715
+ removeSubtree(children[at].model.id);
716
+ note('masks with nothing after them (not drawn)');
717
+ return;
718
+ }
719
+ const next = rest.findIndex((c) => c.model.mask);
720
+ if (next < 0)
721
+ return;
722
+ const inner = rest.slice(next), wrapper = { id: newId(), parent: m.id, name: 'Mask group', opacity: 1, kind: 'frame', t: [1, 0, 0, 1, 0, 0], w: m.w, h: m.h, clip: false };
723
+ models.splice(models.indexOf(inner[0].model), 0, wrapper);
724
+ for (const c of inner)
725
+ c.model.parent = wrapper.id;
726
+ note('masks nested in a wrapper frame');
727
+ applyMasks(wrapper, inner);
728
+ }
729
+ function removeSubtree(id) {
730
+ const gone = new Set([id]);
731
+ for (const m of models)
732
+ if (gone.has(m.parent))
733
+ gone.add(m.id);
734
+ let j = 0;
735
+ for (const m of models)
736
+ if (!gone.has(m.id))
737
+ models[j++] = m;
738
+ models.length = j;
739
+ }
740
+ function visitNode(n, parent, ctx, place = null, depth = 0, rs = null, layer) {
741
+ depthMax = Math.max(depthMax, depth);
742
+ if (depth > 64) {
743
+ drop('instance nesting deeper than 64');
744
+ return;
745
+ }
746
+ // A component root met on the page (the component itself) reads its own default properties.
747
+ const definition = !place && rootOf.get(n.id);
748
+ // An instance's root takes the instance's layer, which stands for both.
749
+ layer ??= place?.layer;
750
+ if (layer === undefined && (n.type === 'instance' || definition))
751
+ layer = resolvedLayer(n, definition);
752
+ const L = layer || undefined, r = L?.node;
753
+ const full = overridesFor(n.id, ctx), o = L ? sizeOverrides(full) : full, eff = { ...n, ...o };
754
+ ctx = { ...ctx, modes: { ...ctx.modes, ...n.variableModes, ...o.variableModes, ...place?.variableModes } };
755
+ // Resolve bindings on the effective stored paints first; expressions replace these
756
+ // fallbacks below. Clone paints so expanding one instance never changes another.
757
+ // A resolved layer's paints have its overrides, computed fields and bound variables applied.
758
+ const style = L ? { ...r.style } : { ...n.style, ...o.style };
759
+ if (!L)
760
+ for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius'])
761
+ if (o[k] !== undefined)
762
+ style[k] = o[k];
763
+ if (L) {
764
+ // The resolver writes a bound or computed radius as one cornerRadius; a layer that stores per-corner radii keeps
765
+ // them as four equal ones, as the converter writes them.
766
+ if (style.cornerRadii === undefined && n.style?.cornerRadii && style.cornerRadius !== undefined) {
767
+ const v = style.cornerRadius;
768
+ style.cornerRadii = { topLeft: v, topRight: v, bottomRight: v, bottomLeft: v };
769
+ }
770
+ // An instance's own paints set on a hug wrapper root belong to its variant's visual frame (see `own` below).
771
+ if (ctx.moved?.id === n.id)
772
+ Object.assign(style, ctx.moved.style);
773
+ if (place?.moved)
774
+ for (const k of place.moved)
775
+ style[k] = n.style?.[k];
776
+ // A kit export fix, so it reads the export's override maps (see boundShadowColours).
777
+ if (style.shadows?.length) {
778
+ const recorded = ctx.ovr.flatMap((m) => (m?.[n.id]?.conditional ?? []).filter((e) => e.value?.shadows).map((e) => e.value.shadows));
779
+ if (recorded.length)
780
+ style.shadows = boundShadowColours(style.shadows, recorded);
781
+ }
782
+ // An instance's root keeps its own opacity: the instance's replaces it by the variant opacity rule (variantOpacity).
783
+ Object.assign(eff, place ? {} : { opacity: r.opacity }, { name: r.name, blendMode: r.blendMode });
784
+ if (n.type === 'instance')
785
+ eff.componentId = L.instance.componentId;
786
+ }
787
+ const allBindings = { ...n.variableBindings, ...o.variableBindings };
788
+ const bindings = L ? Object.fromEntries(Object.entries(allBindings).filter(([k]) => SIZE_BINDINGS.has(k) || (place && k === 'opacity'))) : allBindings;
789
+ for (const key of ['fillColor', 'strokeColor', 'textColor']) {
790
+ if (!bindings[key] || (explicit && key !== 'textColor'))
791
+ continue;
792
+ const value = resolveVariable(bindings[key], ctx.modes);
793
+ if (value === undefined || !rgba(value)) {
794
+ drop(`variable binding: ${key}`);
795
+ continue;
796
+ }
797
+ if (key === 'fillColor')
798
+ style.fills = (style.fills ?? []).map((p) => p.kind === 'solid' ? { ...p, color: value } : p);
799
+ if (key === 'strokeColor')
800
+ style.strokes = (style.strokes ?? []).map((s) => s.paint?.kind === 'solid' ? { ...s, paint: { ...s.paint, color: value } } : s);
801
+ if (key === 'textColor')
802
+ eff.textColor = value;
803
+ }
804
+ // Number bindings (sizes, spacing, radius, stroke width, opacity) take the variable's value in the node's modes.
805
+ for (const [key, id] of Object.entries(bindings)) {
806
+ if (!id || ['fillColor', 'strokeColor', 'textColor'].includes(key))
807
+ continue;
808
+ const v = resolveVariable(id, ctx.modes);
809
+ if (key === 'fontFamily' && typeof v === 'string') {
810
+ eff.fontFamily = v;
811
+ continue;
812
+ }
813
+ if (explicit && key === 'visibility' && typeof v === 'boolean') {
814
+ eff.visible = v;
815
+ continue;
816
+ }
817
+ if (explicit && key === 'fontSize' && typeof v === 'number') {
818
+ eff.fontSize = v;
819
+ continue;
820
+ }
821
+ if (explicit && key === 'wrapGap' && typeof v === 'number') {
822
+ eff.layout = { ...eff.layout, wrapGap: v };
823
+ continue;
824
+ }
825
+ if (typeof v !== 'number') {
826
+ approximate(`variable binding ${key}: not a number (stored value used)`);
827
+ continue;
828
+ }
829
+ const pad = /^padding(Top|Right|Bottom|Left)$/.exec(key);
830
+ if (key === 'width' || key === 'height')
831
+ eff[key] = v;
832
+ else if (key === 'opacity')
833
+ eff.opacity = v;
834
+ else if (key === 'gap')
835
+ eff.layout = { ...eff.layout, gap: v };
836
+ else if (pad)
837
+ eff.layout = { ...eff.layout, padding: { ...eff.layout?.padding, [pad[1].toLowerCase()]: v } };
838
+ else if (key === 'cornerRadius') {
839
+ style.cornerRadius = v;
840
+ if (style.cornerRadii)
841
+ style.cornerRadii = { topLeft: v, topRight: v, bottomRight: v, bottomLeft: v };
842
+ }
843
+ else if (key === 'strokeWidth')
844
+ style.strokes = (style.strokes ?? []).map((s) => ({ ...s, width: v }));
845
+ else {
846
+ if (!explicit)
847
+ approximate(`variable binding ${key} (stored value used)`);
848
+ continue;
849
+ }
850
+ note('number variable bindings applied');
851
+ }
852
+ // A resolved layer's visibility has its conditions, computed field and overrides applied (an instance's root takes
853
+ // the instance's, checked there).
854
+ if (L) {
855
+ if (!place)
856
+ eff.visible = r.visible !== false;
857
+ }
858
+ else if (o.visible !== undefined)
859
+ eff.visible = o.visible;
860
+ // The export keeps no visibility for a slot's items: an instance that swaps a slot child hidden in the component
861
+ // to another component shows it (p53 RangeCalendarPopover's TagList: Tag 4, and Tag 5 in .multi, are drawn).
862
+ // A kit export fix, so it reads the export's override maps: an override that sets the component (whichever) and not
863
+ // the visibility of a child hidden as stored and by no expression.
864
+ if (eff.visible === false && slotChildren.has(n.id) && (L ? n.visible === false && !n.expressions?.visible && full.visible === undefined && full.componentId !== undefined : o.componentId !== undefined))
865
+ eff.visible = true;
866
+ let owner = ctx.owner;
867
+ if (definition) {
868
+ owner = propsOf(definition);
869
+ ctx = { ...ctx, owner, comps: [...ctx.comps, { componentId: definition.id, props: owner, definition: true }] };
870
+ }
871
+ if (eff.condition && !L) {
872
+ const shown = eff.condition === n.condition ? layerShown(owner, ctx.modes, n) : sourceValue(owner, ctx.modes, 'condition', eff.condition).value;
873
+ if (shown === undefined)
874
+ drop('node condition not applied');
875
+ else if (!shown) {
876
+ note('nodes hidden by a condition');
877
+ return;
878
+ }
879
+ }
880
+ // A style value set by an override wins over the component's own expression for it (as in Figma).
881
+ // So do overridden text, property values, visibility and layout: the expressions encode the variant's own values.
882
+ const ownExpressions = Object.fromEntries(Object.entries(n.expressions ?? {}).filter(([key]) => !overridden(key, o)));
883
+ // The run colours a resolved text's override only copies, once its colour expression has evaluated (eff.textColor).
884
+ let copiedColours = L && n.type === 'text' ? snapshotColours(n, r, full, owner) : undefined, colourEvaluated = false;
885
+ for (const [key, src] of Object.entries({ ...ownExpressions, ...o.expressions })) {
886
+ if (L && resolvedField(key) && !(place && key === 'opacity') && !(copiedColours && key === 'textColor'))
887
+ continue;
888
+ const { value: v, error } = o.expressions?.[key] !== undefined ? sourceValue(owner, ctx.modes, key, src, n) : layerValue(owner, ctx.modes, n, key);
889
+ if (error !== undefined) {
890
+ notApplied(`expression not applied: ${key.replace(/\..*/, '.*')}`, error);
891
+ continue;
892
+ }
893
+ applyExpression(eff, key, v, key in ownExpressions && !o.expressions?.[key]);
894
+ if (key === 'textColor')
895
+ colourEvaluated = !!(v?.hex || typeof v === 'string');
896
+ // An override that sets only some effect kinds replaces only those; the rest come from the expression (p71
897
+ // Information model: a vertical attached Toolbar overrides its background blur, 40, and keeps its shadows).
898
+ if (key === 'effects' && !o.expressions?.effects)
899
+ for (const k of EFFECT_KINDS)
900
+ if (o[k] !== undefined || o.style?.[k] !== undefined)
901
+ delete eff[`style.${k}`];
902
+ }
903
+ // An instance's opacity is its variant root's in Figma: it replaces that root's own or evaluated opacity, never
904
+ // multiplies it (the kit copies the variant's opacity onto every instance, so p25's disabled swatches drew at 0.25).
905
+ if (ctx.variantOpacity?.id === n.id)
906
+ eff.opacity = ctx.variantOpacity.opacity;
907
+ if (!colourEvaluated)
908
+ copiedColours = undefined;
909
+ if (eff.visible === false && !explicit) {
910
+ note('hidden nodes skipped');
911
+ return;
912
+ }
913
+ if (n.flipX || n.flipY)
914
+ drop('instance flip');
915
+ const frame = place?.frame ?? eff.frame, rotation = place?.rotation ?? eff.rotation ?? 0;
916
+ // The layer's name: the source's (an override may rename it); a component root expanded in an instance's place takes
917
+ // the instance's name, as Figma's layers panel shows it.
918
+ const common = { id: newId(), sourceId: n.id, parent, name: String(place?.name ?? eff.name ?? ''), opacity: +(eff.opacity ?? 1) };
919
+ if (eff.visible === false)
920
+ common.visible = false;
921
+ active.id = common.id;
922
+ // The layer's export settings (an instance's own go to its expanded root, never its component's).
923
+ const exports = place ? place.exports : exportsOf(eff.exportSettings);
924
+ if (exports)
925
+ common.exports = exports;
926
+ // The node's blend mode (an instance's applies to its expanded root, which takes this common record).
927
+ const mode = place?.blendMode ?? eff.blendMode, blend = mode === undefined ? 0 : BLEND_MODES.indexOf(mode);
928
+ if (blend > 0)
929
+ common.blend = blend;
930
+ else if (blend < 0)
931
+ drop(`blend mode ${mode}`);
932
+ if (n.type === 'instance') {
933
+ const comp = doc.components[eff.componentId];
934
+ if (!comp) {
935
+ drop('instance of a missing component');
936
+ return;
937
+ }
938
+ const root = doc.nodes[comp.rootId];
939
+ const props = L ? propsOf(comp, L.instance.propertyValues) : propsOf(comp, n.propertyValues, eff.exprProps, o.propertyValues);
940
+ // Style set on the instance itself (an enclosing instance's override keyed by its id, e.g. an avatar's image)
941
+ // belongs to the variant's root: the component root, or its only same-size child frame when the root is a bare
942
+ // wrapper. It wins over the instance's own overrides and over the component's expressions there.
943
+ const own = Object.fromEntries(STYLE_KEYS.filter((k) => o[k] !== undefined).map((k) => [k, o[k]]));
944
+ if (o.style)
945
+ own.style = o.style;
946
+ if (Object.keys(own).length && o.variableBindings)
947
+ own.variableBindings = o.variableBindings;
948
+ const only = root.children?.length === 1 && doc.nodes[root.children[0]], bare = !root.style?.fills?.length && !root.expressions?.fills;
949
+ const target = bare && only?.type === 'frame' && only.frame?.width === root.frame?.width && only.frame?.height === root.frame?.height ? only.id : root.id;
950
+ const ovr = [eff.overrides, ...ctx.ovr.map((o) => descendOverrides(o, n.id))];
951
+ if (!L && Object.keys(own).length)
952
+ ovr.push({ [target]: own });
953
+ // The resolver applies them to the root; on a bare wrapper root they move to its visual frame.
954
+ const ownKeys = L && target !== root.id ? [...STYLE_KEYS.filter((k) => full[k] !== undefined), ...Object.keys(full.style ?? {})] : [];
955
+ // Slot contents: an instance's slots map a nested-instance path ('' = this instance) to property id → the node
956
+ // whose children fill that slot frame. They are converted in the instance's own (outer) context.
957
+ const slots = [...(ctx.slots ?? []).map((e) => ({ ...e, map: descendSlots(e.map, n.id) })), ...(eff.slots ? [{ map: eff.slots, ctx }] : [])];
958
+ const variant = (!asStored(frame, root.frame) && atVariantSize(frame, root, props, ctx.modes))
959
+ || (ctx.ovr.length > 0 && !!ctx.comps.at(-1)?.variant && [true, 'kept'].includes(ctx.comps.at(-1).definition));
960
+ const inner = { owner: props, comps: [...ctx.comps, { componentId: comp.id, props, definition: asStored(frame, root.frame) || variant, variant }], ovr, modes: ctx.modes, slots, keptLayout: ctx.keptLayout };
961
+ // The opacity stored on an instance is a copy of its variant root's when it equals that root's opacity in the
962
+ // stored variant; such a copy follows the variant an enclosing override or expression picks (p25's swatches
963
+ // disabled by an outer override), while a different value is the instance's own and is kept (p64's hidden check).
964
+ // Resolved, an opacity the instance's overrides, bindings or expression set differs from its stored one.
965
+ const setOpacity = L ? r.opacity !== n.opacity || !!n.variableBindings?.opacity || n.expressions?.opacity !== undefined
966
+ : o.opacity !== undefined || !!bindings.opacity || n.expressions?.opacity !== undefined || o.expressions?.opacity !== undefined;
967
+ const stored = propsOf(comp, n.propertyValues), sameVariant = eff.componentId === n.componentId && [...props].every(([k, v]) => stored.get(k) === v);
968
+ if (eff.opacity !== undefined && (setOpacity || sameVariant || n.opacity !== storedOpacity(doc.nodes[target], stored, ctx.modes)))
969
+ inner.variantOpacity = { id: target, opacity: common.opacity };
970
+ note('instances expanded');
971
+ const placed = { name: common.name, blendMode: eff.blendMode, exports, stored: root.frame, frame: { ...root.frame, ...frame, width: eff.width ?? frame.width, height: eff.height ?? frame.height, x: eff.x ?? frame.x, y: eff.y ?? frame.y }, rotation, sizing: eff.sizing, resizing: eff.resizing, layoutPositioning: eff.layoutPositioning, constraints: eff.constraints, variableModes: { ...n.variableModes, ...o.variableModes }, layer, ...(ownKeys.length ? { moved: ownKeys } : {}) };
972
+ if (ownKeys.length)
973
+ inner.moved = { id: target, style: Object.fromEntries(ownKeys.map((k) => [k, r.style?.[k]])) };
974
+ // A swapped component (an override or expression changed componentId) keeps the instance's size only when that
975
+ // size was set (it differs from the replaced component's); otherwise it takes its own size, as in Figma.
976
+ const was = doc.nodes[doc.components[n.componentId]?.rootId]?.frame, same = (a, b) => Math.abs(a - b) < 0.01;
977
+ // An instance on the page scaled with Figma's scale tool (and possibly resized), shown by its overrides
978
+ // (overrideScale): the overrides it scaled are taken back to the component's scale for the layout at size / s.
979
+ let scaled = 1;
980
+ if (trials === 0 && !ctx.ovr.length && eff.componentId === n.componentId) {
981
+ const { s, sure } = overrideScale(eff.overrides, comp, props, ctx.modes);
982
+ if (s !== 1) {
983
+ const unscaled = unscale(eff.overrides, s), resizing = unscale(placed.resizing, s);
984
+ let fits = sure;
985
+ if (!fits) {
986
+ // Padding or line heights alone: the instance's box must also be s times its natural size on an axis.
987
+ let nat;
988
+ trials++;
989
+ try {
990
+ nat = naturalSize(root, parent, { ...inner, ovr: [unscaled, ...ovr.slice(1)] }, { ...placed, resizing }, depth);
991
+ }
992
+ finally {
993
+ trials--;
994
+ }
995
+ const near = (a, b) => Math.abs(a - b) <= 0.01 * b;
996
+ fits = !!nat?.w && !!nat.h && (near(placed.frame.width / nat.w, s) || near(placed.frame.height / nat.h, s));
997
+ }
998
+ if (fits) {
999
+ ovr[0] = unscaled;
1000
+ placed.resizing = resizing;
1001
+ scaled = s;
1002
+ note('instances scaled (scale inferred from their overrides)');
1003
+ }
1004
+ }
1005
+ }
1006
+ if (eff.componentId !== n.componentId && was && was !== root.frame && same(was.width, frame.width) && same(was.height, frame.height)) {
1007
+ Object.assign(placed, { frame: { ...placed.frame, width: root.frame.width, height: root.frame.height }, swapped: true });
1008
+ note('swapped instances sized by their component');
1009
+ }
1010
+ else if (scaled === 1 && eff.componentId === n.componentId && !sizeOverridden(o) && trials === 0) {
1011
+ // An override that changes only property values selects another variant of the same component. Like a swap,
1012
+ // the instance takes that variant's size, on each axis where its size is the original variant's (one it set,
1013
+ // or an explicitly overridden size, wins). Variants here are one component's conditional children, so both
1014
+ // sizes are found by laying the component out with the original and with the new property values.
1015
+ const given = {};
1016
+ for (const key of Object.keys(n.expressions ?? {}))
1017
+ if (key.startsWith('propertyValues.')) {
1018
+ const { value } = layerValue(owner, ctx.modes, n, key);
1019
+ if (value !== undefined)
1020
+ given[key.slice(15)] = value;
1021
+ }
1022
+ const before = propsOf(comp, n.propertyValues, given);
1023
+ if ([...props].some(([k, v]) => before.get(k) !== v)) {
1024
+ let old, now;
1025
+ trials++;
1026
+ // The original variant is laid out on the converter's own overrides (layer false), which take it from
1027
+ // `before`: the resolver has no "what if" for a property value an enclosing override sets.
1028
+ try {
1029
+ old = naturalSize(root, parent, { ...inner, owner: before, comps: [...ctx.comps, { componentId: comp.id, props: before, definition: inner.comps.at(-1).definition }] }, { ...placed, layer: false }, depth);
1030
+ now = old && naturalSize(root, parent, inner, placed, depth);
1031
+ }
1032
+ finally {
1033
+ trials--;
1034
+ }
1035
+ const near = (a, b) => Math.abs(a - b) <= 0.5;
1036
+ if (old && now)
1037
+ for (const [k, m] of [['width', 'w'], ['height', 'h']]) {
1038
+ if (near(old[m], placed.frame[k]) && !near(now[m], placed.frame[k])) {
1039
+ placed.frame = { ...placed.frame, [k]: now[m] };
1040
+ note('instances sized by the variant their property overrides select');
1041
+ }
1042
+ // A nested instance's stored size is its component's layout, not one Figma made for these properties, so a
1043
+ // hug height follows the change even where the stored one is not what the original properties lay out (p0
1044
+ // Cover Card headers: 60 px stored, 52 laid out, 20 once the outer Card hides the description).
1045
+ else if (k === 'height' && ctx.ovr.length && !near(old[m], now[m]) && root.layout?.heightSizing === 'hug' && !eff.sizing?.height) {
1046
+ placed.frame = { ...placed.frame, height: now[m] };
1047
+ note('nested hug instances sized by the variant their property overrides select');
1048
+ }
1049
+ // Its width does too where the variant selected has a fixed width (p75 Desktop - 2: the icon-only heart
1050
+ // ToggleButton in a Card is 36 px square, not the 86 px it is stored at).
1051
+ else if (k === 'width' && ctx.ovr.length && !near(old[m], now[m]) && root.layout?.widthSizing === 'hug' && !eff.sizing?.width && variantFixedWidth(root, props, ctx.modes)) {
1052
+ placed.frame = { ...placed.frame, width: now[m] };
1053
+ note('nested hug instances sized by the fixed-width variant their property overrides select');
1054
+ }
1055
+ }
1056
+ // A root its component sizes by expression, kept 'fixed' by an override, lays out at the stored size either
1057
+ // way: the variants' own sizes tell (p53 ButtonGroup buttons swapped to .md are 36 px, not .sm's 32).
1058
+ const was = variantFrame(root, before, ctx.modes), will = variantFrame(root, props, ctx.modes);
1059
+ if (old && now)
1060
+ for (const [k, m] of [['width', 'w'], ['height', 'h']]) {
1061
+ if (near(old[m], now[m]) && near(was[k], placed.frame[k]) && !near(will[k], placed.frame[k])) {
1062
+ placed.frame = { ...placed.frame, [k]: will[k] };
1063
+ note('instances sized by the variant size their property overrides select');
1064
+ }
1065
+ }
1066
+ }
1067
+ }
1068
+ // A resized instance on the page whose stored height is what its variant's line boxes lay out (with nested hug
1069
+ // instances following them, below) kept them: Figma laid it out with those boxes (p34 Drawer forms: 60 px
1070
+ // TextFields with 20 px labels, 64 px with the 24 px glyph line height). A height both lay out tells nothing.
1071
+ // Judged only in an instance's slot content for now: elsewhere (p14 Card, p63 Tabs) it is right for the instance
1072
+ // but moves neighbours whose own errors it had offset, and those pages compare worse.
1073
+ if (trials === 0 && scaled === 1) {
1074
+ let nat, kept;
1075
+ trials++;
1076
+ try {
1077
+ nat = naturalSize(root, parent, inner, placed, depth);
1078
+ if (!ctx.ovr.length && !inner.comps.at(-1).definition && ctx.inSlot && hasLineBox(eff.overrides))
1079
+ kept = naturalSize(root, parent, { ...inner, comps: [...ctx.comps, { ...inner.comps.at(-1), definition: 'kept' }] }, placed, depth);
1080
+ }
1081
+ finally {
1082
+ trials--;
1083
+ }
1084
+ // An instance stored at another width than it lays out at was resized in Figma, which re-laid it out: its
1085
+ // stored height and those inside it are re-hugged ones (p14 Cards, p63 Tabs, p7 Autocomplete lists). A hug-width
1086
+ // root that fills its parent was only stretched by it (p53 two-month Calendar, selected-range rows).
1087
+ const stretched = (eff.resizing?.width ?? eff.sizing?.width) === 'fill' && root.layout?.widthSizing === 'hug';
1088
+ const resized = nat && Math.abs(nat.w - placed.frame.width) > 0.5 && !stretched;
1089
+ if (resized)
1090
+ inner.comps.at(-1).resized = true;
1091
+ if (kept && nat && Math.abs(kept.h - placed.frame.height) <= 0.5 && Math.abs(nat.h - placed.frame.height) > 0.5) {
1092
+ inner.comps.at(-1).definition = 'kept';
1093
+ note('resized instances that keep their variant line boxes');
1094
+ }
1095
+ else if (nat && placed.frame.height - nat.h > 0.5 && !ctx.ovr.length)
1096
+ inner.comps.at(-1).definition = 'relaid';
1097
+ // One stored shorter than its contents was not re-hugged by Figma: it keeps its height and clips the rest (p53
1098
+ // RangeCalendarPopover: .filled instances stay 528 px, not the variant's 544; the Calendar in RangeCalendar
1099
+ // stays 296 px), so the editor must not grow it either. Not inside an instance Figma re-laid out ('relaid',
1100
+ // above), a resized one or one that kept its line boxes: there it re-hugs too (p67 TextField and p68 TimeField
1101
+ // labels are 24 px). A swapped instance takes its new component's size (above).
1102
+ else if (nat && nat.h - placed.frame.height > 0.5 && !resized && !ctx.comps.some((c) => ['relaid', 'kept'].includes(c.definition) || c.resized)) {
1103
+ placed.sizing = { ...placed.sizing, height: 'fixed' };
1104
+ placed.keepHeight = true;
1105
+ inner.keptLayout = true;
1106
+ }
1107
+ }
1108
+ // Inside an instance that kept its line boxes, a nested hug instance in its flow, sized by its variant's height
1109
+ // expression, follows them as Figma re-hugged it (p34 Drawer: Label instances 20 px around a 20 px label, not the
1110
+ // 24 px the TextField variant stores). Also inside the trial layouts above, where variant sizing is skipped.
1111
+ if (scaled === 1 && ctx.comps.at(-1)?.definition === 'kept' && eff.componentId === n.componentId && eff.variantSize?.height !== undefined
1112
+ && root.layout?.heightSizing === 'hug' && eff.layoutPositioning !== 'absolute' && !sizeOverridden(o) && !eff.sizing?.height) {
1113
+ let nat;
1114
+ trials++;
1115
+ try {
1116
+ nat = naturalSize(root, parent, inner, placed, depth);
1117
+ }
1118
+ finally {
1119
+ trials--;
1120
+ }
1121
+ if (nat?.h && Math.abs(nat.h - placed.frame.height) > 0.5) {
1122
+ placed.frame = { ...placed.frame, height: nat.h };
1123
+ note('nested hug instances that follow kept line boxes');
1124
+ }
1125
+ }
1126
+ let s = scaled !== 1 ? scaled : ctx.ovr.length || place?.trial ? 1 : instanceScale(root, parent, inner, placed, depth);
1127
+ if (s === 1 && scaled === 1 && trials === 0 && !ctx.ovr.length && !place?.trial) {
1128
+ // Scaled below 1 and resized, with no padding override: line heights that agree on one k (see lineHeightScale).
1129
+ const k = lineHeightScale(eff.overrides);
1130
+ if (k !== 1) {
1131
+ const unscaled = unscale(eff.overrides, k);
1132
+ let nat;
1133
+ trials++;
1134
+ try {
1135
+ nat = naturalSize(root, parent, { ...inner, ovr: [unscaled, ...ovr.slice(1)] }, placed, depth);
1136
+ }
1137
+ finally {
1138
+ trials--;
1139
+ }
1140
+ // Line heights also size unscaled variants, so the box must be k times the natural size on both axes.
1141
+ const fits = (axis, m) => !!nat?.[m] && Math.abs(nat[m] * k - placed.frame[axis]) <= 0.05 * placed.frame[axis];
1142
+ if (fits('width', 'w') && fits('height', 'h')) {
1143
+ s = scaled = k;
1144
+ ovr[0] = unscaled;
1145
+ note('instances scaled (scale read from agreeing line heights)');
1146
+ }
1147
+ }
1148
+ }
1149
+ const markInstance = (item) => {
1150
+ active.id = item.model.id;
1151
+ item.fromInstance = true;
1152
+ if (explicit && eff.visible === false)
1153
+ item.model.visible = false;
1154
+ if (explicit && !doc.componentPlacements?.[n.id]) {
1155
+ item.model.fileInstance = n.id;
1156
+ if (n.slots?.[''])
1157
+ item.model.fileFills = Object.values(n.slots['']);
1158
+ }
1159
+ if (doc.componentPlacements?.[n.id] === comp.id)
1160
+ item.model.mainOf = comp.id;
1161
+ else if (!n.fileExpanded) {
1162
+ item.model.instanceOf = comp.id;
1163
+ markSet(item.model, comp, props);
1164
+ }
1165
+ };
1166
+ if (s === 1) {
1167
+ const item = visit(root, parent, inner, placed, depth + 1);
1168
+ if (item) {
1169
+ markInstance(item);
1170
+ if (kitFixes)
1171
+ topAlignTallInput(item, comp);
1172
+ }
1173
+ return item;
1174
+ }
1175
+ // A scale read from the box: the scale tool's overrides still hold scaled lengths (p1 Calendar day line boxes).
1176
+ if (scaled === 1)
1177
+ ovr[0] = unscale(eff.overrides, s);
1178
+ // A scaled instance (Figma's scale tool): its contents are laid out at size / s and drawn scaled by s.
1179
+ note('instances scaled (scale inferred from their natural size)');
1180
+ const item = visit(root, parent, inner, { ...placed, frame: { ...placed.frame, width: placed.frame.width / s, height: placed.frame.height / s } }, depth + 1);
1181
+ if (item) {
1182
+ if (kitFixes)
1183
+ topAlignTallInput(item, comp);
1184
+ for (let i = 0; i < 4; i++)
1185
+ item.model.t[i] = +(item.model.t[i] * s).toFixed(6);
1186
+ markInstance(item);
1187
+ }
1188
+ return item;
1189
+ }
1190
+ const f = { ...frame };
1191
+ for (const k of ['x', 'y', 'width', 'height'])
1192
+ if ((!place || ((place.trial || place.swapped) && k in (eff.variantSize ?? {}))) && eff[k] !== undefined)
1193
+ f[k] = eff[k];
1194
+ // A path follows its constraint in shapeNode, from its stored place (moved here too, it would move twice).
1195
+ if (rs && !place && f.width !== undefined && n.shape !== 'path')
1196
+ follow(f, eff.constraints, rs);
1197
+ // Absolute children follow constraints; auto-layout children are positioned below.
1198
+ // A size from the component's own expressions is the variant's size, which its children were placed in.
1199
+ const from = place?.stored ?? { ...frame, ...eff.variantSize }, free = !eff.layout || eff.layout.kind === 'absolute';
1200
+ let mine = null;
1201
+ if (from?.width !== undefined && (f.width !== from.width || f.height !== from.height)) {
1202
+ if (free)
1203
+ mine = { dw: f.width - from.width, dh: f.height - from.height, sx: from.width ? f.width / from.width : 1, sy: from.height ? f.height / from.height : 1 };
1204
+ }
1205
+ // A group with no constraints of its own and upright (host-layout's passes) passes its frame's resize to its
1206
+ // children, which scale measured in the frame: `at` is where their space starts in it (its constraints did not move
1207
+ // it). Any other group resized itself above, and its children follow that in its own space, as a frame's do.
1208
+ if (n.type === 'group' && !(place?.constraints ?? eff.constraints) && transformOf(f, rotation).slice(0, 4).join() === '1,0,0,1') {
1209
+ mine = rs && { ...rs, at: [(rs.at?.[0] ?? 0) + (f.x ?? 0), (rs.at?.[1] ?? 0) + (f.y ?? 0)] };
1210
+ }
1211
+ for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius'])
1212
+ if (eff[`style.${k}`] !== undefined)
1213
+ style[k] = eff[`style.${k}`];
1214
+ if (n.type === 'frame' || n.type === 'group') {
1215
+ const m = { ...common, kind: 'frame', t: transformOf(f, rotation), w: f.width, h: f.height, clip: !!(eff.clipContent) };
1216
+ appearance(m, style, 'frame', n.metadata?.figma);
1217
+ const r = radii(style);
1218
+ if (r)
1219
+ m.radius = r;
1220
+ if (explicit && style.cornerSmoothing)
1221
+ m.smoothing = style.cornerSmoothing;
1222
+ if (definition)
1223
+ m.mainOf = definition.id; // link.ts makes it the component's main
1224
+ if (n.type === 'group') {
1225
+ m.group = true;
1226
+ note('groups marked as groups');
1227
+ }
1228
+ models.push(m);
1229
+ // The outermost instance that fills a slot wins, as an outer override does (p7 Autocomplete: the selected state's
1230
+ // search field fills its tag list with five tags; the tag list instance inside it fills the same slot with three).
1231
+ const children = [];
1232
+ if (L) {
1233
+ // The resolved layer's children, in paint order: those its conditions keep, or the content of the slot host it
1234
+ // shows (converted in the context of the instance whose slot map names that host).
1235
+ const host = L.slot?.hostId, filled = host !== undefined && ((ctx.slots ?? []).find((e) => e.map['']?.[n.slot] === host)
1236
+ ?? (ctx.slots ?? []).find((e) => Object.values(e.map).some((m) => Object.values(m ?? {}).includes(host))));
1237
+ if (host !== undefined) {
1238
+ if (explicit)
1239
+ m.fileSlotHost = host;
1240
+ note('slots filled');
1241
+ }
1242
+ else if ((n.children?.length ?? 0) > L.children.length)
1243
+ note('nodes hidden by a condition', n.children.length - L.children.length);
1244
+ // A host no enclosing slot map names is converted in the slot frame's own context.
1245
+ if (host !== undefined && !filled)
1246
+ approximate("slot hosts no slot map names (converted in the slot frame's context)");
1247
+ for (const c of L.children) {
1248
+ const child = doc.nodes[layerNodeId(c)];
1249
+ if (!child) {
1250
+ drop('missing child');
1251
+ continue;
1252
+ }
1253
+ const converted = visit(child, m.id, host !== undefined ? { ...(filled ? filled.ctx : ctx), inSlot: true } : ctx, null, depth, mine, c); // inSlot: see 'kept'
1254
+ if (converted)
1255
+ children.push(converted);
1256
+ }
1257
+ }
1258
+ else {
1259
+ const filled = n.slot && (ctx.slots ?? []).find((e) => doc.nodes[e.map['']?.[n.slot]]);
1260
+ if (filled)
1261
+ note('slots filled');
1262
+ for (const c of filled ? doc.nodes[filled.map[''][n.slot]].children ?? [] : n.children ?? []) {
1263
+ const child = doc.nodes[c];
1264
+ if (!child) {
1265
+ drop('missing child');
1266
+ continue;
1267
+ }
1268
+ const converted = visit(child, m.id, filled ? { ...filled.ctx, inSlot: true } : ctx, null, depth, mine, layer === false ? false : undefined); // inSlot: see 'kept'
1269
+ if (converted)
1270
+ children.push(converted);
1271
+ }
1272
+ }
1273
+ const viewportTransform = n.metadata?.svgViewportTransform;
1274
+ if (viewportTransform)
1275
+ for (const { model } of children)
1276
+ model.t = mul(viewportTransform, model.t).map((v) => +v.toFixed(6));
1277
+ // The height of the row a text's stored height was laid out in: the kit's own frame, not an instance's resized box
1278
+ // (see layoutFrame). Outside auto layout the stored height places nothing.
1279
+ for (const c of children) {
1280
+ if (!c.model?.storedHeight)
1281
+ continue;
1282
+ if (eff.layout && n.frame?.height > 0)
1283
+ c.model.storedRow = n.frame.height;
1284
+ else
1285
+ delete c.model.storedHeight;
1286
+ }
1287
+ stretchLines(n, children);
1288
+ // A trial layout (instanceScale) or a swapped component sizes the root as its component does, except that a
1289
+ // swapped instance filling its parent keeps filling it (Figma keeps the slot's fill across a swap: p7
1290
+ // Autocomplete's search field fills its 248 px list box instead of hugging its component's 280 px; p0 Cover menu
1291
+ // rows are 248 px, not 220).
1292
+ const own = (axis) => place?.swapped && place.resizing?.[axis] === 'fill' ? 'fill' : n.layout?.[`${axis}Sizing`];
1293
+ const item = { model: m, node: { ...eff, sizing: place?.trial || place?.swapped ? { width: own('width'), height: own('height') } : place?.sizing ?? eff.sizing, layoutPositioning: place?.layoutPositioning ?? eff.layoutPositioning, constraints: place?.constraints ?? eff.constraints, resizing: { ...eff.resizing, ...place?.resizing } }, children, instance: !!place && !place.trial && !place.swapped, swapped: !!place?.swapped };
1294
+ // A frame holding text an override changed, which the editor measures: Figma re-hugs it (see crossContent).
1295
+ item.remeasured = children.some((c) => c.changedText || c.remeasured);
1296
+ if (item.remeasured)
1297
+ item.node.rehug = true;
1298
+ // Inside an instance stored shorter than its contents (keepHeight, keptLayout) Figma did not lay the contents out
1299
+ // again: a hug frame around a stale-box text (storedHeight) keeps its stored height, as the text keeps its place
1300
+ // (p23 ColorSlider: a 40 px instance, re-hugged around 16 px label boxes, draws its 20 px header and the bar 24 px
1301
+ // down, past its bottom).
1302
+ item.keptHeight = !!ctx.keptLayout && n.layout?.heightSizing === 'hug' && !item.node.sizing?.height && children.some((c) => c.model?.storedHeight > c.model.h || c.keptHeight);
1303
+ if (item.keptHeight) {
1304
+ item.node.sizing = { ...item.node.sizing, height: 'fixed' };
1305
+ note('hug frames around stale-box text kept inside instances stored shorter than their contents');
1306
+ }
1307
+ m.layoutData = layoutData(item.node, item.instance);
1308
+ // Figma lays out again an instance it re-hugs, nested instances and all, and stores the result: where the stored
1309
+ // main-axis size is not what its children's stored sizes add up to, the nested ones were laid out anew and the
1310
+ // editor must not hold them at their stored sizes either (`relaid`, scene.ts fit; p67 TextField fields are 88 px
1311
+ // around 20 px label rows holding 24 px text). One that adds up keeps them (p67's TextField component set). An
1312
+ // instance stored smaller than its children add up to was laid out anew as well, re-hugged or not (p35's Share
1313
+ // menu is stored 154 px around 234 px of rows; Figma draws all four), except a wrapper, which keeps its box (see
1314
+ // `wrappers`).
1315
+ const lay = item.node.layout, axis = lay?.kind === 'horizontal' ? 'w' : 'h';
1316
+ if (item.instance && ['horizontal', 'vertical'].includes(lay?.kind) && !lay.wrap && [undefined, 'start', 'center', 'end'].includes(lay.justify) && lay[axis === 'w' ? 'widthSizing' : 'heightSizing'] === 'hug' && (item.remeasured || !wrapped(item))) {
1317
+ const flowing = children.filter((c) => c.model && c.node.visible !== false && c.node.layoutPositioning !== 'absolute');
1318
+ const pad = { top: 0, right: 0, bottom: 0, left: 0, ...lay.padding, ...item.node.padding };
1319
+ const sum = flowing.reduce((t, c) => t + c.model[axis], 0) + (lay.gap ?? 0) * Math.max(0, flowing.length - 1) + (axis === 'w' ? pad.left + pad.right : pad.top + pad.bottom);
1320
+ if (flowing.length && (item.remeasured ? Math.abs(sum - m[axis]) : sum - m[axis]) > 0.5) {
1321
+ m.layoutData.relaid = true;
1322
+ note('instances Figma laid out anew, nested instances and all');
1323
+ // Nor at the sizes the stored-size rule below froze them at: the kit's stored sizes inside such an instance
1324
+ // can be out of date (p44's mobile Modal stores its slot at 144 around a header and body Figma laid out to 80
1325
+ // and 72, so the slot is 160 and the footer gap 20 px, not 4).
1326
+ const unfreeze = (it) => {
1327
+ for (const c of it.children ?? []) {
1328
+ const sizing = c.model?.layoutData?.sizing;
1329
+ if (c.frozen && sizing) {
1330
+ for (const a of c.frozen)
1331
+ delete sizing[a];
1332
+ if (!Object.keys(sizing).length)
1333
+ delete c.model.layoutData.sizing;
1334
+ note('hug frames re-hugged inside instances Figma laid out anew');
1335
+ }
1336
+ unfreeze(c);
1337
+ }
1338
+ };
1339
+ unfreeze(item);
1340
+ }
1341
+ }
1342
+ const variant = wrapped(item);
1343
+ if (variant)
1344
+ wrappers.push([m, variant.model, { top: 0, right: 0, bottom: 0, left: 0, ...item.node.layout.padding, ...item.node.padding }]);
1345
+ layoutFrame(item);
1346
+ // A hug frame stored as resizing 'fixed' hugs here, but where hugging gives back its stored size the editor keeps
1347
+ // that size: a later re-measure (of text, say) must not move what already matches Figma. A frame holding text an
1348
+ // override changed (which the editor measures) still hugs, as Figma re-hugs it: p73's "Bold", "Italic" and
1349
+ // "Underline" toggles are 67, 69 and 106 px wide, not the 181 px of their variant's "Call to action". layoutFrame
1350
+ // keeps an instance root at its placed size, so what hugging gives back is its children's extent (p75 Overview
1351
+ // Cards: a 60 px stored body whose texts hug to 52 re-hugs, as Figma did).
1352
+ for (const [axis, key] of [['width', 'w'], ['height', 'h']]) {
1353
+ if (item.node.sizing?.[axis] === undefined && item.node.resizing?.[axis] === 'fixed' && item.node.layout?.[`${axis}Sizing`] === 'hug' && Math.abs((item.instance ? hugged(item, axis) ?? m[key] : m[key]) - f[axis]) < 0.01 && !item.remeasured) {
1354
+ m.layoutData.sizing = { ...m.layoutData.sizing, [axis]: 'fixed' };
1355
+ (item.frozen ??= []).push(axis);
1356
+ }
1357
+ }
1358
+ // A hug frame on the page (in no instance) keeps the size it was laid out at until an edit inside it (keepSize:
1359
+ // scene.ts layout): the editor's text measures must not re-hug what Figma stored (p63's Information frame). Only
1360
+ // one that places its children from its start along each axis it hugs: a frame centring them along an axis held
1361
+ // at its size would move all of them by half of any error in their sizes (p14's Frame 13: footers 4 px too tall
1362
+ // shifted the column up). A row centred along its fixed width still keeps the height it hugs (p7's sections).
1363
+ const main = lay?.kind === 'horizontal' ? 'width' : 'height';
1364
+ const hugAxes = ['width', 'height'].filter((axis) => (item.node.sizing?.[axis] ?? lay?.[`${axis}Sizing`]) === 'hug');
1365
+ const fromStart = hugAxes.every((axis) => [undefined, 'start'].includes(axis === main ? lay?.justify : lay?.align));
1366
+ if (!ctx.comps.length && !place && hugAxes.length && fromStart) {
1367
+ m.keepSize = true;
1368
+ if (Math.abs(m.w - f.width) > 0.01 || Math.abs(m.h - f.height) > 0.01)
1369
+ approximate('page-level hug frames laid out at other than their stored size');
1370
+ }
1371
+ if (kitFixes)
1372
+ squareJoined(item);
1373
+ // The visual frame a hug wrapper root gave that kept height holds it too (layoutFrame's wrapper allocation); a
1374
+ // component swapped in there takes its own size.
1375
+ if (place?.keepHeight && !children[0]?.swapped && eff.layout?.kind === 'vertical' && eff.layout.heightSizing === 'hug' && children.length === 1 && ['horizontal', 'vertical'].includes(children[0].model.layoutData?.layout?.kind)) {
1376
+ const p = eff.layout?.padding ?? {};
1377
+ resize(children[0], { height: Math.max(0, m.h - (p.top ?? 0) - (p.bottom ?? 0)) });
1378
+ children[0].model.layoutData.sizing = { ...children[0].model.layoutData.sizing, height: 'fixed' };
1379
+ }
1380
+ applyMasks(m, children);
1381
+ return item;
1382
+ }
1383
+ if (n.type === 'text') {
1384
+ const model = textNode(n, L ? { ...eff, ...resolvedText(r, full, eff, copiedColours) } : eff, o, common, f, rotation, style);
1385
+ model.layoutData = layoutData(eff);
1386
+ const stored = (n.paragraphs ?? []).map((p) => (p.runs ?? []).map((r) => r.text ?? '').join('')).join('\n');
1387
+ return { model, node: eff, children: [], changedText: eff.autoResize === 'width-and-height' && model.content !== stored };
1388
+ }
1389
+ if (n.type === 'shape') {
1390
+ const model = shapeNode(n, eff, common, f, rotation, style, rs);
1391
+ if (model)
1392
+ model.layoutData = { ...layoutData(eff), ...model.layoutData };
1393
+ return model ? { model, node: eff, children: [] } : undefined;
1394
+ }
1395
+ drop(`node type ${n.type}`);
1396
+ }
1397
+ // The host document drops a vector's auto-layout sizing (Figma's layoutAlign STRETCH). A straight line across an
1398
+ // auto-layout row or column that spans the frame's whole stored inner cross size is a stretched divider: it fills the
1399
+ // cross axis, so it shortens with added padding (p73 ToggleButtonGroup dividers: 32 px stored, 20 px in Figma once the
1400
+ // group pads them by 10 px).
1401
+ function stretchLines(n, children) {
1402
+ const layout = n.layout;
1403
+ if (!['horizontal', 'vertical'].includes(layout?.kind) || layout.wrap || !n.frame)
1404
+ return;
1405
+ const [cross, main] = layout.kind === 'horizontal' ? ['height', 'width'] : ['width', 'height'];
1406
+ const p = { top: 0, right: 0, bottom: 0, left: 0, ...layout.padding };
1407
+ const inner = n.frame[cross] - (cross === 'height' ? p.top + p.bottom : p.left + p.right);
1408
+ for (const child of children) {
1409
+ if (child.model.kind !== 'path' || child.node.resizing || child.node.layoutPositioning === 'absolute')
1410
+ continue;
1411
+ const b = pathBounds(child.model);
1412
+ if (b[main] > 0.01 || inner <= 0 || Math.abs(b[cross] - inner) > 0.01)
1413
+ continue;
1414
+ child.node = { ...child.node, resizing: { [cross]: 'fill' } };
1415
+ child.model.layoutData = layoutData(child.node);
1416
+ approximate('straight lines stretched across their auto-layout frame');
1417
+ }
1418
+ }
1419
+ // The host document drops three of Figma's overrides on an Input instance that fills its parent's height, which makes
1420
+ // it taller than it hugs (a TextArea's field, p1 Getting Started; p34, p44, p66 and p75 forms): its placeholder
1421
+ // wrapper fills the field's height (stored 'fixed'), the field and the wrapper align their children to the top
1422
+ // (Figma's MIN, which the source cannot say), and the placeholder fills the wrapper's width with an auto height,
1423
+ // wrapping. Without them the placeholder sits centred in the tall field; Figma draws it top-left. The instance is
1424
+ // stretched only later, by its parent's layout, so the rule reads its fill sizing, not its size. Inputs that hug or
1425
+ // keep a fixed height are left as they are.
1426
+ function topAlignTallInput(item, comp) {
1427
+ if (comp.name !== 'Input' || item.children.length !== 1)
1428
+ return;
1429
+ const field = item.children[0], layout = field.node.layout, fills = (c) => (c.node.sizing?.height ?? c.node.resizing?.height) === 'fill';
1430
+ if (!fills(item) || !fills(field) || field.model.kind !== 'frame' || layout?.kind !== 'horizontal' || layout.heightSizing !== 'hug')
1431
+ return;
1432
+ const wrapper = flowOf(field).find((c) => c.model.kind === 'frame' && c.node.layout?.kind === 'horizontal' && flowOf(c).some((t) => t.model.kind === 'text'));
1433
+ if (!wrapper)
1434
+ return;
1435
+ // Rebuilt from the node, the layout data loses the stored sizes the stored-size rule froze, so their mark (`frozen`)
1436
+ // goes too: left, a re-laid ancestor's unfreeze would delete the wrapper's fill height (and it would hug its text).
1437
+ const set = (c, node) => { c.node = node; c.model.layoutData = layoutData(node); delete c.frozen; };
1438
+ set(field, { ...field.node, layout: { ...layout, align: 'start' } });
1439
+ set(wrapper, { ...wrapper.node, layout: { ...wrapper.node.layout, align: 'start' }, sizing: { ...wrapper.node.sizing, height: 'fill' } });
1440
+ for (const t of flowOf(wrapper)) {
1441
+ if (t.model.kind !== 'text')
1442
+ continue;
1443
+ set(t, { ...t.node, autoResize: 'height', wrap: 'wrap', sizing: { ...t.node.sizing, width: 'fill' } });
1444
+ t.model.autoResize = 1;
1445
+ t.model.wrap = 1;
1446
+ delete t.model.keepSize;
1447
+ }
1448
+ layoutFrame(item);
1449
+ approximate('tall Input instances top-aligned');
1450
+ }
1451
+ // An attached button group: an auto-layout frame that clips to rounded corners, with no gap and no padding, around two
1452
+ // or more filled instances. Figma draws its buttons square and lets the group round the ends (all 118 such frames in
1453
+ // the kit's reference export, ButtonGroup and ToggleButtonGroup; a detached group has a gap and keeps round buttons).
1454
+ // The host document drops that radius override, so the buttons' own radius is removed here.
1455
+ function squareJoined(item) {
1456
+ const { model: m, node: n } = item, layout = n.layout;
1457
+ if (!['horizontal', 'vertical'].includes(layout?.kind) || !m.clip || !m.radius || layout.gap)
1458
+ return;
1459
+ const p = { ...layout.padding, ...n.padding };
1460
+ if (['top', 'right', 'bottom', 'left'].some((k) => p[k]))
1461
+ return;
1462
+ // The visual frame of an instance: its root, or the one same-size frame inside a bare wrapper root.
1463
+ const visual = (c) => c.model.radius || c.model.fill || shownFills(c.model) ? c.model
1464
+ : c.children.length === 1 && c.children[0].model.kind === 'frame' && c.children[0].model.w === c.model.w && c.children[0].model.h === c.model.h ? c.children[0].model : c.model;
1465
+ const buttons = flowOf(item).filter((c) => c.fromInstance).map(visual).filter((v) => shownFills(v));
1466
+ if (buttons.length < 2)
1467
+ return;
1468
+ for (const v of buttons)
1469
+ if (v.radius) {
1470
+ delete v.radius;
1471
+ approximate('buttons squared inside an attached group');
1472
+ }
1473
+ }
1474
+ const flowOf = (item) => item.children.filter((c) => c.model && c.node.visible !== false && c.node.layoutPositioning !== 'absolute');
1475
+ // The size an auto-layout frame hugging its flow children has on `axis` (their boxes as placed, turned or scaled, plus
1476
+ // gaps and padding); undefined for a wrap row or a frame with no flow children.
1477
+ function hugged(item, axis) {
1478
+ const layout = item.node.layout, kids = flowOf(item);
1479
+ if (!['horizontal', 'vertical'].includes(layout?.kind) || layout.wrap || !kids.length)
1480
+ return undefined;
1481
+ const box = (c) => {
1482
+ if (c.model.kind === 'path' || !c.model.t) {
1483
+ const b = c.model.kind === 'path' ? pathBounds(c.model) : { width: c.model.w, height: c.model.h };
1484
+ return b[axis];
1485
+ }
1486
+ const [a, b, cc, d] = c.model.t;
1487
+ return axis === 'width' ? Math.abs(a) * c.model.w + Math.abs(cc) * c.model.h : Math.abs(b) * c.model.w + Math.abs(d) * c.model.h;
1488
+ };
1489
+ const p = { top: 0, right: 0, bottom: 0, left: 0, ...layout.padding, ...item.node.padding };
1490
+ const pad = axis === 'width' ? p.left + p.right : p.top + p.bottom, sizes = kids.map(box);
1491
+ const along = (layout.kind === 'horizontal') === (axis === 'width');
1492
+ return pad + (along ? sizes.reduce((x, y) => x + y, 0) + (layout.gap ?? 0) * (kids.length - 1) : Math.max(...sizes));
1493
+ }
1494
+ // Whether an override sets what the component's own expression `key` computes.
1495
+ function overridden(key, o) {
1496
+ if (STYLE_KEYS.includes(key))
1497
+ return o[key] !== undefined || o.style?.[key] !== undefined;
1498
+ if (key === 'characters')
1499
+ return o.characters !== undefined || o.paragraphs !== undefined;
1500
+ if (key.startsWith('propertyValues.'))
1501
+ return o.propertyValues?.[key.slice(15)] !== undefined;
1502
+ if (key === 'effects')
1503
+ return EFFECT_KINDS.every((k) => o[k] !== undefined || o.style?.[k] !== undefined);
1504
+ if (key === 'textColor')
1505
+ return o.textColor !== undefined || !!o.variableBindings?.textColor;
1506
+ if (['fontSize', 'fontWeight'].includes(key))
1507
+ return o.textStyle?.[key] !== undefined;
1508
+ if (key === 'lineHeightMultiplier')
1509
+ return o.textStyle?.lineHeight !== undefined;
1510
+ if (key === 'padding')
1511
+ return o.padding !== undefined || o.layout?.padding !== undefined;
1512
+ if (['gap', 'align', 'justify'].includes(key))
1513
+ return o.layout?.[key] !== undefined;
1514
+ if (key === 'layout.widthSizing' || key === 'resizing.width')
1515
+ return o.sizing?.width !== undefined;
1516
+ if (key === 'layout.heightSizing' || key === 'resizing.height')
1517
+ return o.sizing?.height !== undefined;
1518
+ return ['visible', 'opacity', 'componentId', 'clipContent', 'textAlign'].includes(key) && o[key] !== undefined;
1519
+ }
1520
+ // An instance's root laid out at its component's own size (as a swapped component is), leaving no trace: its
1521
+ // models, ids and counts are discarded. Returns the laid-out model ({ w, h }), or undefined.
1522
+ function naturalSize(root, parent, inner, placed, depth) {
1523
+ const mark = models.length, ids = serial;
1524
+ const diagnostics = [dropped, notes, approximations, weights, expressionErrors];
1525
+ const counts = diagnostics.map((map) => new Map(map));
1526
+ probing++;
1527
+ try {
1528
+ return visit(root, parent, inner, { ...placed, frame: { ...placed.frame, width: root.frame.width, height: root.frame.height }, trial: true }, depth + 1)?.model;
1529
+ }
1530
+ finally {
1531
+ probing--;
1532
+ models.length = mark;
1533
+ serial = ids;
1534
+ for (const [i, m] of diagnostics.entries()) {
1535
+ m.clear();
1536
+ for (const [k, v] of counts[i])
1537
+ m.set(k, v);
1538
+ }
1539
+ }
1540
+ }
1541
+ // Nesting of the trials that size an instance's original variant; inside one, property overrides do not resize.
1542
+ let trials = 0;
1543
+ // Whether an override sets the instance's size (which then wins over the size of the variant it selects).
1544
+ function sizeOverridden(o) {
1545
+ return ['frame', 'width', 'height'].some((k) => o[k] !== undefined) || ['width', 'height'].some((k) => o.expressions?.[k] !== undefined || o.variableBindings?.[k] !== undefined);
1546
+ }
1547
+ // The source keeps no scale factor for an instance scaled with Figma's scale tool: only its scaled box. Infer it for
1548
+ // an auto-layout instance placed on the page (not inside another instance) by laying the instance out at its
1549
+ // natural size: a box s times that size on both axes is a scale by s. A scaled instance that was also resized is
1550
+ // not detected (its scale cannot be told from a resize without the factor).
1551
+ function instanceScale(root, parent, inner, placed, depth) {
1552
+ if (!['horizontal', 'vertical'].includes(root.layout?.kind))
1553
+ return 1;
1554
+ const trial = naturalSize(root, parent, inner, placed, depth);
1555
+ if (!trial?.w || !trial.h)
1556
+ return 1;
1557
+ const sx = placed.frame.width / trial.w, sy = placed.frame.height / trial.h, near = (a, b, e) => Math.abs(a - b) <= e * b;
1558
+ return near(sx, sy, 0.01) && !near(sy, 1, 0.02) && sy > 0.25 && sy < 4 ? +sy.toFixed(4) : 1;
1559
+ }
1560
+ // Figma's scale tool stores what it scales in an instance as overrides: padding, and each text's line height (its
1561
+ // scaled line box over the unscaled font size, which it does not store). Returns the scale s these show (1 for none)
1562
+ // and whether padding shows it. Padding overrides on two or more sides that are one multiple s of the component's
1563
+ // padding occur in the kit on scaled instances (p0 Cover: Button and Cards at 1.6), but need a second signal (line
1564
+ // heights at the same s, padding off the half-pixel grid, or a box s times the natural size; see the caller). Line heights alone are
1565
+ // weaker (a variant's stale line box gives 20/24 px ratios, and a hidden text's box may be another variant's), so they
1566
+ // count only as a ratio above 1 shared by texts with two different line boxes (box height over font size; p0 Cover
1567
+ // TextField: 24/14 and 20/14 px boxes at 1.6).
1568
+ function overrideScale(overrides, comp, props, modes) {
1569
+ const padding = [], lineHeight = [];
1570
+ let offGrid = false;
1571
+ // A node's own expression (direct overrides only: a nested instance's node reads that instance's properties).
1572
+ const value = (node, key, nested) => {
1573
+ if (nested || !node.expressions?.[key])
1574
+ return undefined;
1575
+ return layerValue(props, modes, node, key).value;
1576
+ };
1577
+ const visitOverride = (o, id, nested) => {
1578
+ const node = doc.nodes[id];
1579
+ if (node?.type === 'text' && o.textStyle?.lineHeight !== undefined && node.paragraphs?.length === 1) {
1580
+ const run = node.paragraphs[0].runs?.[0], style = { ...doc.theme?.textStyles?.[run?.styleId], ...run?.overrides };
1581
+ const size = value(node, 'fontSize', nested) ?? style.fontSize ?? 16, h = value(node, 'height', nested) ?? node.frame?.height;
1582
+ if (typeof size === 'number' && typeof h === 'number' && h > 0 && h < 1.5 * size * (style.lineHeight ?? 1.2))
1583
+ lineHeight.push([(o.textStyle.lineHeight * size) / h, (h / size).toFixed(3)]);
1584
+ }
1585
+ const base = node && !nested && o.padding && (value(node, 'padding', nested) ?? node.layout?.padding);
1586
+ if (base)
1587
+ for (const side of ['top', 'right', 'bottom', 'left'])
1588
+ if (o.padding[side] > 0 && base[side] > 0) {
1589
+ padding.push(o.padding[side] / base[side]);
1590
+ offGrid ||= Math.abs(o.padding[side] * 2 - Math.round(o.padding[side] * 2)) > 0.01;
1591
+ }
1592
+ // The instance's own conditions select its variant's values; a nested instance's line heights were scaled alike
1593
+ // whatever its variant, so they count without their conditions (its padding, read against stored values, does not).
1594
+ for (const e of o.conditional ?? []) {
1595
+ if (e.componentId !== comp.id) {
1596
+ visitOverride(e.value, id, true);
1597
+ continue;
1598
+ }
1599
+ let on = false;
1600
+ on = sourceValue(props, modes, 'condition', e.condition).value;
1601
+ if (on === true)
1602
+ visitOverride(e.value, id, nested);
1603
+ }
1604
+ };
1605
+ for (const [key, o] of Object.entries(overrides ?? {}))
1606
+ visitOverride(o, key.split(';').at(-1), key.includes(';'));
1607
+ const near = (a, b) => Math.abs(a - b) <= 0.005 * b;
1608
+ // Line heights: a ratio above 1 (a stale box is shorter, never taller) shared by texts with two different boxes.
1609
+ const shared = lineHeight.find(([r]) => r > 1.05 && new Set(lineHeight.filter(([x]) => near(x, r)).map(([, box]) => box)).size > 1);
1610
+ const s = padding.length > 1 ? (padding.every((r) => near(r, padding[0])) ? padding[0] : 1) : shared?.[0] ?? 1;
1611
+ // Padding alone can be a plain override that happens to be one multiple (16/32 px over 8/16 px is no 2x scale): it
1612
+ // is sure only with a second signal, a line height scaled by the same s or padding off the half-pixel grid that a
1613
+ // typed value keeps (p0 Cover Cards: 25.6 px, 1.6 times 16, also resized); otherwise the caller checks the box
1614
+ // against the natural size.
1615
+ const sure = padding.length > 1 && (offGrid || lineHeight.some(([r]) => near(r, s)));
1616
+ return Math.abs(s - 1) > 0.05 && s > 0.25 && s < 4 ? { s, sure } : { s: 1 };
1617
+ }
1618
+ // The overrides and resizing of an instance scaled by s, at the component's scale: padding, gap, minimum sizes and
1619
+ // line heights divided by s.
1620
+ function unscale(v, s, key) {
1621
+ if (Array.isArray(v))
1622
+ return v.map((x) => unscale(x, s));
1623
+ if (v && typeof v === 'object')
1624
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, k === 'padding' && x && typeof x === 'object'
1625
+ ? Object.fromEntries(Object.entries(x).map(([side, p]) => [side, typeof p === 'number' ? p / s : p])) : unscale(x, s, k)]));
1626
+ return typeof v === 'number' && ['gap', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'lineHeight'].includes(key) ? v / s : v;
1627
+ }
1628
+ // Line-height overrides that are each text's own line height times one k, with k below 1 (overrideScale reads
1629
+ // line heights only above 1). At least three, and two thirds of them, must agree: a line height of exactly 1
1630
+ // elsewhere can stay unscaled (p1 DateRangePicker: 67 of 69 at 0.7283), while one or two are a restyle (p41 Link).
1631
+ function lineHeightScale(overrides) {
1632
+ const ratios = [];
1633
+ const collect = (o, text) => {
1634
+ if (!o || typeof o !== 'object')
1635
+ return;
1636
+ if (o.textStyle?.lineHeight !== undefined) {
1637
+ const run = text.paragraphs?.[0]?.runs?.[0], own = { ...doc.theme?.textStyles?.[run?.styleId], ...run?.overrides }.lineHeight;
1638
+ if (own)
1639
+ ratios.push(o.textStyle.lineHeight / own);
1640
+ }
1641
+ for (const e of o.conditional ?? [])
1642
+ collect(e.value, text);
1643
+ };
1644
+ for (const [key, o] of Object.entries(overrides ?? {})) {
1645
+ const text = doc.nodes[key.split(';').at(-1)];
1646
+ if (text?.type === 'text')
1647
+ collect(o, text);
1648
+ }
1649
+ const k = ratios.find(r => { const n = ratios.filter(q => Math.abs(q - r) <= 0.005 * r).length; return n >= 3 && n * 3 >= ratios.length * 2; });
1650
+ return k !== undefined && k > 0.25 && k < 0.95 ? +k.toFixed(4) : 1;
1651
+ }
1652
+ function applyExpression(eff, key, v, own = false) {
1653
+ const num = typeof v === 'number';
1654
+ if (key.startsWith('propertyValues.')) {
1655
+ (eff.exprProps ??= {})[key.slice(15)] = v;
1656
+ return;
1657
+ }
1658
+ if (['visible', 'clipContent'].includes(key) && typeof v === 'boolean') {
1659
+ eff[key] = v;
1660
+ return;
1661
+ }
1662
+ if ((key === 'width' || key === 'height') && num && own)
1663
+ eff.variantSize = { ...eff.variantSize, [key]: v };
1664
+ if (['opacity', 'width', 'height', 'x', 'y', 'rotation', 'fontSize', 'fontWeight', 'lineHeightMultiplier', 'paragraphSpacing'].includes(key) && num) {
1665
+ eff[key] = v;
1666
+ return;
1667
+ }
1668
+ if (key === 'characters' && typeof v === 'string') {
1669
+ eff.characters = v;
1670
+ return;
1671
+ }
1672
+ if (key === 'fontFamily' && typeof v === 'string') {
1673
+ eff.fontFamily = v;
1674
+ return;
1675
+ }
1676
+ if (key === 'componentId' && typeof v === 'string') {
1677
+ eff.componentId = v;
1678
+ return;
1679
+ }
1680
+ if (key === 'textColor' && (v?.hex || typeof v === 'string')) {
1681
+ eff.textColor = v.hex ?? v;
1682
+ return;
1683
+ }
1684
+ if (key === 'transform' && Array.isArray(v) && v.length === 6) {
1685
+ eff.exprTransform = v;
1686
+ return;
1687
+ }
1688
+ if (['fills', 'strokes', 'shadows'].includes(key) && Array.isArray(v)) {
1689
+ eff[`style.${key}`] = v;
1690
+ return;
1691
+ }
1692
+ if (key === 'effects' && Array.isArray(v)) {
1693
+ v = v.filter((s) => s?.visible !== false); // an effect hidden in Figma (`with { visible: false }`) is not drawn
1694
+ eff['style.shadows'] = v.filter((s) => s.kind === 'drop' || s.kind === 'inner');
1695
+ // The expression's effects replace the layer's, blurs too (the last of each kind wins, as in taco): a variant
1696
+ // without a blur has none, whatever the stored (first) variant has.
1697
+ eff['style.backgroundBlur'] = v.findLast((s) => s.kind === 'background-blur')?.radius ?? 0;
1698
+ eff['style.layerBlur'] = v.findLast((s) => s.kind === 'layer-blur')?.radius ?? 0;
1699
+ return;
1700
+ }
1701
+ if (key === 'cornerRadii' && (num || v?.topLeft !== undefined)) {
1702
+ eff['style.cornerRadii'] = num ? { topLeft: v, topRight: v, bottomRight: v, bottomLeft: v } : v;
1703
+ return;
1704
+ }
1705
+ if (['gap', 'padding', 'align', 'justify', 'direction'].includes(key)) {
1706
+ // Expressions spell the stored 'space-between' as the enum case .space_between.
1707
+ if (key === 'justify' && v === 'space_between')
1708
+ v = 'space-between';
1709
+ eff.layout = { ...eff.layout, [key === 'direction' ? 'kind' : key]: v };
1710
+ return;
1711
+ }
1712
+ if (key === 'minWidth') {
1713
+ eff.resizing = { ...eff.resizing, minWidth: v };
1714
+ return;
1715
+ }
1716
+ if (key === 'constraintSize') {
1717
+ eff.constraintSize = v;
1718
+ return;
1719
+ }
1720
+ if (/^(layout|resizing|constraints)\./.test(key)) {
1721
+ const [group, field] = key.split('.');
1722
+ eff[group] = { ...eff[group], [field]: v };
1723
+ return;
1724
+ }
1725
+ drop(`expression not applied: ${key}`);
1726
+ }
1727
+ function radii(style) {
1728
+ if (style.cornerRadii) {
1729
+ const r = style.cornerRadii, v = [r.topLeft, r.topRight, r.bottomRight, r.bottomLeft].map((x) => Math.max(0, x ?? 0));
1730
+ return v.some((x) => x > 0) ? v : null;
1731
+ }
1732
+ return style.cornerRadius > 0 ? style.cornerRadius : null;
1733
+ }
1734
+ // Fills, the first stroke and effects. One shown solid fill goes in the compact record; anything more in look.fills.
1735
+ // carried: what figma-import carries in the node's metadata.figma (taco/figma-import/import/carry.ts), whose fill and
1736
+ // shadow indexes are into the node's own style lists.
1737
+ function appearance(m, style, kind, carried = {}) {
1738
+ const tiles = new Map(Array.isArray(carried.tiles) ? carried.tiles : []);
1739
+ const inBox = (p) => resolveLinearCall(p, () => localBox(m));
1740
+ const fills = (style.fills ?? []).map((p, i) => paint(inBox(p), tiles.get(i))).filter(Boolean), look = {};
1741
+ if (fills.length === 1 && fills[0].k === 'solid' && fills[0].o === 1 && fills[0].visible !== false)
1742
+ m.fill = fills[0].c;
1743
+ else if (fills.length)
1744
+ look.fills = fills;
1745
+ if (fills.some((p) => p.visible === false))
1746
+ note('hidden fills kept in place');
1747
+ if (fills.some((p) => p.fit === 3))
1748
+ note('tiled image fills');
1749
+ const strokes = (style.strokes ?? []).filter((s) => s.paint?.visible !== false && (s.width > 0 || s.fileBoundWidth && s.width === 0));
1750
+ if (strokes.length) {
1751
+ const s = strokes[0], p = paint(inBox(s.paint));
1752
+ if (strokes.length > 1)
1753
+ drop('additional strokes', strokes.length - 1);
1754
+ if (p) {
1755
+ m.stroke = p.k === 'solid' ? p.c : [0, 0, 0, 1];
1756
+ m.strokeWidth = s.width;
1757
+ const st = { position: { center: 0, inside: 1, outside: 2 }[s.position] ?? 0, join: { miter: 0, bevel: 1, round: 2 }[s.join] ?? null, cap: { none: 0, round: 1, square: 2 }[s.dashCap] ?? 0 };
1758
+ if (p.k !== 'solid' || p.o !== 1) {
1759
+ st.paint = p;
1760
+ if (p.k !== 'solid')
1761
+ note(`sent: ${p.k}${p.k === 'image' ? '' : ' gradient'} strokes`);
1762
+ }
1763
+ if (s.dash?.length)
1764
+ st.dash = s.dash;
1765
+ // Per-side weights (strokeTopWeight etc.). The scene keeps them on containers only; on a path, equal sides are
1766
+ // its stroke width (all 398 path cases in the kit: checkbox bases at 1 px on every side), unequal ones are dropped.
1767
+ if (s.sides) {
1768
+ const v = [s.sides.top, s.sides.right, s.sides.bottom, s.sides.left].map((x) => x ?? 0);
1769
+ if (kind === 'frame')
1770
+ st.sides = v;
1771
+ else if (v.every((x) => x === v[0])) {
1772
+ m.strokeWidth = v[0];
1773
+ note('equal stroke side weights on a path drawn as its stroke width');
1774
+ }
1775
+ else
1776
+ drop('unequal stroke side weights on a path (the scene has side weights on containers only)');
1777
+ }
1778
+ look.stroke = st;
1779
+ }
1780
+ }
1781
+ // A drop shadow is knocked out under the node (knockout: not drawn inside its fill shape), as Figma draws one with
1782
+ // showShadowBehindNode false, its default. The host document does not keep the flag; the Figma export sets it true
1783
+ // only on opaque nodes, where the knockout changes no more than the edge pixels (the supplement takes it from there
1784
+ // for style-bound nodes). A .fig import carries the shadows that set it (metadata.figma.shadowBehind).
1785
+ const behind = new Set(Array.isArray(carried.shadowBehind) ? carried.shadowBehind : []);
1786
+ const shadows = (style.shadows ?? []).map((s, i) => [s, i]).filter(([s]) => s.visible !== false).map(([s, i]) => ({ inner: s.kind === 'inner', x: s.x, y: s.y, blur: Math.max(0, s.blur), spread: s.spread ?? 0, c: rgba(s.color) ?? [0, 0, 0, 0.25], ...(s.kind === 'inner' || behind.has(i) ? {} : { knockout: true }) }));
1787
+ if (behind.size)
1788
+ note('drop shadows shown behind their node (not knocked out)');
1789
+ if (shadows.length > 16) {
1790
+ drop('shadows beyond 16', shadows.length - 16);
1791
+ shadows.length = 16;
1792
+ }
1793
+ if (shadows.length)
1794
+ look.shadows = shadows;
1795
+ if (style.layerBlur > 0)
1796
+ look.layerBlur = { radius: style.layerBlur };
1797
+ if (style.backgroundBlur > 0)
1798
+ look.backgroundBlur = { radius: style.backgroundBlur };
1799
+ for (const p of fills)
1800
+ if (p.k !== 'solid')
1801
+ note(`sent: ${p.k}${p.k === 'image' ? '' : ' gradient'} fills`);
1802
+ if (shadows.length)
1803
+ note('sent: nodes with shadows');
1804
+ if (look.layerBlur)
1805
+ note('sent: layer blurs');
1806
+ if (look.backgroundBlur)
1807
+ note('sent: background blurs');
1808
+ if (Object.keys(look).length)
1809
+ m.look = look;
1810
+ }
1811
+ // Constraints (Figma's): left/top keep the offset, right/bottom keep the far one, center keeps the centre,
1812
+ // left-right/top-bottom stretch, scale scales position and size. A position scales in the resized frame's space, so
1813
+ // a group's child scales with the group's offset in it (rs.at, as host-layout's constrainChildren).
1814
+ function follow(f, c = {}, rs) {
1815
+ const axis = (k, pos, size, d, sc, at) => {
1816
+ if (k === 'right' || k === 'bottom')
1817
+ f[pos] += d;
1818
+ else if (k === 'center')
1819
+ f[pos] += d / 2;
1820
+ else if (k === 'left-right' || k === 'top-bottom')
1821
+ f[size] += d;
1822
+ else if (k === 'scale') {
1823
+ f[pos] = (f[pos] + at) * sc - at;
1824
+ f[size] *= sc;
1825
+ }
1826
+ };
1827
+ axis(c.horizontal, 'x', 'width', rs.dw, rs.sx, rs.at?.[0] ?? 0);
1828
+ axis(c.vertical, 'y', 'height', rs.dh, rs.sy, rs.at?.[1] ?? 0);
1829
+ }
1830
+ function shapeNode(n, eff, common, f, rotation, style, rs) {
1831
+ let net, t, box, shape, regionFills = [];
1832
+ if (explicit && n.shape === 'rectangle') {
1833
+ const m = { ...common, kind: 'rect', t: transformOf(f, rotation), w: f.width, h: f.height, radius: radii(style) ?? 0 };
1834
+ if (style.cornerSmoothing)
1835
+ m.smoothing = style.cornerSmoothing;
1836
+ appearance(m, style, 'rect', n.metadata?.figma);
1837
+ models.push(m);
1838
+ return m;
1839
+ }
1840
+ if (n.shape === 'path') {
1841
+ const vn = n.vectorNetwork, r4 = (x) => +x.toFixed(4) || 0;
1842
+ const at = new Map(vn.vertices.map((v) => [v.id, [v.x, v.y]]));
1843
+ // An elliptical arc (svg-import keeps SVG's) becomes cubics of at most 90 degrees, through new vertices; its id
1844
+ // stands for them all in the regions' loops (`parts`).
1845
+ const vertices = vn.vertices.map((v) => ({ id: v.id, x: r4(v.x), y: r4(v.y) })), segments = [], parts = new Map();
1846
+ let arcs = 0;
1847
+ for (const s of vn.segments) {
1848
+ if (s.kind === 'elliptical-arc' && at.has(s.start) && at.has(s.end)) {
1849
+ const { points, handles } = arcCubics(at.get(s.start), at.get(s.end), s.radiusX, s.radiusY, s.xAxisRotation ?? 0, !!s.largeArc, !!s.sweep);
1850
+ if (handles.length) {
1851
+ arcs++;
1852
+ const ids = points.map((_, i) => `${s.id}~v${i + 1}`);
1853
+ points.forEach(([x, y], i) => vertices.push({ id: ids[i], x: r4(x), y: r4(y) }));
1854
+ const ends = [s.start, ...ids, s.end], own = handles.map((_, i) => (i ? `${s.id}~${i}` : s.id));
1855
+ handles.forEach(([ha, hb], i) => segments.push({ id: own[i], a: ends[i], b: ends[i + 1], ha: ha.map(r4), hb: hb.map(r4) }));
1856
+ parts.set(s.id, own);
1857
+ continue;
1858
+ }
1859
+ }
1860
+ else if (s.kind !== 'line' && s.kind !== 'cubic')
1861
+ drop('path segment kind');
1862
+ segments.push({ id: s.id, a: s.start, b: s.end, ha: s.kind === 'cubic' ? [s.startHandle.dx, s.startHandle.dy].map(r4) : [0, 0], hb: s.kind === 'cubic' ? [s.endHandle.dx, s.endHandle.dy].map(r4) : [0, 0] });
1863
+ }
1864
+ if (arcs)
1865
+ approximate('elliptical arcs split into cubics');
1866
+ net = { vertices, segments, loops: [], next: vertices.length + segments.length };
1867
+ const seg = new Map(net.segments.map((s) => [s.id, s]));
1868
+ const kept = (vn.regions ?? []).filter((r) => r.loops.length);
1869
+ net.regions = kept.map((r) => ({ w: r.windingRule === 'evenodd' ? 1 : 0, loops: r.loops.map((l) => {
1870
+ const refs = l.segments.flatMap((x) => {
1871
+ const rev = x.direction === 'reverse', ids = parts.get(x.segmentId) ?? [x.segmentId];
1872
+ return (rev ? [...ids].reverse() : ids).map((id) => [id, rev]);
1873
+ });
1874
+ const end = ([id, rev]) => (rev ? seg.get(id).a : seg.get(id).b), start = ([id, rev]) => (rev ? seg.get(id).b : seg.get(id).a);
1875
+ return { refs, open: start(refs[0]) !== end(refs[refs.length - 1]) };
1876
+ }) }));
1877
+ regionFills = kept.map((r) => r.fills);
1878
+ t = (eff.exprTransform ?? n.transform ?? [1, 0, 0, 1, f.x ?? 0, f.y ?? 0]).map((v) => +v.toFixed(6));
1879
+ // A path has no frame: its network scales under a scale or stretch constraint, and its translation moves with
1880
+ // the constraint. A stretched path keeps its outline's near edge, which is not its translation when it is turned
1881
+ // or its outline does not start at its origin. As in host-layout's resize, a path squeezed to nothing keeps a
1882
+ // sliver, so that a later, larger size can scale it back. A locked aspect ratio makes a constraint that sizes one
1883
+ // axis size the other too, which keeps its own constraint's anchor on the outline (host-layout's lockedResize).
1884
+ // A path its constraints do not size keeps its network as stored.
1885
+ if (rs) {
1886
+ const m = { t, net }, bounds = pathBounds(m), c = eff.constraints ?? {};
1887
+ const box = { x: t[4], y: t[5], width: bounds.width, height: bounds.height };
1888
+ follow(box, c, rs);
1889
+ t[4] = box.x;
1890
+ t[5] = box.y;
1891
+ const sizes = (k) => k === 'scale' || k === 'left-right' || k === 'top-bottom';
1892
+ const ratio = eff.aspectRatioLocked && !eff.layout ? eff.aspectRatio : undefined;
1893
+ const locked = ratio && sizes(c.horizontal) !== sizes(c.vertical) ? (sizes(c.horizontal) ? 'height' : 'width') : undefined;
1894
+ if (locked) {
1895
+ // The ratio is width / height in the path's own axes; a turned path keeps its box's.
1896
+ const r = Math.abs(t[1]) < 1e-6 && Math.abs(t[2]) < 1e-6 ? ratio : bounds.width / (bounds.height || 1);
1897
+ box[locked] = locked === 'height' ? box.width / r : box.height * r;
1898
+ }
1899
+ // Within 1e-6 of 1 is 1: float noise in a stored ratio or size (1.4999999 for 3:2) must not rewrite the network.
1900
+ const scale = (from, to) => (from && Math.abs(to / from - 1) >= 1e-6 ? Math.max(to, 1e-3) / from : 1);
1901
+ const sx = scale(bounds.width, box.width), sy = scale(bounds.height, box.height);
1902
+ if (sx !== 1 || sy !== 1) {
1903
+ scalePath(m, sx, sy);
1904
+ net = m.net;
1905
+ const after = pathBounds(m);
1906
+ // The near edge stays for a stretch; a locked axis keeps its centre for center, its far edge for right/bottom.
1907
+ const anchor = (k, grown) => (k === 'center' ? grown / 2 : k === 'right' || k === 'bottom' ? grown : 0);
1908
+ if (c.horizontal === 'left-right')
1909
+ t[4] += bounds.x - after.x;
1910
+ else if (locked === 'width')
1911
+ t[4] += bounds.x - after.x - anchor(c.horizontal, box.width - bounds.width);
1912
+ if (c.vertical === 'top-bottom')
1913
+ t[5] += bounds.y - after.y;
1914
+ else if (locked === 'height')
1915
+ t[5] += bounds.y - after.y - anchor(c.vertical, box.height - bounds.height);
1916
+ }
1917
+ }
1918
+ // A Figma STAR or REGULAR_POLYGON (figma-import carries its parameters, metadata.figma.shape) is the parametric
1919
+ // polygon or star (core/shapes.ts) in its box, as Figma draws it: outer points on the box's ellipse, from the top.
1920
+ // A rounded one, or one resized with its parent, keeps Figma's outline.
1921
+ const sp = n.metadata?.figma?.shape;
1922
+ if ((sp?.type === 'polygon' || sp?.type === 'star') && sp.width > 0 && sp.height > 0 && !rs && !(style.cornerRadius > 0)) {
1923
+ const count = Math.min(60, Math.max(3, Math.round(sp.count)));
1924
+ shape = sp.type === 'star' ? { type: 'star', count, ratio: Math.min(1, Math.max(0, sp.ratio ?? 0.382)) } : { type: 'polygon', count };
1925
+ net = shapes.shapeNet(shape, { x: 0, y: 0, width: sp.width, height: sp.height });
1926
+ box = pathBounds({ t, net: network([[0, 0], [sp.width, 0], [sp.width, sp.height], [0, sp.height]], true) });
1927
+ regionFills = [];
1928
+ note('Figma stars and polygons drawn as parametric shapes');
1929
+ }
1930
+ }
1931
+ else {
1932
+ const w = f.width, h = f.height;
1933
+ t = transformOf(f, rotation);
1934
+ if (n.shape === 'rectangle')
1935
+ net = network([[0, 0], [w, 0], [w, h], [0, h]], true);
1936
+ else if (n.shape === 'line')
1937
+ net = network([[0, 0], [w, 0]], false);
1938
+ else if (n.shape === 'ellipse') {
1939
+ const rx = w / 2, ry = h / 2;
1940
+ net = ellipseNetwork(w, h);
1941
+ const a = n.arc, lo = Math.min(a?.startingAngle ?? 0, a?.endingAngle ?? 360), hi = Math.max(a?.startingAngle ?? 0, a?.endingAngle ?? 360);
1942
+ const whole = !a || ((a.endingAngle ?? 360) - (a.startingAngle ?? 0)) % 360 === 0;
1943
+ // An arc keeps its ellipse's box for layout (see host-layout's pathBox).
1944
+ if (a && a.innerRadius >= 0.99 && hi - lo < 360 && style.strokes?.length) {
1945
+ box = pathBounds({ t, net });
1946
+ net = arcNetwork(rx, ry, lo, hi);
1947
+ }
1948
+ // A whole ring of inner radius (nearly) 1 is the ellipse's own outline: its stroke is the ellipse's stroke (all
1949
+ // 184 rings in the kit, the 0.999 tracks of spinners and progress circles, centre-stroked; the ring's 0.012 px
1950
+ // width is below a pixel), and it has no area to fill.
1951
+ else if (a && whole && a.innerRadius >= 0.99) {
1952
+ if (style.fills?.length)
1953
+ style = { ...style, fills: [] };
1954
+ approximate('whole thin rings drawn as their ellipse\'s stroke');
1955
+ }
1956
+ // Any other arc, pie or ring is the parametric ellipse (core/shapes.ts) in the node's box, which keeps the
1957
+ // ellipse's box for layout as above. Its angles are the span between the smaller and the larger one, as above.
1958
+ else if (a && (a.innerRadius > 0 || !whole)) {
1959
+ box = pathBounds({ t, net });
1960
+ shape = { type: 'ellipse', start: whole ? 0 : lo * Math.PI / 180, end: whole ? 2 * Math.PI : Math.min(hi, lo + 360) * Math.PI / 180, ratio: Math.min(1, Math.max(0, a.innerRadius ?? 0)) };
1961
+ net = shapes.shapeNet(shape, { x: 0, y: 0, width: w, height: h });
1962
+ note('ellipse arcs, pies and rings drawn as parametric ellipses');
1963
+ }
1964
+ }
1965
+ else {
1966
+ drop(`shape ${n.shape}`);
1967
+ return;
1968
+ }
1969
+ }
1970
+ // Regions with fills of their own (Figma's region styles, or gradients figma-import places on each region's box):
1971
+ // the scene fills a path's regions with one list, so the path becomes a group of one path per region, in order,
1972
+ // then one with the stroke. A mask stays one path (its outline is what masks).
1973
+ if (regionFills.some((x) => x !== undefined) && !n.mask && !n.isMask) {
1974
+ if (regionFills.length === 1)
1975
+ style = { ...style, fills: regionFills[0] };
1976
+ else
1977
+ return regionGroup(n, common, t, net, style, regionFills);
1978
+ }
1979
+ const m = { ...common, kind: 'path', t, net };
1980
+ if (shape)
1981
+ m.shape = shape;
1982
+ if (box)
1983
+ m.layoutData = { box };
1984
+ appearance(m, style, 'path', n.metadata?.figma);
1985
+ if (n.shape === 'rectangle') {
1986
+ const r = radii(style);
1987
+ if (r) {
1988
+ const v = Array.isArray(r) ? r : [r, r, r, r], lim = Math.min(f.width, f.height) / 2;
1989
+ m.corners = v.map((x, i) => [`v${i}`, Math.min(x, lim)]).filter(([, x]) => x > 0);
1990
+ if (!m.corners.length)
1991
+ delete m.corners;
1992
+ }
1993
+ }
1994
+ strokeCaps(m, n);
1995
+ models.push(m);
1996
+ return m;
1997
+ }
1998
+ // Stroke caps need an open chain whose two ends each appear once (SPEC 3.6).
1999
+ function strokeCaps(m, n) {
2000
+ const cap = { none: 0, round: 1, square: 2 }, net = m.net;
2001
+ if ((n.startCap && n.startCap !== 'none') || (n.endCap && n.endCap !== 'none')) {
2002
+ const count = new Map();
2003
+ for (const s of net.segments)
2004
+ for (const v of [s.a, s.b])
2005
+ count.set(v, (count.get(v) ?? 0) + 1);
2006
+ const first = net.segments[0], last = net.segments[net.segments.length - 1];
2007
+ if (m.stroke && first && count.get(first.a) === 1 && count.get(last.b) === 1 && n.startCap in cap && n.endCap in cap)
2008
+ m.caps = [cap[n.startCap], cap[n.endCap]];
2009
+ else if (m.stroke && first && !(count.get(first.a) === 2 && count.get(last.b) === 2))
2010
+ drop('stroke caps (network ends not single)');
2011
+ }
2012
+ }
2013
+ // A path whose regions have fills of their own, as a group (the node's id, name, opacity, effects and layout) of one
2014
+ // path per filled region, in the network's order, and one with the stroke on top; each keeps the whole network.
2015
+ function regionGroup(n, common, t, net, style, regionFills) {
2016
+ const b = pathBounds({ t, net });
2017
+ const g = { ...common, kind: 'frame', group: true, t: [1, 0, 0, 1, +(t[4] + b.x).toFixed(4), +(t[5] + b.y).toFixed(4)], w: b.width, h: b.height, clip: false };
2018
+ appearance(g, { shadows: style.shadows, layerBlur: style.layerBlur, backgroundBlur: style.backgroundBlur }, 'frame', n.metadata?.figma);
2019
+ models.push(g);
2020
+ const inner = [t[0], t[1], t[2], t[3], +(-b.x).toFixed(4), +(-b.y).toFixed(4)];
2021
+ net.regions.forEach((r, i) => {
2022
+ const fills = regionFills[i] ?? style.fills;
2023
+ if (!fills?.length)
2024
+ return;
2025
+ const p = { id: newId(), parent: g.id, name: `${common.name} ${i + 1}`, opacity: 1, kind: 'path', t: inner, net: { ...net, regions: [r] } };
2026
+ appearance(p, { fills }, 'path', regionFills[i] === undefined ? n.metadata?.figma : {});
2027
+ models.push(p);
2028
+ });
2029
+ if (style.strokes?.length) {
2030
+ const p = { id: newId(), parent: g.id, name: `${common.name} stroke`, opacity: 1, kind: 'path', t: inner, net: { ...net, regions: [] } };
2031
+ appearance(p, { strokes: style.strokes }, 'path');
2032
+ strokeCaps(p, n);
2033
+ models.push(p);
2034
+ }
2035
+ note('paths with per-region fills split into one path per region');
2036
+ return g;
2037
+ }
2038
+ // Text: runs take the theme style, then the run's overrides, then the instance's textStyle override and the
2039
+ // node's expressions.
2040
+ const weights = new Map();
2041
+ // What sizes a run's glyphs (not its colour or decoration).
2042
+ const faceOf = (s) => JSON.stringify([s.fontFamily, s.fontStyle, s.fontVariations, s.fontSize ?? 16, s.fontWeight ?? 400, !!s.italic, s.lineHeight ?? 1.2, s.letterSpacing ?? 0]);
2043
+ const runColour = (run) => ({ ...doc.theme?.textStyles?.[run.styleId], ...run.overrides }).color;
2044
+ const hexOf = (c) => (typeof c === 'string' ? c : c?.hex)?.toLowerCase();
2045
+ // A text's paragraphs: stored, or set as characters (each line one paragraph in the first run's style).
2046
+ function textParagraphs(paragraphs, characters) {
2047
+ if (characters === undefined)
2048
+ return paragraphs ?? [];
2049
+ const first = paragraphs?.[0]?.runs?.[0] ?? {};
2050
+ return characters.split(/\n|\u2029/).map((line) => ({ ...paragraphs?.[0], runs: [{ ...first, text: line }] }));
2051
+ }
2052
+ // A resolved text layer's text, run colours and alignment (its overrides and computed fields applied), on the runs
2053
+ // the converter's own overrides give (`full`): their font sizes and line heights size the box, as before.
2054
+ // copies: the run colours that only copy the text's colour (snapshotColours); such runs take the colour expression's
2055
+ // value (eff.textColor).
2056
+ function resolvedText(r, full, eff, copies) {
2057
+ const base = textParagraphs(full.paragraphs ?? eff.paragraphs, full.characters), shown = r.paragraphs ?? [];
2058
+ const computed = copies ? eff.textColor : undefined;
2059
+ const restyle = (run, from) => {
2060
+ let color = runColour(run);
2061
+ if (computed !== undefined && copies.has(hexOf(color)))
2062
+ color = computed;
2063
+ return { ...from, text: run.text, overrides: color === undefined ? from?.overrides : { ...from?.overrides, color } };
2064
+ };
2065
+ const same = shown.length === base.length && shown.every((p, i) => p.runs?.length === base[i].runs?.length);
2066
+ if (!same)
2067
+ approximate('resolved texts restyled from their first run');
2068
+ const paragraphs = shown.map((p, i) => ({ ...(same ? base[i] : p), align: p.align, runs: (p.runs ?? []).map((run, j) => restyle(run, same ? base[i].runs[j] : base[0]?.runs?.[0] ?? run)) }));
2069
+ if (computed !== undefined)
2070
+ note('text override colours kept from the text colour expression');
2071
+ return { paragraphs, characters: undefined, textColor: undefined, textAlign: undefined };
2072
+ }
2073
+ // A kit export fix, so it reads the export's override maps. The exporter writes a text override that changes only the
2074
+ // characters or the line height with the run colours it saw: the stored run colour (p64 _TableHeaderCell "Member",
2075
+ // "Date", "Amount" under `variant == .default`: #71717a), or what the text's `textColor` expression gives in the
2076
+ // default modes (p63 Tabs "Option", selected: foreground/segment in Light, #18181b). In Figma such an override does
2077
+ // not detach the variable the colour comes from: under "Frame 12 {02_Theme (HeroUI): Dark}" those texts show
2078
+ // foreground/muted's #a1a1aa. The resolver lets an override's runs win over computed fields, so a resolved text (r)
2079
+ // whose runs are such copies, under a `paragraphs` override that sets no colour (textColor, textStyle.color, a
2080
+ // binding or an expression), takes the expression's colour in those runs; a run with another colour keeps it (a real
2081
+ // override). A colour binding needs no fix: the resolver applies bindings after overrides.
2082
+ // The colours that are copies (a run without one counts as one), when any shown run has one; resolvedText applies them.
2083
+ function snapshotColours(n, r, full, owner) {
2084
+ if (n.expressions?.textColor === undefined || full.paragraphs === undefined)
2085
+ return undefined;
2086
+ if (full.textColor !== undefined || full.textStyle?.color !== undefined || full.variableBindings?.textColor !== undefined || full.expressions?.textColor !== undefined)
2087
+ return undefined;
2088
+ const copies = new Set((n.paragraphs ?? []).flatMap((p) => (p.runs ?? []).map((run) => hexOf(runColour(run)))));
2089
+ copies.add(hexOf(layerValue(owner, {}, n, 'textColor').value)).add(undefined);
2090
+ const shown = (r.paragraphs ?? []).flatMap((p) => (p.runs ?? []).map((run) => hexOf(runColour(run))));
2091
+ return shown.some((c) => copies.has(c)) ? copies : undefined;
2092
+ }
2093
+ function textNode(n, eff, o, common, f, rotation, style) {
2094
+ let paragraphs = textParagraphs(eff.paragraphs, eff.characters);
2095
+ if (style.shadows?.length || style.layerBlur || style.backgroundBlur)
2096
+ drop('effects on text');
2097
+ if ((style.strokes ?? []).length)
2098
+ drop('text stroke');
2099
+ const styles = [], keys = new Map(), runs = [], para = [], lines = [], faces = new Set();
2100
+ let boxLine = 0;
2101
+ paragraphs.forEach((p, pi) => {
2102
+ let line = '';
2103
+ for (const r of p.runs ?? []) {
2104
+ const s = { ...doc.theme?.textStyles?.[r.styleId], ...r.overrides, ...o.textStyle };
2105
+ let styleLine; // the style's own line height where the glyphs take the shorter box line instead
2106
+ // A variant's (conditional) line-height override records the line box Figma laid out (box height over font
2107
+ // size): it sizes the box below. Only where Figma kept the component's layout (asStored), or kept an auto-size box
2108
+ // (above); elsewhere the box takes the style's line height. A box line shorter than the style's is also the glyph
2109
+ // pitch: Figma's stored layout centres a single line in the short box (all 2,583 single-line texts of the
2110
+ // reference exports that are 4 px shorter than their style line) and steps wrapped lines by the box line (p0
2111
+ // Cover menu titles and descriptions were 2 px low against their icons with the style's pitch). The box line is
2112
+ // the final font size times the variant's multiplier (p15 "2010": a 12 px style with a 14 px override and 1.4286
2113
+ // stores a 20 px box, not 17.1). In an instance Figma re-laid out ('relaid'), a width-and-height text still takes
2114
+ // the variant's box line (Tag labels in 37 frames, p7 and p22 among them: 20 px, not the 23.3 px style line);
2115
+ // wrapping text there does not (p67/p68 descriptions).
2116
+ if (eff.fontSize)
2117
+ s.fontSize = eff.fontSize;
2118
+ if (o.textStyle?.lineHeight !== undefined && o.lineBoxOnly) {
2119
+ const own = { ...doc.theme?.textStyles?.[r.styleId], ...r.overrides }.lineHeight;
2120
+ if (o.lineBoxOnly === true || (o.lineBoxOnly === 'instance' && ['height', 'width-and-height'].includes(eff.autoResize)) || (o.lineBoxOnly === 'nested' && eff.autoResize === 'height')
2121
+ || (o.lineBoxOnly === 'relaid' && eff.autoResize === 'width-and-height'))
2122
+ boxLine = Math.max(boxLine, (s.fontSize ?? 16) * s.lineHeight);
2123
+ if (!boxLine || !(s.lineHeight < own))
2124
+ s.lineHeight = own;
2125
+ else
2126
+ styleLine = own;
2127
+ }
2128
+ if (eff.lineHeightMultiplier) {
2129
+ s.lineHeight = eff.lineHeightMultiplier;
2130
+ styleLine = undefined;
2131
+ }
2132
+ // A weight or slant override supersedes the style name from a lower-priority source.
2133
+ for (const override of [r.overrides, o.textStyle]) {
2134
+ if (override?.fontStyle)
2135
+ s.fontStyle = override.fontStyle;
2136
+ else if (override?.fontWeight !== undefined || override?.italic !== undefined)
2137
+ s.fontStyle = undefined;
2138
+ }
2139
+ if (eff.fontWeight) {
2140
+ s.fontWeight = eff.fontWeight;
2141
+ s.fontStyle = undefined;
2142
+ }
2143
+ if (eff.fontFamily)
2144
+ s.fontFamily = eff.fontFamily;
2145
+ if (eff.textColor)
2146
+ s.color = eff.textColor;
2147
+ const weight = s.fontWeight ?? 400;
2148
+ // The box line does not change what Figma measured: a stored box stays kept (keepSize, below).
2149
+ faces.add(faceOf(styleLine === undefined ? s : { ...s, lineHeight: styleLine }));
2150
+ weights.set(weight, (weights.get(weight) ?? 0) + 1);
2151
+ const want = runStyle(s);
2152
+ if (explicit && r.styleId && doc.theme?.textStyles?.[r.styleId])
2153
+ Object.assign(want, { textStyle: r.styleId });
2154
+ if (explicit && r.fileFontSize !== undefined)
2155
+ Object.assign(want, { fileFontSize: r.fileFontSize });
2156
+ const key = JSON.stringify(want);
2157
+ if (!keys.has(key)) {
2158
+ keys.set(key, styles.length);
2159
+ styles.push(want);
2160
+ }
2161
+ const text = (r.text ?? '').replace(/[\n\u2029]/g, ' ');
2162
+ if (text.length)
2163
+ runs.push([text.length, keys.get(key)]);
2164
+ line += text;
2165
+ }
2166
+ lines.push(line);
2167
+ const pp = { align: { left: 0, center: 1, right: 2, justify: 3 }[eff.textAlign ?? p.align] ?? 0, after: pi === paragraphs.length - 1 || (p.list && paragraphs[pi + 1]?.list) ? 0 : eff.paragraphSpacing ?? n.paragraphSpacing ?? 0, before: p.spacingBefore ?? 0 };
2168
+ if (p.list?.kind && p.list.kind !== 'none') {
2169
+ pp.list = p.list.kind === 'ordered' ? 1 : 2;
2170
+ pp.level = p.list.level ?? 0;
2171
+ if (p.list.marker?.gap)
2172
+ pp.gap = p.list.marker.gap;
2173
+ }
2174
+ if (p.indent)
2175
+ pp.indent = [p.indent.left ?? 0, p.indent.right ?? 0, p.indent.firstLine ?? 0];
2176
+ para.push(pp);
2177
+ runs.push([1, -1]); // the paragraph break
2178
+ });
2179
+ runs.pop();
2180
+ if (!styles.length)
2181
+ styles.push({ family: 'Inter', style: 'Regular', size: 16, lineHeight: 20, weight: 400, italic: false, underline: false, color: [0, 0, 0, 1], letterSpacing: 0 });
2182
+ // An auto-height box whose line box an override or expression changed keeps its line count (no shaper here).
2183
+ let h = f.height, storedHeight;
2184
+ const first = (eff.paragraphs ?? n.paragraphs)?.[0]?.runs?.[0], stored = n.paragraphs?.[0]?.runs?.[0];
2185
+ if (first && stored && styles.length && ['height', 'width-and-height'].includes(eff.autoResize)) {
2186
+ const base = { ...doc.theme?.textStyles?.[stored.styleId], ...stored.overrides }, was = (base.fontSize ?? 16) * (base.lineHeight ?? 1.2);
2187
+ const now = boxLine || Math.max(...styles.map((x) => x.lineHeight));
2188
+ // Changed text: estimate its line count from an average Inter advance (0.55 em), as no shaper runs here.
2189
+ const storedText = (n.paragraphs ?? []).map((p) => (p.runs ?? []).map((r) => r.text ?? '').join('')).join('\n'), text = lines.join('\n');
2190
+ const size = styles[0].size, count = text === storedText ? Math.max(1, Math.round(h / was)) : eff.autoResize === 'height' && f.width > 0
2191
+ ? lines.reduce((sum, line) => sum + Math.max(1, Math.ceil((line.length * size * 0.55) / f.width)), 0) : lines.length;
2192
+ if (was > 0 && (Math.abs(now - was) > 1e-3 || text !== storedText)) {
2193
+ h = +(count * now).toFixed(3);
2194
+ approximate('auto-height text resized for a changed line box or text');
2195
+ }
2196
+ // A shorter line box with the stored line count shrinks the box Figma laid out at the stored height: Figma did not
2197
+ // move it, so its row places it as if it were that height (`storedHeight`, see layoutFrame).
2198
+ if (was > 0 && now < was - 1e-3 && count === Math.max(1, Math.round(f.height / was)))
2199
+ storedHeight = f.height;
2200
+ }
2201
+ // Figma names a text after its content (the whole of it); like a text made in the editor (core/names.ts), it keeps
2202
+ // the first 30 characters, so long passages do not double the document.
2203
+ const m = { ...common, name: Array.from(common.name).slice(0, 30).join(''), kind: 'text', t: transformOf(f, rotation), w: f.width, h, content: lines.join('\n'), styles, runs, autoResize: { 'width-and-height': 2, height: 1, none: 0 }[eff.autoResize] ?? 0,
2204
+ wrap: eff.autoResize === 'width-and-height' || eff.wrap === 'none' ? 0 : 1, valign: { top: 0, middle: 1, center: 1, bottom: 2 }[n.verticalAlign] ?? 0, para };
2205
+ if (storedHeight > h)
2206
+ m.storedHeight = storedHeight;
2207
+ // Figma does not re-measure an auto-size box (3,816 of the kit's 13,795 visible ones are 4 px shorter than their
2208
+ // line height): the editor keeps a box whose text, faces, mode and wrap width are the stored ones, and measures
2209
+ // the rest (changed by an override or expression), as an edit would.
2210
+ const storedFaces = new Set((n.paragraphs ?? []).flatMap((p) => (p.runs ?? []).map((r) => faceOf({ ...doc.theme?.textStyles?.[r.styleId], ...r.overrides }))));
2211
+ const storedText = (n.paragraphs ?? []).map((p) => (p.runs ?? []).map((r) => (r.text ?? '').replace(/[\n\u2029]/g, ' ')).join('')).join('\n');
2212
+ if (m.autoResize && m.content === storedText && eff.autoResize === n.autoResize && (m.autoResize === 2 || f.width === n.frame?.width)
2213
+ && faces.size === storedFaces.size && [...faces].every((x) => storedFaces.has(x)) && o.lineBoxOnly !== 'remeasure')
2214
+ m.keepSize = true;
2215
+ // A box sized by a variant's line box (above) that the editor measures keeps that line box per line.
2216
+ const pitch = Math.max(...styles.map((x) => x.lineHeight));
2217
+ if (m.autoResize && !m.keepSize && boxLine && pitch > 0 && Math.abs(boxLine - pitch) > 1e-3)
2218
+ m.boxScale = boxLine / pitch;
2219
+ // Figma's leading trim (CAP_HEIGHT) cuts a text's box to run from the cap height to the baseline; the kit export
2220
+ // drops the setting, but the stored box shows it. In the reference exports the one trimmed text (p76 2217:6120,
2221
+ // 64 px Inter in a 77.45 px line) stores a 47 px box, its 46.55 px cap height, and none of the other 13,798 texts
2222
+ // is a single line with a box within 1 px of its cap height and shorter than its line. Such a kept box takes a
2223
+ // line box that puts the baseline at the cap height below its top: with half leading the baseline sits at
2224
+ // line / 2 + (ascent - descent) / 2, so line = 2 cap - (ascent - descent), which for Inter 3.19 (cap 2048,
2225
+ // ascent 2728, descent 680 per 2816 em) is the cap height itself. Each run takes its own, so the largest sets it.
2226
+ const cap = 2048 / 2816, trimmed = 2 * cap - (2728 - 680) / 2816;
2227
+ if (m.keepSize && lines.length === 1 && Math.abs(h - Math.max(...styles.map((x) => x.size)) * cap) <= 1 && h < pitch - 1) {
2228
+ for (const s of styles)
2229
+ s.lineHeight = +(s.size * trimmed).toFixed(3);
2230
+ approximate('leading trim (cap height) taken from a box at the cap height');
2231
+ }
2232
+ models.push(m);
2233
+ return m;
2234
+ }
2235
+ for (const [index, page] of pages.entries()) {
2236
+ const parent = explicit ? `page-${index + 1}` : '';
2237
+ const root = doc.nodes[page.rootId];
2238
+ if (explicit)
2239
+ models.push({ id: parent, kind: 'page', name: page.name, ...(root.variableModes && { modes: root.variableModes }) });
2240
+ const ctx = { owner: null, comps: [], ovr: [], modes: { ...root.variableModes } };
2241
+ for (const c of root.children ?? [])
2242
+ visit(doc.nodes[c], parent, ctx);
2243
+ }
2244
+ if (explicit) {
2245
+ const placed = new Set(Object.values(doc.componentPlacements ?? {}));
2246
+ const ctx = { owner: null, comps: [], ovr: [], modes: {} };
2247
+ for (const component of Object.values(doc.components))
2248
+ if (!placed.has(component.id))
2249
+ visit(doc.nodes[component.rootId], '@components', ctx);
2250
+ for (const source of Object.values(doc.nodes))
2251
+ if (source.slotHost || source.fileStyle)
2252
+ visit(source, '', ctx);
2253
+ }
2254
+ // A wrapper instance holds a box Figma laid out: the editor keeps it and its variant root there (wrapped in
2255
+ // layout.mjs; p35 DropdownItems stay 48 px, not the 56 their contents hug; p63's 86 px Tabs, though its converted
2256
+ // variant root came out 56). One whose variant root came out larger than its box stores a stale box, so the editor
2257
+ // re-hugs it (p57 SearchField descriptions: a 16 px wrapper around a 20 px line that Figma draws 20 px).
2258
+ for (const [w, v, p] of wrappers) {
2259
+ if (v.w > w.w - p.left - p.right + 0.01 || v.h > w.h - p.top - p.bottom + 0.01) {
2260
+ delete w.layoutData.instance;
2261
+ approximate('wrapper instances smaller than their variant root (re-hugged)', 1, w);
2262
+ }
2263
+ else
2264
+ v.layoutData.instance = true;
2265
+ }
2266
+ // Image assets the models use, listed in out.assets (and in the report, with their bytes).
2267
+ const assets = {}, used = new Set(), files = [];
2268
+ for (const m of models)
2269
+ for (const p of [...m.look?.fills ?? [], m.look?.stroke?.paint])
2270
+ if (p?.k === 'image')
2271
+ used.add(p.asset);
2272
+ for (const id of [...used].sort()) {
2273
+ const a = doc.assets[id], src = options.assetSrc?.(id, a) ?? `assets/${id}.${a.mimeType === 'image/jpeg' ? 'jpg' : a.mimeType.split('/')[1]}`;
2274
+ files.push({ id, src, mimeType: a.mimeType, data: a.source.data });
2275
+ assets[id] = { src, w: a.width, h: a.height };
2276
+ }
2277
+ const out = { leading: 'half', ...(!explicit && { page: pages[0].name }), ...(options.source !== undefined ? { source: options.source } : {}), models, ...(used.size ? { assets } : {}) };
2278
+ const linked = options.link === false ? null : linkWithLayers(out);
2279
+ if (expanded && linked) {
2280
+ const original = new Map(models.map(m => [m.id, m]));
2281
+ for (const m of models)
2282
+ if (m.fileInstance)
2283
+ expanded.set(m.id, m);
2284
+ // Hidden main copies are recorded before the occurrences linked against them.
2285
+ for (const [id, paths] of linked.aliases)
2286
+ for (const path of paths)
2287
+ expanded.set(path, original.get(id) ?? expanded.get(id));
2288
+ }
2289
+ if (options.link === false && !options.markers)
2290
+ for (const m of out.models)
2291
+ unmark(m);
2292
+ const remaining = new Set(out.models.map((m) => m.id));
2293
+ function affectedIds(id) {
2294
+ const aliases = linked?.aliases.get(id) ?? [];
2295
+ const stored = [id, ...aliases].filter((key) => remaining.has(key));
2296
+ return stored.length ? stored : aliases.filter((key) => key.includes(';') && remaining.has(key.split(';', 1)[0]));
2297
+ }
2298
+ const layerIds = new Map([...affected].map(([key, layers]) => [
2299
+ key, [...new Set([...layers].flatMap(({ id }) => id === undefined ? [] : affectedIds(id)))],
2300
+ ]));
2301
+ return { doc: out, report: { dropped, expressionErrors, notes, approximations, weights, layerIds, depth: depthMax, links: linked?.counts ?? null, assets: files } };
2302
+ }