@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,1530 @@
1
+ import { constrainChildren, entryOf, formatExpressionName, getNodeBounds, layerPathKey, paragraphsFromCharacters, parseLayerPath, PROPERTIES_DROPPED_BY_FIELD, TEXT_STYLE_PROPERTIES, } from "../../model/index.js";
2
+ import { stackLayoutOf } from "./converters/layout.js";
3
+ import { withImageCrop } from "./carry.js";
4
+ import { field, guidText, isObject } from "./fields.js";
5
+ import { isDetachedStyle, STYLE_REFERENCE_FIELDS, styleBackedList } from "./styles.js";
6
+ import { assignedPropertyValues, assignedValueOf, propertyByFigmaId } from "./componentProps.js";
7
+ import { frameGeometry, readNumbers, STROKE_CAPS } from "./converters/shared.js";
8
+ import { hyperlinkOf, inheritOpenTypeToggles, KEPT_LINE_HEIGHT_FIELD, OPEN_TYPE_FIELDS, OPEN_TYPE_TOGGLES } from "./converters/text.js";
9
+ import { exportSettingsOf } from "./converters/exportSettings.js";
10
+ /** The `variableConsumptionMap` fields that bind each merged override field. */
11
+ const BOUND_BY_OVERRIDE = {
12
+ size: ["WIDTH", "HEIGHT"], visible: ["VISIBLE"], opacity: ["OPACITY"],
13
+ strokeWeight: ["STROKE_WEIGHT", "BORDER_TOP_WEIGHT", "BORDER_RIGHT_WEIGHT", "BORDER_BOTTOM_WEIGHT", "BORDER_LEFT_WEIGHT"],
14
+ };
15
+ /** The component bindings the model drops from a layer the override is applied to, so the override must write each again. */
16
+ export function bindingsDroppedBy(override) {
17
+ const dropped = new Set();
18
+ for (const [name, properties] of Object.entries(PROPERTIES_DROPPED_BY_FIELD))
19
+ if (override[name] !== undefined)
20
+ properties.forEach((property) => dropped.add(property));
21
+ for (const key of Object.keys(isObject(override["textStyle"]) ? override["textStyle"] : {})) {
22
+ const property = TEXT_STYLE_PROPERTIES[key];
23
+ if (property !== undefined)
24
+ dropped.add(property);
25
+ }
26
+ return dropped;
27
+ }
28
+ /**
29
+ * The binding fields an override of `name` unbinds. Figma writes the whole `size` vector when either axis changes, and
30
+ * the axis left alone stays bound, so `size` unbinds WIDTH only when `x` differs and HEIGHT only when `y` differs.
31
+ */
32
+ function overriddenBindingFields(name, value, before) {
33
+ if (name !== "size")
34
+ return BOUND_BY_OVERRIDE[name] ?? [];
35
+ const old = isObject(before) ? before : {};
36
+ const now = isObject(value) ? value : {};
37
+ return [...(now["x"] !== old["x"] ? ["WIDTH"] : []), ...(now["y"] !== old["y"] ? ["HEIGHT"] : [])];
38
+ }
39
+ /**
40
+ * `change` with the `overridden` fields merged in and without the component's bindings of the fields they change:
41
+ * Figma unbinds a field that an override sets, so the instance takes the override's value, not the component's variable.
42
+ */
43
+ function withOverrides(change, overridden) {
44
+ const merged = { ...change, ...overridden };
45
+ const unbound = new Set(Object.entries(overridden).flatMap(([name, value]) => overriddenBindingFields(name, value, change[name])));
46
+ const map = change["variableConsumptionMap"];
47
+ if (unbound.size === 0 || !isObject(map) || !Array.isArray(map["entries"]))
48
+ return merged;
49
+ const entries = map["entries"].filter((entry) => {
50
+ const name = isObject(entry) ? entry["variableField"] : undefined;
51
+ return typeof name !== "string" || !unbound.has(name);
52
+ });
53
+ return { ...merged, variableConsumptionMap: { ...map, entries } };
54
+ }
55
+ /**
56
+ * A key equal for two decoded Kiwi values exactly when they are equal field by field, so a list of values can be indexed
57
+ * once instead of compared pairwise: objects by their keys in sorted order, arrays by their items, primitives as
58
+ * `Object.is` compares them, and any other object (such as a `Uint8Array`) by its identity, numbered in `identities`.
59
+ */
60
+ function dataKey(value, identities) {
61
+ if (Array.isArray(value))
62
+ return `[${Array.from(value, (item) => dataKey(item, identities)).join(",")}]`;
63
+ if (isObject(value))
64
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${dataKey(value[key], identities)}`).join(",")}}`;
65
+ if (typeof value === "string")
66
+ return JSON.stringify(value);
67
+ if (typeof value === "number")
68
+ return Object.is(value, -0) ? "n-0" : `n${value}`;
69
+ if (typeof value === "bigint" || typeof value === "boolean")
70
+ return `${typeof value === "bigint" ? "b" : "t"}${String(value)}`;
71
+ if (value === undefined || value === null)
72
+ return String(value);
73
+ if (!identities.has(value))
74
+ identities.set(value, identities.size);
75
+ return `#${identities.get(value)}`;
76
+ }
77
+ /**
78
+ * What an override's `parameterConsumptionMap` holds that its `variableConsumptionMap` (`variableMap`) lacks: a key other
79
+ * than `entries`, and each entry with no equal entry in `variableMap`, by its field. An entry with only a field that
80
+ * `variableMap` binds is Figma's record of the component's binding being replaced, and adds nothing.
81
+ */
82
+ function parameterMapExtras(parameterMap, variableMap) {
83
+ if (!isObject(parameterMap))
84
+ return ["parameterConsumptionMap"];
85
+ const listed = (value) => isObject(value) && Array.isArray(value["entries"]) ? value["entries"] : [];
86
+ // Indexed once, so a file with many entries on both sides costs time in their sum, not their product.
87
+ const identities = new Map();
88
+ const bound = new Set(listed(variableMap).map((other) => dataKey(other, identities)));
89
+ const boundFields = new Set(listed(variableMap).flatMap((other) => isObject(other) ? [other["variableField"]] : []));
90
+ const extras = Object.keys(parameterMap).filter((key) => key !== "entries" || !Array.isArray(parameterMap[key]));
91
+ for (const entry of listed(parameterMap)) {
92
+ if (bound.has(dataKey(entry, identities)))
93
+ continue;
94
+ const variableField = isObject(entry) ? entry["variableField"] : undefined;
95
+ // `variableField === variableField` keeps `NaN` unmatched, as the strict comparison this replaces did.
96
+ const unbinds = isObject(entry) && Object.keys(entry).length === 1 && variableField !== undefined
97
+ && variableField === variableField && boundFields.has(variableField);
98
+ if (!unbinds)
99
+ extras.push(typeof variableField === "string" ? variableField : "an entry with no field");
100
+ }
101
+ return extras;
102
+ }
103
+ /**
104
+ * A `variableConsumptionMap` with the entries of an override's own map (`over`) in place of those of the same field in
105
+ * `map`, the component layer's.
106
+ */
107
+ function withBindingEntries(map, over) {
108
+ const entriesOf = (value) => isObject(value) && Array.isArray(value["entries"]) ? value["entries"] : [];
109
+ const fieldOf = (entry) => isObject(entry) ? entry["variableField"] : undefined;
110
+ const overEntries = entriesOf(over);
111
+ const named = new Set(overEntries.map(fieldOf));
112
+ return { ...isObject(map) ? map : {}, entries: [...entriesOf(map).filter((entry) => !named.has(fieldOf(entry))), ...overEntries] };
113
+ }
114
+ /**
115
+ * Writes `null` in each override for a binding the model would keep from a nested instance's own override (`mergeOverrides`
116
+ * in the model) of a field the override sets plainly. Runs once every instance has its overrides, since the nested instances
117
+ * along a path are finished in file order.
118
+ */
119
+ export function unbindInnerBindings(overrides, nested) {
120
+ if (overrides === undefined)
121
+ return;
122
+ for (const [key, through] of nested) {
123
+ const override = overrides[key];
124
+ if (override === undefined)
125
+ continue;
126
+ const dropped = bindingsDroppedBy(override);
127
+ const nulls = {};
128
+ for (const { instance, inner } of through) {
129
+ const bound = instance.type === "instance" ? entryOf(instance.overrides, inner)?.variableBindings : undefined;
130
+ for (const [property, value] of Object.entries(bound ?? {})) {
131
+ if (value !== null && value !== undefined && dropped.has(property) && override.variableBindings?.[property] === undefined)
132
+ nulls[property] = null;
133
+ }
134
+ }
135
+ if (Object.keys(nulls).length > 0)
136
+ overrides[key] = { ...override, variableBindings: { ...override.variableBindings, ...nulls } };
137
+ }
138
+ }
139
+ /** The key an override path step names a layer by: its `overrideKey`, else its guid. */
140
+ export function overrideKeyOf(node) {
141
+ const key = node.change["overrideKey"];
142
+ return key === undefined ? node.id : guidText(key, `node ${node.id} overrideKey`);
143
+ }
144
+ /**
145
+ * Override fields whose effect the walk reads by converting the layer with
146
+ * and without them (`convertAlone`): paints, strokes, effects and the styles that back them, visibility,
147
+ * opacity, and a text layer's characters, style and truncation.
148
+ */
149
+ const CONVERTED_FIELDS = new Set([
150
+ "fillPaints", "strokePaints", "strokeWeight", "strokeAlign", "strokeJoin", "strokeCap", "dashPattern", "miterLimit",
151
+ "borderStrokeWeightsIndependent", "borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", "effects",
152
+ "styleIdForEffect", "styleIdForFill", "styleIdForStrokeFill", "visible", "opacity",
153
+ "textData", "styleIdForText", "fontName", "fontSize", "lineHeight", "letterSpacing", "textAlignHorizontal", "paragraphSpacing", "listSpacing", "textCase", "textDecoration", "fontVariations", "hyperlink",
154
+ "cornerSmoothing", "textTruncation", "maxLines", ...OPEN_TYPE_FIELDS,
155
+ ]);
156
+ /** Fields applied to a frame or to the component root shown by a nested instance. */
157
+ const STACK_FIELDS = { gap: "stackSpacing", align: "stackCounterAlignItems", justify: "stackPrimaryAlignItems",
158
+ wrap: "stackWrap", wrapGap: "stackCounterSpacing", alignContent: "stackCounterAlignContent" };
159
+ const FRAME_FIELDS = new Set(["stackPrimarySizing", "stackCounterSizing", "stackMode", ...Object.values(STACK_FIELDS),
160
+ "frameMaskDisabled", "cornerSmoothing"]);
161
+ /** Keep only changed members, including explicit defaults which clear an inherited setting. */
162
+ function frameOverrides(base, next, authored = {}) {
163
+ const before = base.layout, after = next.layout;
164
+ const layout = {};
165
+ if (before.kind !== after.kind || "stackMode" in authored)
166
+ layout.kind = after.kind;
167
+ if (after.kind === "horizontal" || after.kind === "vertical") {
168
+ const from = before.kind === "horizontal" || before.kind === "vertical" ? before : undefined;
169
+ for (const key of ["gap", "align", "justify", "wrap", "wrapGap", "alignContent"]) {
170
+ if (after[key] !== from?.[key] || STACK_FIELDS[key] in authored)
171
+ layout[key] = after[key] ?? (key === "wrap" ? false : key === "alignContent" ? "auto" : after.gap);
172
+ }
173
+ }
174
+ const sizing = before.kind === "absolute" && after.kind !== "absolute" ? { width: after.widthSizing, height: after.heightSizing } : undefined;
175
+ return { ...(Object.keys(layout).length && { layout }), ...(sizing && { sizing }),
176
+ ...(before.kind === "absolute" && after.kind !== "absolute" && { padding: after.padding }),
177
+ ...(!!base.clipContent !== !!next.clipContent && { clipContent: !!next.clipContent }) };
178
+ }
179
+ /**
180
+ * Padding override fields and the side each sets (`stackPadding`, Figma's older single value, sets every side the
181
+ * entry does not set on its own), as `stackLayoutOf` reads them.
182
+ */
183
+ const PADDING_FIELDS = {
184
+ stackHorizontalPadding: ["left"], stackPaddingRight: ["right"], stackVerticalPadding: ["top"], stackPaddingBottom: ["bottom"],
185
+ stackPadding: ["top", "right", "bottom", "left"],
186
+ };
187
+ const PADDING_FIELDS_OF_SIDE = {
188
+ left: ["stackHorizontalPadding"], right: ["stackPaddingRight"], top: ["stackVerticalPadding"], bottom: ["stackPaddingBottom"],
189
+ };
190
+ /**
191
+ * Fields that change neither pixels nor behaviour, so they are skipped
192
+ * without a report: Figma's own bookkeeping and the font file version it loaded.
193
+ */
194
+ const BOOKKEEPING_FIELDS = new Set([
195
+ "guidPath", "overrideLevel", "textUserLayoutVersion", "vectorOperationVersion", "fontVersion",
196
+ ]);
197
+ const HANDOFF_OVERRIDE_FIELDS = new Set(["annotations", "measurements"]);
198
+ const activeHandoffOverride = (value) => value !== undefined && (!Array.isArray(value) || value.some((item) => !isObject(item) || item["isDeleted"] !== true));
199
+ /** The parts of a converted layer an instance can override, as `LayerOverride` fields, plus those it cannot. */
200
+ const STYLE_OVERRIDES = ["cornerSmoothing", "fills", "strokes", "shadows", "layerBlur", "backgroundBlur"];
201
+ const same = (a, b) => JSON.stringify(a, withImageCrop) === JSON.stringify(b, withImageCrop);
202
+ function styleOf(node) {
203
+ return "style" in node && node.style !== undefined ? node.style : {};
204
+ }
205
+ /** The text of paragraphs as `LayerOverride.characters` writes it. */
206
+ function plainText(paragraphs) {
207
+ return paragraphs.map((paragraph) => paragraph.runs.map((run) => run.text).join("")).join("\n");
208
+ }
209
+ /**
210
+ * Whether `next` is `base`'s first paragraph and run style with other text, which `characters` can say: the
211
+ * paragraphs `paragraphsFromCharacters` makes, which after the first take the space above of `base`'s second paragraph,
212
+ * or none of their own when it has one.
213
+ */
214
+ function onlyCharactersChanged(base, next) {
215
+ const first = base[0];
216
+ const firstRun = first?.runs[0];
217
+ if (first === undefined || firstRun === undefined)
218
+ return false;
219
+ const { text: _text, ...runFields } = firstRun;
220
+ const made = paragraphsFromCharacters(plainText(next), base);
221
+ return next.length === made.length && next.every(({ runs, ...fields }, index) => {
222
+ const { runs: _runs, ...madeFields } = made[index];
223
+ return same(fields, madeFields) && runs.every(({ text: _t, ...rest }) => same(rest, runFields));
224
+ });
225
+ }
226
+ /**
227
+ * The alignment `next` gives every paragraph where `base` gives every paragraph another one, with `next` aligned as
228
+ * `base` is, or `undefined`. Figma aligns a whole text layer at once, so an override of `textAlignHorizontal` changes
229
+ * only this, and it is written as `LayerOverride.textAlign` rather than in a `paragraphs` override that would also fix
230
+ * the text.
231
+ */
232
+ function alignmentChange(base, next) {
233
+ const align = next[0]?.align;
234
+ const baseAlign = base[0]?.align;
235
+ if (align === undefined || align === baseAlign || !next.every((paragraph) => paragraph.align === align) || !base.every((paragraph) => paragraph.align === baseAlign))
236
+ return undefined;
237
+ return {
238
+ align,
239
+ paragraphs: next.map(({ align: _align, ...paragraph }) => (baseAlign === undefined ? paragraph : { ...paragraph, align: baseAlign })),
240
+ };
241
+ }
242
+ /**
243
+ * The run fields an override can set on every run of a text layer with one `textStyle`: a weight, italic or line height
244
+ * that a bound font style or line height sets, and a colour that an override's fill sets.
245
+ */
246
+ const UNIFORM_FIELDS = ["fontStyle", "fontWeight", "italic", "lineHeight", "color"];
247
+ function withoutUniformFields(overrides) {
248
+ const rest = { ...overrides };
249
+ for (const name of UNIFORM_FIELDS)
250
+ delete rest[name];
251
+ return rest;
252
+ }
253
+ /**
254
+ * The `textStyle` that turns `base` into `next` when they differ only in a weight, italic, line height or colour that
255
+ * `next` gives every run, as a bound font style or line height or an override's fill does, or `undefined`. A `textStyle` override keeps the text, so
256
+ * characters a property drives stay.
257
+ */
258
+ function uniformStyleChange(base, next) {
259
+ if (base.length !== next.length)
260
+ return undefined;
261
+ const plain = (paragraphs) => paragraphs.map(({ runs: shown, ...fields }) => ({
262
+ ...fields, runs: shown.map(({ overrides, ...run }) => ({ ...run, overrides: withoutUniformFields(overrides ?? {}) })),
263
+ }));
264
+ if (!same(plain(base), plain(next)))
265
+ return undefined;
266
+ const runs = next.flatMap((paragraph) => paragraph.runs);
267
+ const baseRuns = base.flatMap((paragraph) => paragraph.runs);
268
+ const change = {};
269
+ for (const name of UNIFORM_FIELDS) {
270
+ const value = (run) => name === "italic" ? run?.overrides?.italic ?? false : run?.overrides?.[name];
271
+ const first = value(runs[0]);
272
+ if (baseRuns.every((run, index) => value(run) === value(runs[index])))
273
+ continue;
274
+ // A `textStyle` gives every run one value, and cannot take a weight or line height away.
275
+ if (!runs.every((run) => value(run) === first) || first === undefined)
276
+ return undefined;
277
+ change[name] = first;
278
+ }
279
+ return change;
280
+ }
281
+ /**
282
+ * The `LayerOverride` that turns `base` (a component layer, converted) into
283
+ * `next` (the same layer with an instance's override fields, converted):
284
+ * paints, strokes, effects, visibility, opacity and text. Any other part
285
+ * that differs is reported, since Taco instances do not override it.
286
+ */
287
+ function overrideBetween(base, next, report) {
288
+ const override = {};
289
+ if (next.visible !== base.visible)
290
+ override["visible"] = next.visible;
291
+ if (next.opacity !== base.opacity)
292
+ override["opacity"] = next.opacity;
293
+ const baseStyle = styleOf(base);
294
+ const nextStyle = styleOf(next);
295
+ for (const name of STYLE_OVERRIDES) {
296
+ if (!same(baseStyle[name], nextStyle[name]))
297
+ override[name] = nextStyle[name] ?? (name === "layerBlur" || name === "backgroundBlur" || name === "cornerSmoothing" ? 0 : []);
298
+ }
299
+ for (const name of new Set([...Object.keys(baseStyle), ...Object.keys(nextStyle)])) {
300
+ if (!STYLE_OVERRIDES.includes(name) && !same(baseStyle[name], nextStyle[name])) {
301
+ report("property-left-out", `an override of a layer's ${name} is left out: Taco instances cannot override it`);
302
+ }
303
+ }
304
+ if (base.type === "shape" && base.shape === "path" && next.type === "shape" && next.shape === "path" && (base.startCap !== next.startCap || base.endCap !== next.endCap)) {
305
+ report("property-left-out", "an override of a path's end caps is left out: Taco instances cannot override them");
306
+ }
307
+ // An instance cannot override the text's paragraph spacing, so where it differs every later paragraph keeps the
308
+ // instance's spacing as its own space above, in a `paragraphs` override.
309
+ const nextParagraphs = base.type !== "text" || next.type !== "text" || base.paragraphSpacing === next.paragraphSpacing
310
+ ? next.type === "text" ? next.paragraphs : []
311
+ : next.paragraphs.map((paragraph, index) => index === 0 || paragraph.spacingBefore !== undefined ? paragraph
312
+ : { ...paragraph, spacingBefore: next.paragraphSpacing ?? 0 });
313
+ if (base.type === "text" && next.type === "text" && !same(base.paragraphs, nextParagraphs)) {
314
+ // An alignment Figma sets for the whole layer goes on its own, so the text itself can still follow the component.
315
+ const realigned = alignmentChange(base.paragraphs, nextParagraphs);
316
+ const shown = realigned?.paragraphs ?? nextParagraphs;
317
+ if (!same(base.paragraphs, shown)) {
318
+ const uniform = uniformStyleChange(base.paragraphs, shown);
319
+ if (uniform !== undefined && Object.keys(uniform).length > 0)
320
+ override["textStyle"] = uniform;
321
+ else if (onlyCharactersChanged(base.paragraphs, shown))
322
+ override["characters"] = plainText(shown);
323
+ else
324
+ override["paragraphs"] = nextParagraphs;
325
+ }
326
+ // Paragraphs carry their own alignment.
327
+ if (realigned !== undefined && override["paragraphs"] === undefined)
328
+ override["textAlign"] = realigned.align;
329
+ }
330
+ // `null` takes away a line limit or truncation the component has.
331
+ if (base.type === "text" && next.type === "text") {
332
+ for (const name of ["maxLines", "truncate"])
333
+ if (base[name] !== next[name])
334
+ override[name] = next[name] ?? null;
335
+ }
336
+ return override;
337
+ }
338
+ /**
339
+ * The `LayerOverride.sizing` that turns the Hug or Fixed sizing of `base` (a
340
+ * component layer, converted on its own) into that of `next` (the same layer
341
+ * with an instance's override fields, converted), both by `stackLayoutOf`, or
342
+ * `undefined` when nothing differs or either is not a stack. An axis where the
343
+ * layer fills its stack is taken off later, by `dropSizingWhereFilled`.
344
+ */
345
+ function sizingBetween(base, next, fields) {
346
+ if (base.type !== "frame" || next.type !== "frame" || base.layout.kind === "absolute" || next.layout.kind === "absolute")
347
+ return { same: [] };
348
+ const primary = next.layout.kind === "vertical" ? "height" : "width";
349
+ const named = new Set([
350
+ ...("stackPrimarySizing" in fields ? [primary] : []), ...("stackCounterSizing" in fields ? [primary === "width" ? "height" : "width"] : []),
351
+ ]);
352
+ const sizing = {};
353
+ const same = [];
354
+ for (const [axis, key] of [["width", "widthSizing"], ["height", "heightSizing"]]) {
355
+ if (next.layout[key] !== base.layout[key])
356
+ sizing[axis] = next.layout[key];
357
+ else if (named.has(axis)) {
358
+ sizing[axis] = next.layout[key];
359
+ same.push(axis);
360
+ }
361
+ }
362
+ return Object.keys(sizing).length > 0 ? { sizing, same } : { same };
363
+ }
364
+ /**
365
+ * Takes off each `LayerOverride.sizing` axis in `held` that no holder's own
366
+ * override changes, as it then only repeats the component's sizing. Then
367
+ * writes each axis the override leaves out as the outermost holder that
368
+ * overrides it has it, since the outer `sizing` replaces a holder's whole
369
+ * (`mergeOverrides` in the model's instance resolver) where Figma keeps the
370
+ * other axis. Runs once every instance has its overrides, like
371
+ * `unbindInnerBindings`. A holder's axis read here may itself be one this
372
+ * takes off later, which keeps an axis that repeats what is there anyway.
373
+ */
374
+ export function dropUnheldSizing(overrides, held) {
375
+ if (overrides === undefined)
376
+ return;
377
+ for (const [key, { axes, holders }] of held) {
378
+ const override = overrides[key];
379
+ if (override?.sizing === undefined)
380
+ continue;
381
+ const heldAs = (axis) => holders.map(({ instance, inner }) => instance.type === "instance" ? entryOf(instance.overrides, inner)?.sizing?.[axis] : undefined).find((value) => value !== undefined);
382
+ const unheld = new Set(axes.filter((axis) => heldAs(axis) === undefined));
383
+ const kept = Object.fromEntries(Object.entries(override.sizing).filter(([axis]) => !unheld.has(axis)));
384
+ const others = Object.keys(kept).length === 0 ? [] : ["width", "height"].filter((axis) => !(axis in kept));
385
+ const sizing = { ...kept, ...Object.fromEntries(others.flatMap((axis) => heldAs(axis) === undefined ? [] : [[axis, heldAs(axis)]])) };
386
+ if (unheld.size === 0 && Object.keys(sizing).length === Object.keys(override.sizing).length)
387
+ continue;
388
+ const { sizing: _sizing, ...rest } = override;
389
+ const next = Object.keys(sizing).length > 0 ? { ...rest, sizing } : rest;
390
+ if (Object.keys(next).length > 0)
391
+ overrides[key] = next;
392
+ else
393
+ delete overrides[key];
394
+ }
395
+ }
396
+ /**
397
+ * Takes off each `LayerOverride.sizing` axis where the layer fills its stack,
398
+ * as Fill wins over a frame's own Hug or Fixed in Figma (see
399
+ * `stackChildFields`) and Taco refuses a frame that both fills and hugs; under
400
+ * a nested instance's component root, the nested instance's Fill counts. Runs
401
+ * once the walk has settled the stacks, which is when a layer's Fill is known;
402
+ * `nodes` are the converted layers by their Taco ids and `roots` the ids of
403
+ * the component roots.
404
+ */
405
+ export function dropSizingWhereFilled(overrides, nodes, roots) {
406
+ if (overrides === undefined)
407
+ return;
408
+ for (const [key, override] of Object.entries(overrides)) {
409
+ if (override.sizing === undefined)
410
+ continue;
411
+ const path = parseLayerPath(key) ?? [];
412
+ const layer = entryOf(nodes, path.at(-1) ?? "");
413
+ const holder = layer !== undefined && roots.has(layer.id) ? entryOf(nodes, path.at(-2) ?? "") : undefined;
414
+ const fills = (axis) => [layer, holder?.type === "instance" ? holder : undefined]
415
+ .some((node) => node !== undefined && "resizing" in node && node.resizing?.[axis] === "fill");
416
+ const sizing = Object.fromEntries(Object.entries(override.sizing).filter(([axis]) => !fills(axis)));
417
+ const { sizing: _sizing, ...rest } = override;
418
+ const next = Object.keys(sizing).length > 0 ? { ...rest, sizing } : rest;
419
+ if (Object.keys(next).length > 0)
420
+ overrides[key] = next;
421
+ else
422
+ delete overrides[key];
423
+ }
424
+ }
425
+ /** What an override path resolves to when it goes through a swap the nesting check left out (`InstanceContext.refusedSwaps`). */
426
+ const INSIDE_LEFT_OUT = "inside a left-out swap";
427
+ /** The override fields that give a text layer another line height, so an instance that sets one keeps its own. */
428
+ const LINE_HEIGHT_SETTERS = ["lineHeight", "styleIdForText", "fontSize"];
429
+ /**
430
+ * The one line height in pixels Figma laid out every line of a text at, read from its stored layout (`derivedTextData`,
431
+ * on a text node or a `derivedSymbolData` entry), or `undefined` without lines or with lines of different heights.
432
+ */
433
+ function storedLineHeight(fields, where) {
434
+ const derived = field(fields, "derivedTextData", "object", where);
435
+ const lines = derived === undefined ? [] : field(derived, "baselines", "list", `${where} derivedTextData`) ?? [];
436
+ let found;
437
+ for (const [index, line] of lines.entries()) {
438
+ const height = isObject(line) ? field(line, "lineHeight", "number", `${where} derivedTextData.baselines[${String(index)}]`) : undefined;
439
+ if (height === undefined || (found !== undefined && Math.abs(found - height) > 0.01))
440
+ return undefined;
441
+ found ??= height;
442
+ }
443
+ return found;
444
+ }
445
+ /** Each component's layers by Figma id, for walking up from a layer. */
446
+ const layersByFigmaIdCache = new WeakMap();
447
+ function layersByFigmaId(component) {
448
+ let found = layersByFigmaIdCache.get(component);
449
+ if (found === undefined)
450
+ layersByFigmaIdCache.set(component, found = new Map([...component.layers.values()].map((layer) => [layer.figma.id, layer])));
451
+ return found;
452
+ }
453
+ /** The variable bindings that set a frame's layout. */
454
+ const LAYOUT_BINDINGS = ["gap", "wrapGap", "columnGap", "rowGap", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft"];
455
+ /** How far apart two lengths may be and still count as the same: Figma stores float32 numbers. */
456
+ const LENGTH_TOLERANCE = 0.05;
457
+ /** A Figma layer's size and center in its parent, from `size` and `transform`, or `undefined` when either is incomplete. */
458
+ function figmaBox(size, transform, where) {
459
+ if (!isObject(size) || !isObject(transform))
460
+ return undefined;
461
+ const sides = readNumbers(size, ["x", "y"], `${where} size`);
462
+ const m = readNumbers(transform, ["m00", "m01", "m02", "m10", "m11", "m12"], `${where} transform`);
463
+ if (sides === null || m === null)
464
+ return undefined;
465
+ return {
466
+ width: sides.x, height: sides.y,
467
+ x: m.m02 + (m.m00 * sides.x + m.m01 * sides.y) / 2, y: m.m12 + (m.m10 * sides.x + m.m11 * sides.y) / 2,
468
+ };
469
+ }
470
+ /** A Figma layer's axis-aligned bounds in its parent, from `size` and `transform`, or `undefined` when either is incomplete. */
471
+ function figmaBounds(size, transform, where) {
472
+ if (!isObject(size) || !isObject(transform))
473
+ return undefined;
474
+ const sides = readNumbers(size, ["x", "y"], `${where} size`);
475
+ const m = readNumbers(transform, ["m00", "m01", "m02", "m10", "m11", "m12"], `${where} transform`);
476
+ if (sides === null || m === null)
477
+ return undefined;
478
+ const corners = [[0, 0], [sides.x, 0], [0, sides.y], [sides.x, sides.y]];
479
+ const xs = corners.map(([u, v]) => m.m00 * u + m.m01 * v + m.m02);
480
+ const ys = corners.map(([u, v]) => m.m10 * u + m.m11 * v + m.m12);
481
+ const x = Math.min(...xs);
482
+ const y = Math.min(...ys);
483
+ return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y };
484
+ }
485
+ /**
486
+ * Whether Taco moves and scales a path other than Figma laid it out. A path
487
+ * has no frame: Taco constrains it by its geometry's bounds, scaling and
488
+ * moving the geometry along each axis, so the map from its bounds before to
489
+ * its bounds after is applied to Figma's bounds before and compared with
490
+ * Figma's bounds after.
491
+ */
492
+ function pathPlacedOtherThanFigma(node, placed, figmaBefore, figmaAfter) {
493
+ const before = getNodeBounds(node);
494
+ const after = getNodeBounds(placed);
495
+ const axis = (start, length, nextStart, nextLength, figmaStart, figmaLength) => {
496
+ const scale = length === 0 ? 1 : nextLength / length;
497
+ return { start: nextStart + (figmaStart - start) * scale, length: figmaLength * scale };
498
+ };
499
+ const x = axis(before.x, before.width, after.x, after.width, figmaBefore.x, figmaBefore.width);
500
+ const y = axis(before.y, before.height, after.y, after.height, figmaBefore.y, figmaBefore.height);
501
+ return [[x.start, figmaAfter.x], [x.length, figmaAfter.width], [y.start, figmaAfter.y], [y.length, figmaAfter.height]]
502
+ .some(([taco, figma]) => Math.abs(taco - figma) > LENGTH_TOLERANCE);
503
+ }
504
+ /**
505
+ * Whether Taco lays out a resized instance of a component without auto
506
+ * layout other than Figma did: Taco moves and resizes the component's layers
507
+ * by their constraints (`constrainChildren`, as the instance resolver does),
508
+ * and Figma keeps the result in `derivedSymbolData`, a size and transform
509
+ * for each layer path it changed. Both are compared as changes from the
510
+ * component's own layer, so the two ways of placing a layer need not agree.
511
+ * Only the component's own layers are compared, not those inside a nested
512
+ * instance. `swappedToOtherSize` tells whether the instance swaps one of
513
+ * them to a component of another size: Taco gives it that size before its
514
+ * constraints unless it was resized (`swappedInstance` in the model), which is not simulated
515
+ * here, so a resized instance with one counts as laid out otherwise.
516
+ */
517
+ function constrainedOtherThanFigma(instance, component, self, nodes, swappedToOtherSize, kept) {
518
+ const from = component.root.frame;
519
+ if (self.frame.width === from.width && self.frame.height === from.height)
520
+ return false;
521
+ const where = `node ${instance.id}`;
522
+ // Each layer's size and transform as Figma shows them in the instance: laid out, else overridden, else the component's.
523
+ const laidOut = new Map();
524
+ const overridden = new Map();
525
+ let derivedCount = 0;
526
+ for (const [list, into] of [["derivedSymbolData", laidOut], ["symbolOverrides", overridden]]) {
527
+ const entries = list === "derivedSymbolData" ? field(instance.change, list, "list", where) ?? []
528
+ : field(field(instance.change, "symbolData", "object", where) ?? {}, list, "list", `${where} symbolData`) ?? [];
529
+ if (list === "derivedSymbolData")
530
+ derivedCount = entries.length;
531
+ for (const [index, entry] of entries.entries()) {
532
+ if (!isObject(entry))
533
+ continue;
534
+ const at = `${where} ${list}[${String(index)}]`;
535
+ const path = field(entry, "guidPath", "object", at);
536
+ const guids = path === undefined ? [] : field(path, "guids", "list", `${at}.guidPath`) ?? [];
537
+ if (guids.length === 1)
538
+ into.set(guidText(guids[0], `${at}.guidPath`), entry);
539
+ }
540
+ }
541
+ // Without Figma's layout there is nothing to compare against.
542
+ if (derivedCount === 0)
543
+ return false;
544
+ if (swappedToOtherSize)
545
+ return true;
546
+ const placed = new Map(constrainChildren(nodes, component.root.id, from, self.frame).map((node) => [node.id, node]));
547
+ for (const [key, { figma, node }] of component.layers) {
548
+ if (node.id === component.root.id || kept?.has(layerPathKey([node.id])))
549
+ continue;
550
+ const at = `node ${figma.id}`;
551
+ const derived = laidOut.get(key);
552
+ const override = overridden.get(key);
553
+ // For saved files, only compare paths with a derived entry. Other layers still follow constraints.
554
+ if (kept && !derived)
555
+ continue;
556
+ const sizeAfter = derived?.["size"] ?? override?.["size"] ?? figma.change["size"];
557
+ const transformAfter = derived?.["transform"] ?? override?.["transform"] ?? figma.change["transform"];
558
+ if (!("frame" in node)) {
559
+ // Figma lays out a path again only where it keeps a size, transform and geometry for it; elsewhere it shows no layout to compare against.
560
+ if ([derived, override].every((entry) => entry?.["size"] === undefined && entry?.["transform"] === undefined))
561
+ continue;
562
+ const figmaBefore = figmaBounds(figma.change["size"], figma.change["transform"], at);
563
+ const figmaAfter = figmaBounds(sizeAfter, transformAfter, at);
564
+ if (figmaBefore === undefined || figmaAfter === undefined)
565
+ continue;
566
+ if (pathPlacedOtherThanFigma(node, placed.get(node.id) ?? node, figmaBefore, figmaAfter))
567
+ return true;
568
+ continue;
569
+ }
570
+ const before = figmaBox(figma.change["size"], figma.change["transform"], at);
571
+ const figmaAfter = figmaBox(sizeAfter, transformAfter, at);
572
+ if (before === undefined || figmaAfter === undefined)
573
+ continue;
574
+ const tacoAfter = (placed.get(node.id) ?? node);
575
+ const center = (frame) => ({ x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 });
576
+ const tacoBefore = center(node.frame);
577
+ const tacoNow = center(tacoAfter.frame);
578
+ const changes = [
579
+ [figmaAfter.width - before.width, tacoAfter.frame.width - node.frame.width],
580
+ [figmaAfter.height - before.height, tacoAfter.frame.height - node.frame.height],
581
+ [figmaAfter.x - before.x, tacoNow.x - tacoBefore.x],
582
+ [figmaAfter.y - before.y, tacoNow.y - tacoBefore.y],
583
+ ];
584
+ if (changes.some(([figmaChange, tacoChange]) => Math.abs(figmaChange - tacoChange) > LENGTH_TOLERANCE)) {
585
+ return true;
586
+ }
587
+ }
588
+ return false;
589
+ }
590
+ /** A derived entry can omit fields that still have their authored or component values. */
591
+ function storedBox(layer, derived, authored) {
592
+ const { figma, node } = layer;
593
+ const path = node.type === "shape" && node.shape === "path";
594
+ if (path && [derived, authored].every(entry => entry?.["size"] === undefined && entry?.["transform"] === undefined))
595
+ return undefined;
596
+ const geometry = frameGeometry({ ...figma, change: {
597
+ size: derived["size"] ?? authored?.["size"] ?? figma.change["size"],
598
+ transform: derived["transform"] ?? authored?.["transform"] ?? figma.change["transform"],
599
+ } });
600
+ if (!geometry)
601
+ return undefined;
602
+ const { sides: { x: width, y: height }, m } = geometry;
603
+ if (width < 0 || height < 0)
604
+ return undefined;
605
+ const transform = [m.m00, m.m10, m.m01, m.m11, m.m02, m.m12];
606
+ if (!path)
607
+ return { width, height, transform };
608
+ const before = figma.change["size"];
609
+ if (!isObject(before))
610
+ return undefined;
611
+ const original = readNumbers(before, ["x", "y"], `node ${figma.id} size`);
612
+ if (!original || (!original.x && width) || (!original.y && height))
613
+ return undefined;
614
+ const pathScale = [original.x ? width / original.x : 1, original.y ? height / original.y : 1];
615
+ if (!pathScale.every(Number.isFinite))
616
+ return undefined;
617
+ return { width, height, transform, pathScale };
618
+ }
619
+ /**
620
+ * The axes an instance hugs where Figma stored another size for it (`size`)
621
+ * than the one it laid its root out at (the `derivedSymbolData` entry whose
622
+ * path is just the component root's key). Figma keeps the stored size after
623
+ * the instance's contents change, such as a text style's line height, and
624
+ * places the layers by the laid-out one; Taco would hug the contents again,
625
+ * so these axes are kept Fixed at the stored size instead. Fill still wins,
626
+ * as the instance's own `resizing` comes before its sizing override.
627
+ */
628
+ function storedOverHug(instance, component, self) {
629
+ if (self.layout.kind === "absolute")
630
+ return [];
631
+ const where = `node ${instance.id}`;
632
+ const rootKey = overrideKeyOf(component.symbol);
633
+ const root = (field(instance.change, "derivedSymbolData", "list", where) ?? []).find((entry, index) => {
634
+ if (!isObject(entry))
635
+ return false;
636
+ const at = `${where} derivedSymbolData[${String(index)}]`;
637
+ const path = field(entry, "guidPath", "object", at);
638
+ const guids = path === undefined ? [] : field(path, "guids", "list", `${at}.guidPath`) ?? [];
639
+ return guids.length === 1 && guidText(guids[0], `${at}.guidPath`) === rootKey;
640
+ });
641
+ const laidOut = root?.["size"];
642
+ const stored = instance.change["size"];
643
+ if (!isObject(laidOut) || !isObject(stored))
644
+ return [];
645
+ const layout = self.layout;
646
+ return [["width", "x", "widthSizing"], ["height", "y", "heightSizing"]].flatMap(([axis, key, sizingKey]) => {
647
+ const [from, to] = [laidOut[key], stored[key]];
648
+ return layout[sizingKey] === "hug" && typeof from === "number" && typeof to === "number" && Math.abs(from - to) > LENGTH_TOLERANCE ? [axis] : [];
649
+ });
650
+ }
651
+ /**
652
+ * The instance fields made from a Figma INSTANCE once every component is
653
+ * imported: its property values (`componentPropAssignments`) and its
654
+ * overrides. `self` is the instance converted as a frame; where its own
655
+ * paints, strokes and effects differ from the component root's they become
656
+ * an override under the root's path, and so does a Hug or Fixed axis that
657
+ * differs. Each `symbolOverrides` path step names a layer by its
658
+ * `overrideKey` (or guid); a step past the first goes through a nested
659
+ * instance into the component it shows, after explicit swaps by this instance or its nested holders,
660
+ * or a swap driven by a component property. Fields become `LayerOverride` fields where Taco
661
+ * has them (`overriddenSymbolID` a swap, `componentPropAssignments` property
662
+ * values, paints, effects, visibility, opacity, text); the rest are counted
663
+ * through `leftOutField`. A swap in `refusedSwaps` is left out, and so is
664
+ * every override and property value set inside the component it would show.
665
+ * `swaps` are the swaps kept, as `container>target` SYMBOL ids, for the
666
+ * walk's nesting check.
667
+ */
668
+ export function instanceFields(instance, component, self, context) {
669
+ const where = `node ${instance.id}`;
670
+ const overrides = {};
671
+ const overrideAt = (key) => (overrides[key] ??= {});
672
+ const assignedLinks = new Map();
673
+ const captureLinks = (shown, path) => (id, data, text) => {
674
+ const key = `${path}/${id}`, table = data["styleOverrideTable"];
675
+ if (Array.isArray(table) && table.some(row => isObject(row) && Object.hasOwn(row, "hyperlink")))
676
+ assignedLinks.set(key, { shown, path, id, text, data });
677
+ else
678
+ assignedLinks.delete(key);
679
+ };
680
+ const componentIdOf = (symbolId) => context.component(symbolId)?.componentId;
681
+ const swapsKept = new Set();
682
+ const refusedSwap = (container, target) => context.refusedSwaps?.get(`${container.symbol.id}>${target}`);
683
+ const pathSwaps = new Map();
684
+ const swapsAtPath = (path) => {
685
+ let record = pathSwaps.get(path);
686
+ if (!record)
687
+ pathSwaps.set(path, record = {});
688
+ return record;
689
+ };
690
+ // Checks an instance swap value of `inComponent`'s property: the reason it is left out, else `undefined`, and the swap is kept.
691
+ const leftOutValue = (inComponent, path) => (symbolId, property) => {
692
+ const refused = refusedSwap(inComponent, symbolId);
693
+ // Another variant can bind an assignment which is dormant on the stored component.
694
+ const properties = swapsAtPath(path).properties ??= {};
695
+ if (refused === undefined) {
696
+ properties[property] = symbolId;
697
+ if (inComponent.boundSwaps.has(property))
698
+ swapsKept.add(`${inComponent.symbol.id}>${symbolId}`);
699
+ }
700
+ else
701
+ properties[property] ??= INSIDE_LEFT_OUT;
702
+ return refused;
703
+ };
704
+ const symbolData = field(instance.change, "symbolData", "object", where) ?? {};
705
+ const entries = (field(symbolData, "symbolOverrides", "list", `${where} symbolData`) ?? []).flatMap((entry, index) => {
706
+ const at = `${where} symbolOverrides[${String(index)}]`;
707
+ if (!isObject(entry))
708
+ return [];
709
+ const path = field(entry, "guidPath", "object", at);
710
+ const guids = path === undefined ? [] : field(path, "guids", "list", `${at}.guidPath`) ?? [];
711
+ return [{ keys: guids.map((guid) => guidText(guid, `${at}.guidPath`)), entry, at }];
712
+ }).sort((a, b) => a.keys.length - b.keys.length);
713
+ const rootFields = Object.assign({}, ...entries.filter(({ keys }) => keys.length === 1 && keys[0] === component.symbol.id)
714
+ .map(({ entry }) => Object.fromEntries(Object.entries(entry).filter(([key]) => FRAME_FIELDS.has(key) || Object.hasOwn(PADDING_FIELDS, key)))));
715
+ const ownFields = { ...instance.change, ...rootFields };
716
+ if (Object.keys(rootFields).length) {
717
+ const converted = context.convertAlone(instance, rootFields);
718
+ if (converted?.type === "frame")
719
+ self = { ...self, layout: converted.layout, style: { ...self.style, cornerSmoothing: converted.style?.cornerSmoothing ?? 0 },
720
+ clipContent: !!converted.clipContent };
721
+ }
722
+ // The instance's own frame against the component root.
723
+ const rootKey = layerPathKey([component.root.id]);
724
+ const rootStyle = styleOf(component.root);
725
+ const ownStyle = styleOf(self);
726
+ for (const name of STYLE_OVERRIDES) {
727
+ if (name === "cornerSmoothing" && ownFields.cornerSmoothing === undefined)
728
+ continue;
729
+ if (!same(rootStyle[name], ownStyle[name]))
730
+ overrideAt(rootKey)[name] = ownStyle[name] ?? (name === "layerBlur" || name === "backgroundBlur" || name === "cornerSmoothing" ? 0 : []);
731
+ }
732
+ for (const name of new Set([...Object.keys(rootStyle), ...Object.keys(ownStyle)])) {
733
+ if (context.fileOverride && (name === "cornerRadius" || name === "cornerRadii"))
734
+ continue;
735
+ if (!STYLE_OVERRIDES.includes(name) && !same(rootStyle[name], ownStyle[name])) {
736
+ context.report("property-left-out", `an instance's own ${name} differs from its component and is left out: Taco instances cannot override it`);
737
+ }
738
+ }
739
+ // A sparse INSTANCE can omit its entire stack and clip flag. Only authored fields replace the template.
740
+ if (ownFields.stackMode === undefined || rootFields.stackMode !== undefined || ownFields.stackMode !== component.symbol.change["stackMode"]) {
741
+ const stack = Object.keys(ownFields).some(key => FRAME_FIELDS.has(key) && key.startsWith("stack") || Object.hasOwn(PADDING_FIELDS, key));
742
+ const layout = stack ? stackLayoutOf({ ...component.symbol.change, ...ownFields }, () => { }) : undefined;
743
+ self = { ...self, layout: layout ?? (ownFields.stackMode === undefined ? component.root.layout : self.layout) };
744
+ }
745
+ Object.assign(overrideAt(rootKey), frameOverrides(component.root, {
746
+ ...self, clipContent: !!(ownFields.frameMaskDisabled === undefined ? component.root.clipContent : self.clipContent),
747
+ }));
748
+ if (component.root.layout.kind !== "absolute" && self.layout.kind !== "absolute") {
749
+ const sizing = {};
750
+ for (const [axis, key] of [["width", "widthSizing"], ["height", "heightSizing"]]) {
751
+ const own = self.layout[key];
752
+ if (own !== component.root.layout[key] && (own === "hug" || own === "fixed"))
753
+ sizing[axis] = own;
754
+ }
755
+ // Figma does not lay an instance's own frame out again after its contents change: it draws the size it stored.
756
+ const kept = storedOverHug(instance, component, self);
757
+ for (const axis of kept) {
758
+ if (component.root.layout[axis === "width" ? "widthSizing" : "heightSizing"] === "fixed")
759
+ delete sizing[axis];
760
+ else
761
+ sizing[axis] = "fixed";
762
+ }
763
+ if (kept.length > 0)
764
+ context.report("approximated", "instance keeps the size Figma stored after its contents changed");
765
+ if (Object.keys(sizing).length > 0)
766
+ overrideAt(rootKey)["sizing"] = sizing;
767
+ }
768
+ if (component.root.layout.kind !== "absolute" && self.layout.kind !== "absolute") {
769
+ // The sides the instance pads differently from its component root, as Figma lets an instance do.
770
+ const own = self.layout.padding;
771
+ const from = component.root.layout.padding;
772
+ const padding = {};
773
+ for (const side of ["top", "right", "bottom", "left"])
774
+ if (own[side] !== from[side])
775
+ padding[side] = own[side];
776
+ if (Object.keys(padding).length > 0)
777
+ overrideAt(rootKey)["padding"] = padding;
778
+ }
779
+ // The property values set for the instance at each path's Figma keys ("" for this instance), for instance swap properties.
780
+ const assignmentsAt = new Map([["", field(instance.change, "componentPropAssignments", "list", where) ?? []]]);
781
+ for (const { keys, entry, at } of entries) {
782
+ const list = field(entry, "componentPropAssignments", "list", at);
783
+ if (list !== undefined && keys.length > 0)
784
+ assignmentsAt.set(keys.join("/"), [...assignmentsAt.get(keys.join("/")) ?? [], ...list]);
785
+ }
786
+ // Each holder's path ends at the bound layer. The assignment belongs to its parent instance
787
+ // (the empty path for the innermost holder). An explicit swap resets values from deeper holders.
788
+ const heldPropertySwap = (through, property) => {
789
+ for (const holder of through) {
790
+ const parent = layerPathKey(parseLayerPath(holder.inner).slice(0, -1));
791
+ const inherited = context.nestedSwaps(holder.instance, parent);
792
+ const value = inherited?.properties?.[property];
793
+ if (value !== undefined || inherited?.symbol !== undefined)
794
+ return value;
795
+ }
796
+ return undefined;
797
+ };
798
+ // A placement's own assignment takes precedence over its enclosing holders.
799
+ const propertySwap = (layer, inComponent, parentKey, through) => {
800
+ let symbolId;
801
+ for (const ref of field(layer.change, "componentPropRefs", "list", `node ${layer.id}`) ?? []) {
802
+ if (!isObject(ref) || ref["componentPropNodeField"] !== "OVERRIDDEN_SYMBOL_ID" || ref["defID"] === undefined || ref["isDeleted"] === true)
803
+ continue;
804
+ const property = propertyByFigmaId(inComponent.properties, guidText(ref["defID"], `node ${layer.id} componentPropRefs`));
805
+ if (property === undefined)
806
+ continue;
807
+ let own;
808
+ for (const assignment of assignmentsAt.get(parentKey) ?? []) {
809
+ if (!isObject(assignment) || assignment["defID"] === undefined)
810
+ continue;
811
+ if (propertyByFigmaId(inComponent.properties, guidText(assignment["defID"], `${where} componentPropAssignments`)) !== property)
812
+ continue;
813
+ own = assignedValueOf(assignment, `${where} componentPropAssignments`).symbolId ?? own;
814
+ }
815
+ symbolId = own ?? (swaps.has(parentKey) ? undefined : heldPropertySwap(through, property.definition.id)) ?? symbolId;
816
+ }
817
+ return symbolId;
818
+ };
819
+ // The component a nested instance layer in `inComponent` shows, by its path's Figma keys: a swap this instance made, else a swap
820
+ // property value, else its own. `INSIDE_LEFT_OUT` when the nesting check left out the swap or value it would show.
821
+ const swaps = new Map();
822
+ const leftOutSwaps = new Set();
823
+ const shownAt = (keys, layer, inComponent, through) => {
824
+ const key = keys.join("/");
825
+ const swapped = swaps.get(key);
826
+ if (swapped !== undefined)
827
+ return context.component(swapped);
828
+ if (leftOutSwaps.has(key))
829
+ return INSIDE_LEFT_OUT;
830
+ for (const holder of through) {
831
+ const inherited = context.nestedSwaps(holder.instance, holder.inner)?.symbol;
832
+ if (inherited !== undefined)
833
+ return inherited === INSIDE_LEFT_OUT ? INSIDE_LEFT_OUT : context.component(inherited);
834
+ }
835
+ const valued = propertySwap(layer, inComponent, keys.slice(0, -1).join("/"), through);
836
+ if (valued === INSIDE_LEFT_OUT || (valued !== undefined && refusedSwap(inComponent, valued) !== undefined))
837
+ return INSIDE_LEFT_OUT;
838
+ return context.component(valued ?? shownSymbol(layer) ?? "");
839
+ };
840
+ const resolve = (keys) => {
841
+ let inComponent = component;
842
+ const ids = [];
843
+ const instances = [];
844
+ let layer;
845
+ for (let i = 0; i < keys.length; i++) {
846
+ if (inComponent === undefined || inComponent === INSIDE_LEFT_OUT)
847
+ return inComponent;
848
+ layer = inComponent.layers.get(keys[i]);
849
+ if (layer === undefined) {
850
+ const flattenedInto = inComponent.flattened.get(keys[i]);
851
+ return flattenedInto === undefined ? undefined : { flattenedInto };
852
+ }
853
+ ids.push(layer.node.id);
854
+ const through = instances.map((instance, at) => ({ instance, inner: layerPathKey(ids.slice(at + 1)) }));
855
+ if (i === keys.length - 1) {
856
+ return { key: layerPathKey(ids), layer, component: inComponent, through };
857
+ }
858
+ if (layer.figma.type !== "INSTANCE")
859
+ return undefined;
860
+ instances.push(layer.node);
861
+ inComponent = shownAt(keys.slice(0, i + 1), layer.figma, inComponent, through);
862
+ }
863
+ return undefined;
864
+ };
865
+ /**
866
+ * The values that put back the defaults of the swapped-in component's properties that the components holding the nested
867
+ * instance layer at `keys` give it (the layer's own values and overrides at its path in the components it is in) and
868
+ * that the swap override `entry` does not set. Figma gives a layer swapped by an override only the values that override
869
+ * carries, while Taco would keep the values held below on top of the swapped-in component's defaults.
870
+ */
871
+ const swapResetValues = (keys, entry, shown, at) => {
872
+ const reset = {};
873
+ if (shown === undefined)
874
+ return reset;
875
+ const held = [];
876
+ for (let i = 0; i < keys.length; i++) {
877
+ const host = resolve(keys.slice(0, i + 1));
878
+ if (host === undefined || host === INSIDE_LEFT_OUT || "flattenedInto" in host || host.layer.figma.type !== "INSTANCE")
879
+ continue;
880
+ const hostWhere = `node ${host.layer.figma.id}`;
881
+ if (i === keys.length - 1) {
882
+ held.push(...field(host.layer.figma.change, "componentPropAssignments", "list", hostWhere) ?? []);
883
+ continue;
884
+ }
885
+ const rest = keys.slice(i + 1).join("/");
886
+ const hostData = field(host.layer.figma.change, "symbolData", "object", hostWhere) ?? {};
887
+ for (const inner of field(hostData, "symbolOverrides", "list", `${hostWhere} symbolData`) ?? []) {
888
+ if (!isObject(inner))
889
+ continue;
890
+ const path = field(inner, "guidPath", "object", hostWhere);
891
+ const guids = path === undefined ? [] : field(path, "guids", "list", `${hostWhere}.guidPath`) ?? [];
892
+ if (guids.map((guid) => guidText(guid, `${hostWhere}.guidPath`)).join("/") !== rest)
893
+ continue;
894
+ held.push(...field(inner, "componentPropAssignments", "list", hostWhere) ?? []);
895
+ }
896
+ }
897
+ const own = new Set();
898
+ for (const assignment of field(entry, "componentPropAssignments", "list", at) ?? []) {
899
+ if (!isObject(assignment) || assignment["defID"] === undefined)
900
+ continue;
901
+ const property = propertyByFigmaId(shown.properties, guidText(assignment["defID"], `${at} componentPropAssignments`));
902
+ if (property !== undefined)
903
+ own.add(property.definition.id);
904
+ }
905
+ for (const assignment of held) {
906
+ if (!isObject(assignment) || assignment["defID"] === undefined)
907
+ continue;
908
+ const definition = propertyByFigmaId(shown.properties, guidText(assignment["defID"], `${where} held componentPropAssignments`))?.definition;
909
+ if (definition === undefined || definition.kind === "slot" || own.has(definition.id))
910
+ continue;
911
+ reset[definition.id] = definition.defaultValue;
912
+ }
913
+ return reset;
914
+ };
915
+ const insideLeftOut = new Set();
916
+ const pending = new Map();
917
+ const targets = [];
918
+ let rootExports;
919
+ // Swaps first, shorter paths before longer ones, so property values and deeper paths are read against the component swapped in.
920
+ for (const { keys, entry, at } of entries) {
921
+ // A path naming the component itself targets the instance, which already carries those values.
922
+ if (keys.length === 1 && keys[0] === component.symbol.id) {
923
+ for (const name of HANDOFF_OVERRIDE_FIELDS)
924
+ if (activeHandoffOverride(entry[name]))
925
+ context.leftOutField(name);
926
+ if (entry["exportSettings"] !== undefined)
927
+ rootExports = entry["exportSettings"];
928
+ continue;
929
+ }
930
+ if (entry["exportSettings"] !== undefined) {
931
+ context.report("property-left-out", "an export settings override on an inherited layer is left out");
932
+ }
933
+ const target = keys.length === 0 ? undefined : resolve(keys);
934
+ if (target !== undefined && target !== INSIDE_LEFT_OUT && "flattenedInto" in target) {
935
+ context.report("property-left-out", `an override of an operand of the boolean operation ${JSON.stringify(target.flattenedInto)} is left out: the boolean operation is flattened to its outline`);
936
+ continue;
937
+ }
938
+ if (target === undefined || target === INSIDE_LEFT_OUT) {
939
+ if (target === undefined)
940
+ context.report("property-left-out", keys.some(key => !context.hasSourceKey(key))
941
+ ? "an override path contains a GUID with no source layer or override key"
942
+ : "an override path that names no imported layer of the component is left out");
943
+ else
944
+ insideLeftOut.add(entry);
945
+ continue;
946
+ }
947
+ let gathered = pending.get(target.key);
948
+ if (gathered === undefined)
949
+ pending.set(target.key, gathered = { target, fields: {}, override: overrideAt(target.key) });
950
+ context.fileOverride?.(target.key, entry);
951
+ targets.push({ keys, entry, at, gathered });
952
+ if (entry["overriddenSymbolID"] === undefined || target.layer.figma.type !== "INSTANCE")
953
+ continue;
954
+ const symbolId = guidText(entry["overriddenSymbolID"], `${at} overriddenSymbolID`);
955
+ const swapped = componentIdOf(symbolId);
956
+ const refused = refusedSwap(target.component, symbolId);
957
+ if (swapped === undefined)
958
+ context.report("property-left-out", "a swap to a component that is not in the message is left out");
959
+ else if (refused !== undefined) {
960
+ context.report("property-left-out", `a swap ${refused}`);
961
+ leftOutSwaps.add(keys.join("/"));
962
+ if (!swaps.has(keys.join("/")))
963
+ swapsAtPath(target.key).symbol = INSIDE_LEFT_OUT;
964
+ }
965
+ else {
966
+ gathered.override["componentId"] = swapped;
967
+ const reset = swapResetValues(keys, entry, context.component(symbolId), at);
968
+ if (Object.keys(reset).length > 0)
969
+ gathered.override["propertyValues"] = { ...gathered.override["propertyValues"], ...reset };
970
+ swaps.set(keys.join("/"), symbolId);
971
+ swapsAtPath(target.key).symbol = symbolId;
972
+ swapsKept.add(`${target.component.symbol.id}>${symbolId}`);
973
+ }
974
+ }
975
+ const boxes = new Map();
976
+ const from = component.root.frame;
977
+ const resizedFreeFrame = component.root.layout.kind === "absolute" && (self.frame.width !== from.width || self.frame.height !== from.height);
978
+ if (context.fileLayout) {
979
+ const authored = new Map();
980
+ for (const { keys, entry } of entries) {
981
+ const key = keys.join("/");
982
+ authored.set(key, { ...authored.get(key), ...entry });
983
+ }
984
+ for (const [index, entry] of (field(instance.change, "derivedSymbolData", "list", where) ?? []).entries()) {
985
+ if (!isObject(entry) || (!resizedFreeFrame && entry["size"] === undefined))
986
+ continue;
987
+ const at = `${where} derivedSymbolData[${String(index)}]`;
988
+ const path = field(entry, "guidPath", "object", at);
989
+ const keys = (path === undefined ? [] : field(path, "guids", "list", `${at}.guidPath`) ?? []).map(guid => guidText(guid, `${at}.guidPath`));
990
+ const target = resolve(keys);
991
+ if (!target || target === INSIDE_LEFT_OUT || "flattenedInto" in target || target.layer.node.id === target.component.root.id)
992
+ continue;
993
+ // A stack can allocate a different size even when the stored group or vector
994
+ // matches its main. Keep that explicit size as an input to the adapter.
995
+ const layer = target.layer.node;
996
+ const change = target.layer.figma.change;
997
+ const requestsFill = change["stackPositioning"] !== "ABSOLUTE" &&
998
+ (Number(change["stackChildPrimaryGrow"]) > 0 || change["stackChildAlignSelf"] === "STRETCH");
999
+ const fillLayer = layer.type === "group" || (layer.type === "shape" && layer.shape === "path");
1000
+ if (!resizedFreeFrame && !(fillLayer && requestsFill))
1001
+ continue;
1002
+ const box = storedBox(target.layer, entry, authored.get(keys.join("/")));
1003
+ if (box)
1004
+ boxes.set(target.key, box);
1005
+ }
1006
+ context.fileLayout(boxes, !resizedFreeFrame);
1007
+ }
1008
+ if (component.root.layout.kind === "absolute") {
1009
+ // A nested instance layer of the component that this instance swaps (by an override or a property value) to a component of another size.
1010
+ const swappedToOtherSize = [...component.layers].some(([key, { figma, node }]) => {
1011
+ if (figma.type !== "INSTANCE" || !("frame" in node) || boxes.has(layerPathKey([node.id])))
1012
+ return false;
1013
+ const shown = shownAt([key], figma, component, []);
1014
+ const own = context.component(shownSymbol(figma) ?? "");
1015
+ if (shown === undefined || shown === INSIDE_LEFT_OUT || shown === own)
1016
+ return false;
1017
+ // A layer resized away from its own component's size keeps its size when swapped.
1018
+ if (own !== undefined && (Math.abs(own.root.frame.width - node.frame.width) > 0.01 || Math.abs(own.root.frame.height - node.frame.height) > 0.01))
1019
+ return false;
1020
+ return Math.abs(shown.root.frame.width - node.frame.width) > 0.01 || Math.abs(shown.root.frame.height - node.frame.height) > 0.01;
1021
+ });
1022
+ if (constrainedOtherThanFigma(instance, component, self, context.nodes, swappedToOtherSize, context.fileLayout ? boxes : undefined)) {
1023
+ context.report("approximated", "the layers of a resized instance follow their constraints to sizes or positions other than the ones Figma laid out for it");
1024
+ }
1025
+ }
1026
+ const modeOverrides = new Map();
1027
+ for (const { keys, entry, at, gathered } of targets) {
1028
+ const { target } = gathered;
1029
+ const isInstance = target.layer.figma.type === "INSTANCE";
1030
+ for (const [name, value] of Object.entries(entry)) {
1031
+ if (BOOKKEEPING_FIELDS.has(name) || name === "exportSettings" || (name === "overriddenSymbolID" && isInstance))
1032
+ continue;
1033
+ if (HANDOFF_OVERRIDE_FIELDS.has(name)) {
1034
+ if (activeHandoffOverride(value))
1035
+ context.leftOutField(name);
1036
+ continue;
1037
+ }
1038
+ // Figma's record of the variable bindings this override set, which `variableConsumptionMap` beside it holds too.
1039
+ if (name === "parameterConsumptionMap" && entry["variableConsumptionMap"] !== undefined) {
1040
+ const extras = parameterMapExtras(value, entry["variableConsumptionMap"]);
1041
+ if (extras.length > 0)
1042
+ context.report("property-left-out", `an override's parameterConsumptionMap binds what its variableConsumptionMap does not, left out: ${extras.join(", ")}`);
1043
+ continue;
1044
+ }
1045
+ if (name === "componentPropAssignments" && isInstance) {
1046
+ const shown = shownAt(keys, target.layer.figma, target.component, target.through);
1047
+ if (shown === INSIDE_LEFT_OUT)
1048
+ insideLeftOut.add(entry);
1049
+ if (shown === undefined || shown === INSIDE_LEFT_OUT)
1050
+ continue;
1051
+ const values = assignedPropertyValues(field(entry, name, "list", at), shown.properties, shown.variantDefs, componentIdOf, leftOutValue(shown, target.key), at, context.report, captureLinks(shown, target.key));
1052
+ if (Object.keys(values).length > 0)
1053
+ gathered.override["propertyValues"] = { ...gathered.override["propertyValues"], ...values };
1054
+ }
1055
+ else if (name === "variableModeBySetMap" && (target.through.length === 0 || context.fileOverride)) {
1056
+ // The instance's modes on a layer of the component reach the bound font styles under it; Taco keeps no other part.
1057
+ modeOverrides.set(target.layer.figma.id, value);
1058
+ if (!context.fileOverride)
1059
+ context.leftOutField(name);
1060
+ }
1061
+ else if ((FRAME_FIELDS.has(name) || Object.hasOwn(PADDING_FIELDS, name)) && (target.layer.node.type === "frame" || isInstance)) {
1062
+ const shown = isInstance ? shownAt(keys, target.layer.figma, target.component, target.through) : undefined;
1063
+ if (shown === INSIDE_LEFT_OUT)
1064
+ insideLeftOut.add(entry);
1065
+ else if (isInstance && shown === undefined)
1066
+ context.leftOutField(name);
1067
+ else {
1068
+ const { figma } = target.layer;
1069
+ const under = (inner) => layerPathKey([...parseLayerPath(inner), shown.root.id]);
1070
+ const key = shown === undefined ? target.key : under(target.key);
1071
+ gathered.frame ??= {
1072
+ fields: {}, at: overrideAt(key), key, from: shown === undefined || figma.change["stackMode"] !== undefined ? figma : shown.symbol,
1073
+ holders: shown === undefined ? target.through
1074
+ : [...target.through.map(({ instance, inner }) => ({ instance, inner: under(inner) })), { instance: target.layer.node, inner: layerPathKey([shown.root.id]) }],
1075
+ };
1076
+ if (Object.hasOwn(PADDING_FIELDS, name)) {
1077
+ const sides = PADDING_FIELDS[name];
1078
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
1079
+ context.leftOutField(name);
1080
+ else
1081
+ (gathered.frame.padding ??= []).push({ name, value, sides: sides.filter(side => sides.length === 1 || !PADDING_FIELDS_OF_SIDE[side].some(key => key in entry)) });
1082
+ }
1083
+ else
1084
+ gathered.frame.fields[name] = value;
1085
+ }
1086
+ }
1087
+ else if (name === "name") {
1088
+ // A rename the instance makes; one that gives back the component layer's name, or no name, is no change.
1089
+ const renamed = field(entry, name, "string", at);
1090
+ if (renamed !== undefined && renamed !== "" && renamed !== target.layer.node.name)
1091
+ gathered.override["name"] = renamed;
1092
+ else
1093
+ delete gathered.override["name"];
1094
+ }
1095
+ else if (context.fileOverride && (name === "cornerRadius" || name === "rectangleCornerRadiiIndependent" || /^rectangle(Top|Bottom)(Left|Right)CornerRadius$/.test(name))) {
1096
+ // The native override supports radii directly. fileOverride has recorded the authored values.
1097
+ continue;
1098
+ }
1099
+ else if (CONVERTED_FIELDS.has(name) || name === "variableConsumptionMap") {
1100
+ gathered.fields[name] = value;
1101
+ // A style the override names but the message lacks is reported as on a text layer; Figma's detach id is no style.
1102
+ if (name === "styleIdForText" && !isDetachedStyle(value) && !context.hasTextStyle(value)) {
1103
+ context.report("approximated", "the text's Figma text style is not in the message; its values are kept as direct formatting");
1104
+ }
1105
+ // `convertAlone` reports nothing, so a style the override names but the message lacks is reported here.
1106
+ const backed = STYLE_REFERENCE_FIELDS.get(name);
1107
+ if (backed !== undefined)
1108
+ styleBackedList({ [name]: value }, backed, context.styleList, at, context.report);
1109
+ }
1110
+ else {
1111
+ context.leftOutField(name);
1112
+ }
1113
+ }
1114
+ }
1115
+ // A text layer whose font style or line height is bound takes the variable's value in the component's modes, so it is
1116
+ // read again in the modes this instance shows it in, which may give another value; so is a layer with a gradient
1117
+ // whose stops are bound (`bindsGradientStop`).
1118
+ const readsModes = (layer) => layer.node.type === "text" && (bindsFontStyle(layer.figma) || context.bindsLineHeight(layer.figma))
1119
+ || bindsGradientStop(layer.figma);
1120
+ for (const [key, layer] of component.layers) {
1121
+ if (!readsModes(layer))
1122
+ continue;
1123
+ const target = resolve([key]);
1124
+ if (target !== undefined && target !== INSIDE_LEFT_OUT && !("flattenedInto" in target) && !pending.has(target.key))
1125
+ pending.set(target.key, { target, fields: {}, override: overrideAt(target.key) });
1126
+ }
1127
+ // Figma draws an instance's text from the layout it stored for that instance, and keeps that layout when a text style
1128
+ // the text uses changes later, while the component is laid out again with the style's new line height. A text whose
1129
+ // lines this instance stores at one line height other than the component's keeps it, unless an override sets its own.
1130
+ for (const [index, entry] of (field(instance.change, "derivedSymbolData", "list", where) ?? []).entries()) {
1131
+ if (!isObject(entry))
1132
+ continue;
1133
+ const at = `${where} derivedSymbolData[${String(index)}]`;
1134
+ const stored = storedLineHeight(entry, at);
1135
+ if (stored === undefined)
1136
+ continue;
1137
+ const path = field(entry, "guidPath", "object", at);
1138
+ const keys = (path === undefined ? [] : field(path, "guids", "list", `${at}.guidPath`) ?? []).map((guid) => guidText(guid, `${at}.guidPath`));
1139
+ const target = keys.length === 0 ? undefined : resolve(keys);
1140
+ if (target === undefined || target === INSIDE_LEFT_OUT || "flattenedInto" in target || target.layer.node.type !== "text")
1141
+ continue;
1142
+ const own = storedLineHeight(target.layer.figma.change, `node ${target.layer.figma.id}`);
1143
+ if (own === undefined || Math.abs(stored - own) <= 0.01)
1144
+ continue;
1145
+ const pathText = keys.join("/");
1146
+ if (entries.some((set) => set.keys.join("/") === pathText && LINE_HEIGHT_SETTERS.some((name) => Object.hasOwn(set.entry, name))))
1147
+ continue;
1148
+ let gathered = pending.get(target.key);
1149
+ if (gathered === undefined)
1150
+ pending.set(target.key, gathered = { target, fields: {}, override: overrideAt(target.key) });
1151
+ gathered.fields[KEPT_LINE_HEIGHT_FIELD] = stored;
1152
+ context.report("approximated", "instance keeps Figma's stored line height from before its text style changed");
1153
+ }
1154
+ const heldSizing = new Map();
1155
+ for (const { target, fields, override, frame } of pending.values()) {
1156
+ if (frame !== undefined) {
1157
+ const base = context.convertAlone(frame.from);
1158
+ const next = context.convertAlone(frame.from, frame.fields);
1159
+ if (base?.type === "frame" && next?.type === "frame") {
1160
+ Object.assign(frame.at, frameOverrides(base, next, frame.fields));
1161
+ // Resolve padding after stackMode, even when separate entries enable the stack and pad it.
1162
+ for (const { name, sides, value } of frame.padding ?? []) {
1163
+ if (next.layout.kind === "absolute")
1164
+ context.leftOutField(name);
1165
+ else {
1166
+ const padding = (frame.at.padding ??= {});
1167
+ for (const side of sides)
1168
+ padding[side] = value;
1169
+ }
1170
+ }
1171
+ if ("cornerSmoothing" in frame.fields)
1172
+ frame.at.cornerSmoothing = next.style?.cornerSmoothing ?? 0;
1173
+ if ("frameMaskDisabled" in frame.fields)
1174
+ frame.at.clipContent = !!next.clipContent;
1175
+ }
1176
+ const changed = base === null || next === null ? undefined : sizingBetween(base, next, frame.fields);
1177
+ if (changed?.sizing !== undefined)
1178
+ frame.at["sizing"] = changed.sizing;
1179
+ if (changed?.sizing !== undefined && frame.holders.length > 0)
1180
+ heldSizing.set(frame.key, { axes: changed.same, holders: frame.holders });
1181
+ }
1182
+ const { figma } = target.layer;
1183
+ const direct = target.through.length === 0;
1184
+ if (Object.keys(fields).length === 0 && !(direct && readsModes(target.layer)))
1185
+ continue;
1186
+ const { variableConsumptionMap: ownMap, ...plain } = fields;
1187
+ if (OPEN_TYPE_TOGGLES.some(name => name in plain))
1188
+ Object.assign(plain, inheritOpenTypeToggles(figma.change, plain));
1189
+ // A locally authored paint or effect list replaces the main's style reference as well as its list.
1190
+ if (context.fileOverride)
1191
+ for (const [ref, list] of STYLE_REFERENCE_FIELDS)
1192
+ if (list in plain && !(ref in plain))
1193
+ plain[ref] = undefined;
1194
+ const shownBy = direct ? { instance, symbol: component.symbol, modes: modeOverrides } : undefined;
1195
+ const base = context.convertAlone(figma);
1196
+ // A text's line height is converted from its variable, so the bindings the override supplies or replaces go in too.
1197
+ const textBindings = ownMap !== undefined && target.layer.node.type === "text"
1198
+ && (bindsField({ variableConsumptionMap: ownMap }, "LINE_HEIGHT") || bindsField({ variableConsumptionMap: ownMap }, "FONT_SIZE"));
1199
+ const converted = textBindings ? { ...plain, variableConsumptionMap: withBindingEntries(figma.change["variableConsumptionMap"], ownMap) } : plain;
1200
+ // Only a layer that reads its instance's modes converts once per instance; the rest share one conversion.
1201
+ const next = context.convertAlone(figma, converted, readsModes(target.layer) || textBindings ? shownBy : undefined);
1202
+ if (base === null || next === null) {
1203
+ if (Object.keys(fields).length > 0)
1204
+ context.report("property-left-out", "an override of a layer that cannot be converted on its own is left out");
1205
+ continue;
1206
+ }
1207
+ // A cap Taco has no match for converts as flat on both sides, so compare the raw values.
1208
+ const cap = plain["strokeCap"];
1209
+ if (typeof cap === "string" && !Object.hasOwn(STROKE_CAPS, cap) && cap !== (figma.change["strokeCap"] ?? "NONE")) {
1210
+ context.report("property-left-out", `an override of a layer's stroke cap to ${cap} is left out: Taco has no such cap`);
1211
+ }
1212
+ // The bindings the override makes: a variable it binds, and `null` for a component binding of a field it sets plainly.
1213
+ const unbound = withOverrides(figma.change, plain);
1214
+ const nextFigma = { ...figma, change: ownMap === undefined ? unbound : { ...unbound, variableConsumptionMap: withBindingEntries(unbound["variableConsumptionMap"], ownMap) } };
1215
+ const before = context.bindingsOf(base, figma);
1216
+ const after = context.bindingsOf(next, nextFigma, shownBy);
1217
+ // Between the bound layers, so that a font style the override binds, or this instance's modes give, reaches the text.
1218
+ Object.assign(override, overrideBetween(before.layer, after.layer, context.report));
1219
+ const bindings = {};
1220
+ // A binding of a field the override sets is dropped by the model, so it is written even where it does not change.
1221
+ const dropped = bindingsDroppedBy(override);
1222
+ for (const property of new Set([...Object.keys(before.bindings), ...Object.keys(after.bindings)])) {
1223
+ if (dropped.has(property) || before.bindings[property] !== after.bindings[property])
1224
+ bindings[property] = after.bindings[property] ?? null;
1225
+ }
1226
+ if (Object.keys(bindings).length > 0)
1227
+ override["variableBindings"] = bindings;
1228
+ if (after.leftOut !== undefined && after.leftOut !== before.leftOut)
1229
+ context.report("property-left-out", after.leftOut);
1230
+ // A font style the override binds, or this instance's modes give, is fixed here, so its approximation is reported here.
1231
+ if (after.approximated !== undefined && after.approximated !== before.approximated)
1232
+ context.report("approximated", after.approximated);
1233
+ }
1234
+ // Slots, after the other overrides, as the content frame's own paints replace the slot frame's.
1235
+ const slots = {};
1236
+ const filledSlots = [];
1237
+ // The size a `symbolOverrides` entry at `keys` gives its layer, the last one winning.
1238
+ const overriddenSize = (keys) => {
1239
+ let found;
1240
+ for (const { keys: at, entry } of entries) {
1241
+ const size = isObject(entry["size"]) ? entry["size"] : undefined;
1242
+ if (size === undefined || at.length !== keys.length || at.some((key, i) => key !== keys[i]))
1243
+ continue;
1244
+ found = { ...(typeof size["x"] === "number" ? { width: size["x"] } : {}), ...(typeof size["y"] === "number" ? { height: size["y"] } : {}) };
1245
+ }
1246
+ return found;
1247
+ };
1248
+ // The property values this instance gives its component, read here for the slot frames they show or hide.
1249
+ const propertyValues = assignedPropertyValues(field(instance.change, "componentPropAssignments", "list", where), component.properties, component.variantDefs, componentIdOf, leftOutValue(component, ""), where, context.report, captureLinks(component, ""));
1250
+ for (const { shown, path, id, text, data } of assignedLinks.values()) {
1251
+ const table = new Map();
1252
+ for (const row of data["styleOverrideTable"]) {
1253
+ if (isObject(row) && typeof row["styleID"] === "number" && row["styleID"] !== 0 && Object.hasOwn(row, "hyperlink"))
1254
+ table.set(row["styleID"], hyperlinkOf(row["hyperlink"], context.report));
1255
+ }
1256
+ const ids = field(data, "characterStyleIDs", "list", where) ?? [];
1257
+ const prefix = path ? parseLayerPath(path) : [];
1258
+ for (const { figma, node } of shown.layers.values()) {
1259
+ if (node.type !== "text")
1260
+ continue;
1261
+ const ref = field(figma.change, "componentPropRefs", "list", where)?.findLast(ref => isObject(ref) && ref["componentPropNodeField"] === "TEXT_DATA" && ref["defID"] !== undefined && ref["isDeleted"] !== true);
1262
+ if (!isObject(ref) || propertyByFigmaId(shown.properties, guidText(ref["defID"], where))?.definition.id !== id)
1263
+ continue;
1264
+ const key = layerPathKey([...prefix, node.id]);
1265
+ const at = overrideAt(key), fields = pending.get(key)?.fields;
1266
+ // A paint override can produce full paragraphs too. Use their formatting for the
1267
+ // assignment unless the occurrence actually overrode its text body or links.
1268
+ if (at["characters"] !== undefined || (at["paragraphs"] !== undefined &&
1269
+ (fields?.["textData"] !== undefined || fields?.["hyperlink"] !== undefined)))
1270
+ continue;
1271
+ const source = at["paragraphs"];
1272
+ let i = 0, applied = false;
1273
+ const paragraphs = paragraphsFromCharacters(text, source ?? node.paragraphs).map(paragraph => {
1274
+ const runs = paragraph.runs.flatMap(run => {
1275
+ if (!run.text)
1276
+ return [run];
1277
+ const { hyperlink: inherited, ...style } = run;
1278
+ const parts = [];
1279
+ for (const char of run.text) {
1280
+ const raw = ids[i++], override = typeof raw === "number" && table.has(raw);
1281
+ const hyperlink = override ? table.get(raw) : inherited;
1282
+ const last = parts.at(-1);
1283
+ if (last && last.hyperlink === hyperlink)
1284
+ last.text += char;
1285
+ else
1286
+ parts.push({ ...style, text: char, ...(hyperlink !== undefined && { hyperlink }) });
1287
+ applied ||= override;
1288
+ }
1289
+ return parts;
1290
+ });
1291
+ ++i; // The paragraph break also consumes a Figma character style ID.
1292
+ return { ...paragraph, runs };
1293
+ });
1294
+ if (applied)
1295
+ at["paragraphs"] = paragraphs;
1296
+ }
1297
+ }
1298
+ // Whether a frame keeps its size along `axis` when its parent is resized: only Left and Right, Top and Bottom, or Scale stretch it.
1299
+ const stretches = (node, axis) => {
1300
+ const constraint = "constraints" in node ? node.constraints?.[axis === "width" ? "horizontal" : "vertical"] : undefined;
1301
+ return constraint === "left-right" || constraint === "top-bottom" || constraint === "scale";
1302
+ };
1303
+ const differs = (a, b) => a !== undefined && Math.abs(a - b) > LENGTH_TOLERANCE;
1304
+ /**
1305
+ * Whether the layer `start` of `inComponent`, shown at Figma keys `prefix` in this instance, changes size along `axis`
1306
+ * because something above it does: every frame from it up to the component root stretches, and the instance showing the
1307
+ * component is resized; or a frame on the way has a size override. A nested instance is resized by its placement or
1308
+ * an override, or, when it stretches, by what is above it in turn; a fixed one stops the chain.
1309
+ */
1310
+ const changesSize = (start, inComponent, prefix, axis) => {
1311
+ const byFigmaId = layersByFigmaId(inComponent);
1312
+ for (let at = start; at !== undefined && at.figma !== inComponent.symbol; at = at.figma.parentId === undefined ? undefined : byFigmaId.get(at.figma.parentId)) {
1313
+ // A size override counts only where it gives the frame another size than in its component.
1314
+ if (at !== start && "frame" in at.node && differs(overriddenSize([...prefix, overrideKeyOf(at.figma)])?.[axis], at.node.frame[axis]))
1315
+ return true;
1316
+ if (!stretches(at.node, axis))
1317
+ return false;
1318
+ }
1319
+ const root = inComponent.root.frame[axis];
1320
+ if (prefix.length === 0)
1321
+ return differs(self.frame[axis], root);
1322
+ const target = resolve(prefix);
1323
+ if (target === undefined || target === INSIDE_LEFT_OUT || "flattenedInto" in target)
1324
+ return true;
1325
+ const placed = target.layer.node;
1326
+ if (differs(placed.frame?.[axis], root) || differs(overriddenSize(prefix)?.[axis], root))
1327
+ return true;
1328
+ return changesSize(target.layer, target.component, prefix.slice(0, -1), axis);
1329
+ };
1330
+ for (const { keys, defId, host, content } of context.slotFills ?? []) {
1331
+ let inComponent = component;
1332
+ let pathIds = [];
1333
+ let values = propertyValues;
1334
+ if (keys.length > 0) {
1335
+ const target = resolve(keys);
1336
+ if (target === INSIDE_LEFT_OUT)
1337
+ inComponent = INSIDE_LEFT_OUT;
1338
+ else if (target === undefined || "flattenedInto" in target || target.layer.figma.type !== "INSTANCE")
1339
+ inComponent = undefined;
1340
+ else {
1341
+ inComponent = shownAt(keys, target.layer.figma, target.component, target.through);
1342
+ pathIds = parseLayerPath(target.key) ?? [];
1343
+ const nested = target.layer.node;
1344
+ values = { ...nested.propertyValues, ...overrides[target.key]?.["propertyValues"] };
1345
+ }
1346
+ }
1347
+ if (inComponent === undefined || inComponent === INSIDE_LEFT_OUT) {
1348
+ context.report("property-left-out", "the content placed in a slot of a nested instance that was not imported is left out");
1349
+ continue;
1350
+ }
1351
+ const property = propertyByFigmaId(inComponent.properties, defId)?.definition;
1352
+ // Every frame bound to the slot, in tree order. The resolver fills the first one shown: no condition leaves it out
1353
+ // (the import writes none) and it is visible after property bindings and overrides.
1354
+ const boundLayers = property?.kind !== "slot" ? []
1355
+ : [...inComponent.layers.values()].filter(({ node }) => node.type === "frame" && node.slot === property.id);
1356
+ const visibleIn = (layer, shownIn) => {
1357
+ const overridden = overrides[layerPathKey([...pathIds, layer.node.id])]?.["visible"];
1358
+ if (typeof overridden === "boolean")
1359
+ return overridden;
1360
+ const bound = layer.node.expressions?.visible;
1361
+ const by = bound === undefined ? undefined : shownIn.properties.find(({ definition }) => definition.kind === "boolean" && formatExpressionName(definition.name) === bound)?.definition;
1362
+ if (by?.kind === "boolean")
1363
+ return values[by.id] ?? by.defaultValue;
1364
+ return layer.node.visible;
1365
+ };
1366
+ const shownIn = inComponent;
1367
+ // Shown with every layer above it up to the component root, which the instance's own visibility stands for.
1368
+ const byFigmaId = layersByFigmaId(shownIn);
1369
+ const effectivelyVisible = (layer) => {
1370
+ for (let at = layer; at !== undefined && at.figma !== shownIn.symbol; at = at.figma.parentId === undefined ? undefined : byFigmaId.get(at.figma.parentId)) {
1371
+ if (!visibleIn(at, shownIn))
1372
+ return false;
1373
+ }
1374
+ return true;
1375
+ };
1376
+ const unconditioned = boundLayers.filter(({ node }) => node.condition === undefined);
1377
+ const slotLayer = unconditioned.find(effectivelyVisible) ?? unconditioned[0];
1378
+ if (property === undefined || slotLayer === undefined) {
1379
+ context.report("property-left-out", keys.length
1380
+ ? "a nested slot assignment has no imported slot declaration or bound frame"
1381
+ : "the content placed in a slot names no imported slot of the component; it is left out");
1382
+ continue;
1383
+ }
1384
+ const pathKey = layerPathKey(pathIds);
1385
+ const bySlot = (slots[pathKey] ??= {});
1386
+ if (bySlot[property.id] !== undefined) {
1387
+ context.report("property-left-out", "a second content placed in the same slot is left out");
1388
+ continue;
1389
+ }
1390
+ bySlot[property.id] = host.id;
1391
+ const slotFrame = slotLayer.node;
1392
+ const slotKey = layerPathKey([...pathIds, slotFrame.id]);
1393
+ const sizing = overrides[slotKey]?.["sizing"];
1394
+ const slotSize = overriddenSize([...keys, overrideKeyOf(slotLayer.figma)]);
1395
+ filledSlots.push({
1396
+ slotFrame, content, ...(slotSize === undefined ? {} : { size: slotSize }),
1397
+ // An axis the slot frame itself changes size on, by what is above it (`changesSize`), or that an override makes hug.
1398
+ skip: {
1399
+ width: sizing?.width === "hug" || (slotSize?.width === undefined && changesSize(slotLayer, shownIn, keys, "width")),
1400
+ height: sizing?.height === "hug" || (slotSize?.height === undefined && changesSize(slotLayer, shownIn, keys, "height")),
1401
+ },
1402
+ });
1403
+ // The host stands where the slot frame does; the cascade keeps its frame in step with the slot frame's.
1404
+ Object.assign(host, { frame: { ...slotFrame.frame }, rotation: 0, opacity: 1, visible: true });
1405
+ for (const name of ["style", "flipX", "flipY", "variableBindings", "resizing", "constraints", "absolute"])
1406
+ delete host[name];
1407
+ // The content frame's own paints, opacity, effects and name show on the slot frame. They go on every frame bound to the
1408
+ // slot, so they hold whichever of them shows the content.
1409
+ const next = context.convertAlone(content);
1410
+ const base = context.convertAlone(slotLayer.figma);
1411
+ if (base === null || next === null)
1412
+ continue;
1413
+ const before = context.bindingsOf(base, slotLayer.figma);
1414
+ const after = context.bindingsOf(next, content);
1415
+ for (const bound of boundLayers) {
1416
+ const boundBase = bound === slotLayer ? base : context.convertAlone(bound.figma);
1417
+ if (boundBase === null)
1418
+ continue;
1419
+ const at = overrideAt(layerPathKey([...pathIds, bound.node.id]));
1420
+ const baseStyle = styleOf(boundBase);
1421
+ const nextStyle = styleOf(next);
1422
+ for (const name of STYLE_OVERRIDES) {
1423
+ if (!same(baseStyle[name], nextStyle[name]))
1424
+ at[name] = nextStyle[name] ?? (name === "layerBlur" || name === "backgroundBlur" || name === "cornerSmoothing" ? 0 : []);
1425
+ }
1426
+ if (next.opacity !== boundBase.opacity)
1427
+ at["opacity"] = next.opacity;
1428
+ if (content.name !== "" && content.name !== bound.node.name)
1429
+ at["name"] = content.name;
1430
+ const boundBefore = bound === slotLayer ? before : context.bindingsOf(boundBase, bound.figma);
1431
+ // Only the bindings of the fields set here: the content frame's layout bindings are the slot frame's to keep.
1432
+ const bindings = {};
1433
+ const dropped = bindingsDroppedBy(at);
1434
+ for (const property of new Set([...Object.keys(boundBefore.bindings), ...Object.keys(after.bindings)])) {
1435
+ if (dropped.has(property))
1436
+ bindings[property] = after.bindings[property] ?? null;
1437
+ }
1438
+ if (Object.keys(bindings).length > 0)
1439
+ at["variableBindings"] = { ...at["variableBindings"], ...bindings };
1440
+ }
1441
+ // Slot content contributes children to the host, whose own layout arranges them.
1442
+ const layoutOf = (frame) => {
1443
+ if (frame.type !== "frame")
1444
+ return undefined;
1445
+ const { widthSizing: _width, heightSizing: _height, ...rest } = frame.layout;
1446
+ return rest;
1447
+ };
1448
+ const layoutBindings = (bound) => JSON.stringify(LAYOUT_BINDINGS.map((name) => bound[name] ?? null));
1449
+ if (!same(layoutOf(base), layoutOf(next)) || layoutBindings(before.bindings) !== layoutBindings(after.bindings)) {
1450
+ context.report("approximated", "a slot's content frame has another layout (direction, gap, padding or alignment) than its slot frame; the slot frame's layout is used");
1451
+ }
1452
+ }
1453
+ for (const _ of insideLeftOut)
1454
+ context.report("property-left-out", "an override inside a swap that was left out is left out too");
1455
+ const kept = Object.fromEntries(Object.entries(overrides).filter(([, value]) => Object.keys(value).length > 0));
1456
+ // Some instances store their own rows only on the override of the root.
1457
+ const exportSettings = instance.change["exportSettings"] === undefined ? exportSettingsOf(rootExports, context.report) : undefined;
1458
+ return {
1459
+ fields: {
1460
+ ...(exportSettings === undefined ? {} : { exportSettings }),
1461
+ ...(Object.keys(kept).length > 0 ? { overrides: kept } : {}),
1462
+ ...(Object.keys(propertyValues).length > 0 ? { propertyValues } : {}),
1463
+ ...(Object.keys(slots).length > 0 ? { slots } : {}),
1464
+ },
1465
+ swaps: swapsKept, pathSwaps,
1466
+ filledSlots,
1467
+ nested: new Map([...pending.values()].filter(({ target }) => target.through.length > 0).map(({ target }) => [target.key, target.through])),
1468
+ heldSizing,
1469
+ };
1470
+ }
1471
+ /** Whether a Figma layer binds its font style to a variable (`variableConsumptionMap` field `FONT_STYLE`). */
1472
+ function bindsFontStyle(figma) {
1473
+ return bindsField(figma.change, "FONT_STYLE");
1474
+ }
1475
+ /**
1476
+ * Whether a gradient among the layer's own fills or strokes binds a stop's colour to a variable (`stopsVar`). Taco
1477
+ * cannot bind a stop, so such a gradient takes the colours of the modes each instance shows it in, as an override.
1478
+ */
1479
+ function bindsGradientStop(figma) {
1480
+ const where = `node ${figma.id}`;
1481
+ return ["fillPaints", "strokePaints"].some((list) => (field(figma.change, list, "list", where) ?? [])
1482
+ .some((paint) => isObject(paint) && (field(paint, "stopsVar", "list", where) ?? []).some((stop) => isObject(stop) && stop["colorVar"] !== undefined)));
1483
+ }
1484
+ /** Whether Figma fields (a layer's, a text style's or a styled range's) bind `variableField` to a variable. */
1485
+ export function bindsField(fields, variableField) {
1486
+ const where = "variableConsumptionMap";
1487
+ return (field(field(fields, "variableConsumptionMap", "object", where) ?? {}, "entries", "list", where) ?? [])
1488
+ .some((entry) => isObject(entry) && entry["variableField"] === variableField);
1489
+ }
1490
+ /** The SYMBOL a Figma INSTANCE names (`symbolData.symbolID`), or `undefined`. */
1491
+ export function shownSymbol(instance) {
1492
+ const symbolData = field(instance.change, "symbolData", "object", `node ${instance.id}`);
1493
+ return symbolData?.["symbolID"] === undefined ? undefined : guidText(symbolData["symbolID"], `node ${instance.id} symbolData.symbolID`);
1494
+ }
1495
+ /** Every SYMBOL a node's change names: its instance's component, override swaps and instance swap values and defaults. */
1496
+ export function symbolsNamedBy(change) {
1497
+ const found = [];
1498
+ const guid = (value) => {
1499
+ if (isObject(value) && Number.isInteger(value["sessionID"]) && Number.isInteger(value["localID"]))
1500
+ found.push(`${String(value["sessionID"])}:${String(value["localID"])}`);
1501
+ };
1502
+ const symbolData = isObject(change["symbolData"]) ? change["symbolData"] : undefined;
1503
+ guid(symbolData?.["symbolID"]);
1504
+ const values = (list) => {
1505
+ if (!Array.isArray(list))
1506
+ return;
1507
+ for (const item of list) {
1508
+ if (!isObject(item))
1509
+ continue;
1510
+ if (isObject(item["value"]))
1511
+ guid(item["value"]["guidValue"]);
1512
+ // Newer files keep an instance swap value in `varValue.value.symbolIdValue.guid`.
1513
+ const held = isObject(item["varValue"]) && isObject(item["varValue"]["value"]) ? item["varValue"]["value"] : undefined;
1514
+ if (isObject(held?.["symbolIdValue"]))
1515
+ guid(held["symbolIdValue"]["guid"]);
1516
+ }
1517
+ };
1518
+ values(change["componentPropAssignments"]);
1519
+ for (const entry of Array.isArray(symbolData?.["symbolOverrides"]) ? symbolData["symbolOverrides"] : []) {
1520
+ if (!isObject(entry))
1521
+ continue;
1522
+ guid(entry["overriddenSymbolID"]);
1523
+ values(entry["componentPropAssignments"]);
1524
+ }
1525
+ for (const def of Array.isArray(change["componentPropDefs"]) ? change["componentPropDefs"] : []) {
1526
+ if (isObject(def) && isObject(def["initialValue"]))
1527
+ guid(def["initialValue"]["guidValue"]);
1528
+ }
1529
+ return found;
1530
+ }