@moondraft/import 0.0.0-stage → 0.2.0

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