@moondraft/import 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +34 -0
  3. package/README.md +36 -2
  4. package/SOURCE.md +169 -0
  5. package/dist/adapter/convert.d.ts +122 -0
  6. package/dist/adapter/convert.js +2302 -0
  7. package/dist/adapter/figma.d.ts +9 -0
  8. package/dist/adapter/figma.js +30 -0
  9. package/dist/adapter/file-components.d.ts +14 -0
  10. package/dist/adapter/file-components.js +262 -0
  11. package/dist/adapter/file-resources.d.ts +29 -0
  12. package/dist/adapter/file-resources.js +562 -0
  13. package/dist/adapter/index.d.ts +6 -0
  14. package/dist/adapter/index.js +9 -0
  15. package/dist/adapter/link.d.ts +45 -0
  16. package/dist/adapter/link.js +688 -0
  17. package/dist/adapter/payload.d.ts +31 -0
  18. package/dist/adapter/payload.js +78 -0
  19. package/dist/adapter/shapes.d.ts +31 -0
  20. package/dist/adapter/shapes.js +75 -0
  21. package/dist/adapter/variables.d.ts +44 -0
  22. package/dist/adapter/variables.js +103 -0
  23. package/dist/figma-file.d.ts +38 -0
  24. package/dist/figma-file.js +97 -0
  25. package/dist/figma-worker.d.ts +11 -0
  26. package/dist/figma-worker.js +12 -0
  27. package/dist/figma.d.ts +26 -0
  28. package/dist/figma.js +96 -0
  29. package/dist/index.d.ts +28 -0
  30. package/dist/index.js +49 -0
  31. package/dist/report.d.ts +15 -0
  32. package/dist/report.js +69 -0
  33. package/dist/svg.d.ts +33 -0
  34. package/dist/svg.js +44 -0
  35. package/dist/syntax.d.ts +8 -0
  36. package/dist/syntax.js +19 -0
  37. package/dist/taco/figma-import/clipboard.d.ts +25 -0
  38. package/dist/taco/figma-import/clipboard.js +87 -0
  39. package/dist/taco/figma-import/clipboardSize.d.ts +31 -0
  40. package/dist/taco/figma-import/clipboardSize.js +107 -0
  41. package/dist/taco/figma-import/container/compression.d.ts +9 -0
  42. package/dist/taco/figma-import/container/compression.js +174 -0
  43. package/dist/taco/figma-import/container/error.d.ts +15 -0
  44. package/dist/taco/figma-import/container/error.js +19 -0
  45. package/dist/taco/figma-import/container/kiwiContainer.d.ts +38 -0
  46. package/dist/taco/figma-import/container/kiwiContainer.js +61 -0
  47. package/dist/taco/figma-import/container/limits.d.ts +22 -0
  48. package/dist/taco/figma-import/container/limits.js +22 -0
  49. package/dist/taco/figma-import/container/zip.d.ts +14 -0
  50. package/dist/taco/figma-import/container/zip.js +154 -0
  51. package/dist/taco/figma-import/figFile.d.ts +34 -0
  52. package/dist/taco/figma-import/figFile.js +91 -0
  53. package/dist/taco/figma-import/figFileDocument.d.ts +25 -0
  54. package/dist/taco/figma-import/figFileDocument.js +100 -0
  55. package/dist/taco/figma-import/import/blobs.d.ts +10 -0
  56. package/dist/taco/figma-import/import/blobs.js +23 -0
  57. package/dist/taco/figma-import/import/carry.d.ts +11 -0
  58. package/dist/taco/figma-import/import/carry.js +33 -0
  59. package/dist/taco/figma-import/import/componentProps.d.ts +84 -0
  60. package/dist/taco/figma-import/import/componentProps.js +313 -0
  61. package/dist/taco/figma-import/import/componentSets.d.ts +83 -0
  62. package/dist/taco/figma-import/import/componentSets.js +647 -0
  63. package/dist/taco/figma-import/import/converters/effects.d.ts +31 -0
  64. package/dist/taco/figma-import/import/converters/effects.js +127 -0
  65. package/dist/taco/figma-import/import/converters/ellipse.d.ts +7 -0
  66. package/dist/taco/figma-import/import/converters/ellipse.js +54 -0
  67. package/dist/taco/figma-import/import/converters/frame.d.ts +21 -0
  68. package/dist/taco/figma-import/import/converters/frame.js +55 -0
  69. package/dist/taco/figma-import/import/converters/gradient.d.ts +72 -0
  70. package/dist/taco/figma-import/import/converters/gradient.js +106 -0
  71. package/dist/taco/figma-import/import/converters/group.d.ts +21 -0
  72. package/dist/taco/figma-import/import/converters/group.js +39 -0
  73. package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
  74. package/dist/taco/figma-import/import/converters/image.js +83 -0
  75. package/dist/taco/figma-import/import/converters/layout.d.ts +34 -0
  76. package/dist/taco/figma-import/import/converters/layout.js +168 -0
  77. package/dist/taco/figma-import/import/converters/line.d.ts +11 -0
  78. package/dist/taco/figma-import/import/converters/line.js +40 -0
  79. package/dist/taco/figma-import/import/converters/rectangle.d.ts +3 -0
  80. package/dist/taco/figma-import/import/converters/rectangle.js +11 -0
  81. package/dist/taco/figma-import/import/converters/section.d.ts +9 -0
  82. package/dist/taco/figma-import/import/converters/section.js +35 -0
  83. package/dist/taco/figma-import/import/converters/shared.d.ts +68 -0
  84. package/dist/taco/figma-import/import/converters/shared.js +362 -0
  85. package/dist/taco/figma-import/import/converters/text.d.ts +41 -0
  86. package/dist/taco/figma-import/import/converters/text.js +576 -0
  87. package/dist/taco/figma-import/import/converters/vector.d.ts +84 -0
  88. package/dist/taco/figma-import/import/converters/vector.js +468 -0
  89. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +98 -0
  90. package/dist/taco/figma-import/import/converters/vectorNetwork.js +385 -0
  91. package/dist/taco/figma-import/import/fields.d.ts +15 -0
  92. package/dist/taco/figma-import/import/fields.js +29 -0
  93. package/dist/taco/figma-import/import/instances.d.ts +163 -0
  94. package/dist/taco/figma-import/import/instances.js +1323 -0
  95. package/dist/taco/figma-import/import/nestingCycles.d.ts +86 -0
  96. package/dist/taco/figma-import/import/nestingCycles.js +488 -0
  97. package/dist/taco/figma-import/import/slots.d.ts +56 -0
  98. package/dist/taco/figma-import/import/slots.js +96 -0
  99. package/dist/taco/figma-import/import/styles.d.ts +46 -0
  100. package/dist/taco/figma-import/import/styles.js +42 -0
  101. package/dist/taco/figma-import/import/tree.d.ts +66 -0
  102. package/dist/taco/figma-import/import/tree.js +194 -0
  103. package/dist/taco/figma-import/import/types.d.ts +232 -0
  104. package/dist/taco/figma-import/import/types.js +33 -0
  105. package/dist/taco/figma-import/import/variables.d.ts +136 -0
  106. package/dist/taco/figma-import/import/variables.js +762 -0
  107. package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
  108. package/dist/taco/figma-import/import/variantTrees.js +480 -0
  109. package/dist/taco/figma-import/import/walk.d.ts +159 -0
  110. package/dist/taco/figma-import/import/walk.js +1297 -0
  111. package/dist/taco/figma-import/index.d.ts +22 -0
  112. package/dist/taco/figma-import/index.js +13 -0
  113. package/dist/taco/figma-import/kiwi/byteReader.d.ts +37 -0
  114. package/dist/taco/figma-import/kiwi/byteReader.js +151 -0
  115. package/dist/taco/figma-import/kiwi/error.d.ts +14 -0
  116. package/dist/taco/figma-import/kiwi/error.js +29 -0
  117. package/dist/taco/figma-import/kiwi/limits.d.ts +18 -0
  118. package/dist/taco/figma-import/kiwi/limits.js +18 -0
  119. package/dist/taco/figma-import/kiwi/message.d.ts +10 -0
  120. package/dist/taco/figma-import/kiwi/message.js +145 -0
  121. package/dist/taco/figma-import/kiwi/schema.d.ts +42 -0
  122. package/dist/taco/figma-import/kiwi/schema.js +206 -0
  123. package/dist/taco/figma-import/kiwi/types.d.ts +46 -0
  124. package/dist/taco/figma-import/kiwi/types.js +18 -0
  125. package/dist/taco/model/agent-hidden-fields.d.ts +20 -0
  126. package/dist/taco/model/agent-hidden-fields.js +29 -0
  127. package/dist/taco/model/asset-users.d.ts +23 -0
  128. package/dist/taco/model/asset-users.js +128 -0
  129. package/dist/taco/model/auto-layout-lines.d.ts +32 -0
  130. package/dist/taco/model/auto-layout-lines.js +70 -0
  131. package/dist/taco/model/codec.d.ts +444 -0
  132. package/dist/taco/model/codec.js +5635 -0
  133. package/dist/taco/model/color.d.ts +11 -0
  134. package/dist/taco/model/color.js +61 -0
  135. package/dist/taco/model/comment-operations.d.ts +102 -0
  136. package/dist/taco/model/comment-operations.js +227 -0
  137. package/dist/taco/model/component-evaluation.d.ts +94 -0
  138. package/dist/taco/model/component-evaluation.js +548 -0
  139. package/dist/taco/model/component-expressions.d.ts +242 -0
  140. package/dist/taco/model/component-expressions.js +1082 -0
  141. package/dist/taco/model/component-properties.d.ts +111 -0
  142. package/dist/taco/model/component-properties.js +339 -0
  143. package/dist/taco/model/component-samples.d.ts +83 -0
  144. package/dist/taco/model/component-samples.js +290 -0
  145. package/dist/taco/model/component-validity.d.ts +85 -0
  146. package/dist/taco/model/component-validity.js +397 -0
  147. package/dist/taco/model/components.d.ts +155 -0
  148. package/dist/taco/model/components.js +505 -0
  149. package/dist/taco/model/connector-ends.d.ts +20 -0
  150. package/dist/taco/model/connector-ends.js +188 -0
  151. package/dist/taco/model/connector-geometry.d.ts +74 -0
  152. package/dist/taco/model/connector-geometry.js +293 -0
  153. package/dist/taco/model/corner-radii.d.ts +26 -0
  154. package/dist/taco/model/corner-radii.js +47 -0
  155. package/dist/taco/model/derivations.d.ts +81 -0
  156. package/dist/taco/model/derivations.js +151 -0
  157. package/dist/taco/model/export-settings.d.ts +53 -0
  158. package/dist/taco/model/export-settings.js +156 -0
  159. package/dist/taco/model/expressions/ast.d.ts +153 -0
  160. package/dist/taco/model/expressions/ast.js +6 -0
  161. package/dist/taco/model/expressions/cache.d.ts +23 -0
  162. package/dist/taco/model/expressions/cache.js +43 -0
  163. package/dist/taco/model/expressions/check.d.ts +72 -0
  164. package/dist/taco/model/expressions/check.js +517 -0
  165. package/dist/taco/model/expressions/completion.d.ts +61 -0
  166. package/dist/taco/model/expressions/completion.js +421 -0
  167. package/dist/taco/model/expressions/evaluate.d.ts +32 -0
  168. package/dist/taco/model/expressions/evaluate.js +519 -0
  169. package/dist/taco/model/expressions/forms.d.ts +84 -0
  170. package/dist/taco/model/expressions/forms.js +200 -0
  171. package/dist/taco/model/expressions/index.d.ts +14 -0
  172. package/dist/taco/model/expressions/index.js +17 -0
  173. package/dist/taco/model/expressions/lexer.d.ts +42 -0
  174. package/dist/taco/model/expressions/lexer.js +213 -0
  175. package/dist/taco/model/expressions/library.d.ts +33 -0
  176. package/dist/taco/model/expressions/library.js +117 -0
  177. package/dist/taco/model/expressions/names.d.ts +43 -0
  178. package/dist/taco/model/expressions/names.js +99 -0
  179. package/dist/taco/model/expressions/parser.d.ts +15 -0
  180. package/dist/taco/model/expressions/parser.js +438 -0
  181. package/dist/taco/model/expressions/rename.d.ts +34 -0
  182. package/dist/taco/model/expressions/rename.js +46 -0
  183. package/dist/taco/model/expressions/source.d.ts +15 -0
  184. package/dist/taco/model/expressions/source.js +161 -0
  185. package/dist/taco/model/expressions/types.d.ts +119 -0
  186. package/dist/taco/model/expressions/types.js +102 -0
  187. package/dist/taco/model/expressions/values.d.ts +97 -0
  188. package/dist/taco/model/expressions/values.js +160 -0
  189. package/dist/taco/model/geometry-limits.d.ts +16 -0
  190. package/dist/taco/model/geometry-limits.js +67 -0
  191. package/dist/taco/model/geometry.d.ts +47 -0
  192. package/dist/taco/model/geometry.js +193 -0
  193. package/dist/taco/model/group-bounds.d.ts +38 -0
  194. package/dist/taco/model/group-bounds.js +144 -0
  195. package/dist/taco/model/id-table.d.ts +37 -0
  196. package/dist/taco/model/id-table.js +80 -0
  197. package/dist/taco/model/index.d.ts +25 -0
  198. package/dist/taco/model/index.js +27 -0
  199. package/dist/taco/model/instance-resolver.d.ts +372 -0
  200. package/dist/taco/model/instance-resolver.js +1748 -0
  201. package/dist/taco/model/layer-syntax.d.ts +340 -0
  202. package/dist/taco/model/layer-syntax.js +3506 -0
  203. package/dist/taco/model/layout/constraints.d.ts +84 -0
  204. package/dist/taco/model/layout/constraints.js +445 -0
  205. package/dist/taco/model/layout/frame-layout.d.ts +46 -0
  206. package/dist/taco/model/layout/frame-layout.js +618 -0
  207. package/dist/taco/model/layout/node-sizing.d.ts +163 -0
  208. package/dist/taco/model/layout/node-sizing.js +486 -0
  209. package/dist/taco/model/legacy-connector-caps.d.ts +15 -0
  210. package/dist/taco/model/legacy-connector-caps.js +70 -0
  211. package/dist/taco/model/linear-call.d.ts +48 -0
  212. package/dist/taco/model/linear-call.js +58 -0
  213. package/dist/taco/model/new-nodes.d.ts +145 -0
  214. package/dist/taco/model/new-nodes.js +277 -0
  215. package/dist/taco/model/node-builder.d.ts +449 -0
  216. package/dist/taco/model/node-builder.js +2294 -0
  217. package/dist/taco/model/node-table-watch.d.ts +36 -0
  218. package/dist/taco/model/node-table-watch.js +63 -0
  219. package/dist/taco/model/node-transform.d.ts +39 -0
  220. package/dist/taco/model/node-transform.js +79 -0
  221. package/dist/taco/model/node-users-index.d.ts +10 -0
  222. package/dist/taco/model/node-users-index.js +82 -0
  223. package/dist/taco/model/operation-references.d.ts +80 -0
  224. package/dist/taco/model/operation-references.js +399 -0
  225. package/dist/taco/model/operations.d.ts +610 -0
  226. package/dist/taco/model/operations.js +2882 -0
  227. package/dist/taco/model/overlay-table.d.ts +71 -0
  228. package/dist/taco/model/overlay-table.js +171 -0
  229. package/dist/taco/model/override-remap.d.ts +69 -0
  230. package/dist/taco/model/override-remap.js +230 -0
  231. package/dist/taco/model/parent-table.d.ts +53 -0
  232. package/dist/taco/model/parent-table.js +193 -0
  233. package/dist/taco/model/problem-collector.d.ts +27 -0
  234. package/dist/taco/model/problem-collector.js +101 -0
  235. package/dist/taco/model/sha256.d.ts +10 -0
  236. package/dist/taco/model/sha256.js +74 -0
  237. package/dist/taco/model/shape-geometry.d.ts +96 -0
  238. package/dist/taco/model/shape-geometry.js +368 -0
  239. package/dist/taco/model/shared-node-table.d.ts +97 -0
  240. package/dist/taco/model/shared-node-table.js +546 -0
  241. package/dist/taco/model/slots.d.ts +113 -0
  242. package/dist/taco/model/slots.js +281 -0
  243. package/dist/taco/model/stroke-settings.d.ts +37 -0
  244. package/dist/taco/model/stroke-settings.js +90 -0
  245. package/dist/taco/model/svg-path-import.d.ts +89 -0
  246. package/dist/taco/model/svg-path-import.js +219 -0
  247. package/dist/taco/model/text-measurement.d.ts +142 -0
  248. package/dist/taco/model/text-measurement.js +846 -0
  249. package/dist/taco/model/text-reads.d.ts +66 -0
  250. package/dist/taco/model/text-reads.js +128 -0
  251. package/dist/taco/model/text-sizer.d.ts +358 -0
  252. package/dist/taco/model/text-sizer.js +996 -0
  253. package/dist/taco/model/theme-users.d.ts +59 -0
  254. package/dist/taco/model/theme-users.js +312 -0
  255. package/dist/taco/model/thumbnail.d.ts +15 -0
  256. package/dist/taco/model/thumbnail.js +34 -0
  257. package/dist/taco/model/types.d.ts +2347 -0
  258. package/dist/taco/model/types.js +366 -0
  259. package/dist/taco/model/unknown-property.d.ts +5 -0
  260. package/dist/taco/model/unknown-property.js +7 -0
  261. package/dist/taco/model/validated-documents.d.ts +22 -0
  262. package/dist/taco/model/validated-documents.js +22 -0
  263. package/dist/taco/model/variable-modes.d.ts +61 -0
  264. package/dist/taco/model/variable-modes.js +438 -0
  265. package/dist/taco/model/variable-references.d.ts +54 -0
  266. package/dist/taco/model/variable-references.js +183 -0
  267. package/dist/taco/model/variables.d.ts +24 -0
  268. package/dist/taco/model/variables.js +151 -0
  269. package/dist/taco/model/vector-network.d.ts +34 -0
  270. package/dist/taco/model/vector-network.js +411 -0
  271. package/dist/taco/svg-import/import-svg.d.ts +36 -0
  272. package/dist/taco/svg-import/import-svg.js +729 -0
  273. package/dist/taco/svg-import/index.d.ts +3 -0
  274. package/dist/taco/svg-import/index.js +3 -0
  275. package/dist/taco/svg-import/limits/limits.d.ts +79 -0
  276. package/dist/taco/svg-import/limits/limits.js +160 -0
  277. package/dist/taco/svg-import/paint/gradients.d.ts +64 -0
  278. package/dist/taco/svg-import/paint/gradients.js +429 -0
  279. package/dist/taco/svg-import/paint/paint.d.ts +32 -0
  280. package/dist/taco/svg-import/paint/paint.js +162 -0
  281. package/dist/taco/svg-import/paths/paths.d.ts +58 -0
  282. package/dist/taco/svg-import/paths/paths.js +205 -0
  283. package/dist/taco/svg-import/public-types.d.ts +279 -0
  284. package/dist/taco/svg-import/public-types.js +56 -0
  285. package/dist/taco/svg-import/report/report.d.ts +44 -0
  286. package/dist/taco/svg-import/report/report.js +79 -0
  287. package/dist/taco/svg-import/reuse/reuse.d.ts +99 -0
  288. package/dist/taco/svg-import/reuse/reuse.js +840 -0
  289. package/dist/taco/svg-import/shapes/shapes.d.ts +35 -0
  290. package/dist/taco/svg-import/shapes/shapes.js +386 -0
  291. package/dist/taco/svg-import/structure/effects.d.ts +26 -0
  292. package/dist/taco/svg-import/structure/effects.js +618 -0
  293. package/dist/taco/svg-import/structure/image.d.ts +24 -0
  294. package/dist/taco/svg-import/structure/image.js +495 -0
  295. package/dist/taco/svg-import/structure/walk.d.ts +85 -0
  296. package/dist/taco/svg-import/structure/walk.js +544 -0
  297. package/dist/taco/svg-import/style/color.d.ts +40 -0
  298. package/dist/taco/svg-import/style/color.js +275 -0
  299. package/dist/taco/svg-import/style/computed.d.ts +214 -0
  300. package/dist/taco/svg-import/style/computed.js +1534 -0
  301. package/dist/taco/svg-import/style/css.d.ts +127 -0
  302. package/dist/taco/svg-import/style/css.js +541 -0
  303. package/dist/taco/svg-import/style/media.d.ts +25 -0
  304. package/dist/taco/svg-import/style/media.js +307 -0
  305. package/dist/taco/svg-import/style/properties.d.ts +43 -0
  306. package/dist/taco/svg-import/style/properties.js +135 -0
  307. package/dist/taco/svg-import/style/selector-reach.d.ts +30 -0
  308. package/dist/taco/svg-import/style/selector-reach.js +169 -0
  309. package/dist/taco/svg-import/style/selector-validity.d.ts +14 -0
  310. package/dist/taco/svg-import/style/selector-validity.js +307 -0
  311. package/dist/taco/svg-import/text/text.d.ts +29 -0
  312. package/dist/taco/svg-import/text/text.js +545 -0
  313. package/dist/taco/svg-import/transform/matrix.d.ts +111 -0
  314. package/dist/taco/svg-import/transform/matrix.js +229 -0
  315. package/dist/taco/svg-import/tree/element-data.d.ts +52 -0
  316. package/dist/taco/svg-import/tree/element-data.js +155 -0
  317. package/dist/taco/svg-import/tree/elements.d.ts +36 -0
  318. package/dist/taco/svg-import/tree/elements.js +121 -0
  319. package/dist/taco/svg-import/units/length.d.ts +43 -0
  320. package/dist/taco/svg-import/units/length.js +125 -0
  321. package/dist/taco/svg-import/units/viewbox.d.ts +35 -0
  322. package/dist/taco/svg-import/units/viewbox.js +77 -0
  323. package/package.json +54 -4
@@ -0,0 +1,31 @@
1
+ import { type Payload } from '@moondraft/editor/core';
2
+ import type { DocumentJSON } from '@moondraft/editor/schema';
3
+ import type { SvgImportResult } from '../taco/svg-import/index.ts';
4
+ import type { ConvertReport, TacoDocument } from './convert.ts';
5
+ /** Settings for creating a paste payload from a converted document. */
6
+ export interface PayloadOptions {
7
+ /** The payload's client id (a paste in the core of that id treats its roots as copies of its own layers). */
8
+ client?: string;
9
+ }
10
+ /**
11
+ * Turns a converted single-page document into a paste payload.
12
+ * @param converted - Converted document and asset report.
13
+ * @param options - Payload client settings.
14
+ * @returns Layers, main definitions and inline assets in a payload, with the original report.
15
+ */
16
+ export declare function toPayload(converted: {
17
+ doc: DocumentJSON;
18
+ report: ConvertReport;
19
+ }, options?: PayloadOptions): {
20
+ /** Clipboard payload with the converted page's layers and dependencies. */
21
+ payload: Payload;
22
+ /** Conversion report for the original page. */
23
+ report: ConvertReport;
24
+ };
25
+ /**
26
+ * Wraps SVG reader output as a one-page Taco document.
27
+ * @param result - Layers, components and images returned by the SVG reader.
28
+ * @param name - Display name for the page. Defaults to SVG.
29
+ * @returns The document with the SVG tree as its one top-level layer.
30
+ */
31
+ export declare function svgDocument(result: SvgImportResult, name?: string): TacoDocument;
@@ -0,0 +1,78 @@
1
+ // A converted page as the editor's clipboard payload (packages/editor/src/core/clipboard.ts Payload), which
2
+ // commands.paste inserts in one undo step: placed by the selection, the view or a drop point, its images made asset
3
+ // records. Also the taco document an SVG import (taco's svg-import, SvgImportResult) is, for toDocument.
4
+ import { clipboard, legacyAuto } from '@moondraft/editor/core';
5
+ import { COMPONENTS } from '@moondraft/editor/schema';
6
+ /** The converter's own fields, which no layer record has (source ids, link markers, its estimates). */
7
+ const CONVERTER_ONLY = ['sourceId', 'instanceOf', 'mainOf', 'setOf', 'variant'];
8
+ /**
9
+ * Turns a converted single-page document into a paste payload.
10
+ * @param converted - Converted document and asset report.
11
+ * @param options - Payload client settings.
12
+ * @returns Layers, main definitions and inline assets in a payload, with the original report.
13
+ */
14
+ export function toPayload(converted, options = {}) {
15
+ const { doc, report } = converted;
16
+ const parentOf = new Map(doc.models.map((m) => [m.id, m.parent ?? '']));
17
+ const hiddenRoot = (id) => {
18
+ for (let at = id, p = parentOf.get(at); p !== undefined; at = p, p = parentOf.get(at))
19
+ if (p === COMPONENTS)
20
+ return at;
21
+ return undefined;
22
+ };
23
+ const nodes = [], roots = [], mains = {};
24
+ for (const model of doc.models.map(legacyAuto)) {
25
+ const { runs, ...rest } = model, m = rest;
26
+ for (const k of CONVERTER_ONLY)
27
+ delete m[k];
28
+ if (runs) {
29
+ const at = [];
30
+ let s = 0;
31
+ for (const [n, k] of runs) {
32
+ if (k >= 0)
33
+ s = k;
34
+ for (let i = 0; i < n; i++)
35
+ at.push(s);
36
+ }
37
+ m.styleAt = at;
38
+ }
39
+ const record = { parent: '', t: [1, 0, 0, 1, 0, 0], opacity: 1, ...m }, main = hiddenRoot(record.id);
40
+ if (main !== undefined)
41
+ (mains[main] ??= []).push(record);
42
+ else {
43
+ nodes.push(record);
44
+ if (!record.parent)
45
+ roots.push({ id: record.id, world: [...record.t] });
46
+ }
47
+ }
48
+ const assets = {};
49
+ for (const a of report.assets) {
50
+ const size = doc.assets?.[a.id];
51
+ assets[a.id] = { src: `data:${a.mimeType};base64,${a.data}`, ...(size?.w !== undefined ? { w: size.w } : {}), ...(size?.h !== undefined ? { h: size.h } : {}) };
52
+ }
53
+ const payload = { format: clipboard.FORMAT, version: clipboard.VERSION, client: options.client ?? 'moondraft-import', roots, nodes, assets, ...(Object.keys(mains).length ? { mains } : {}) };
54
+ return { payload, report };
55
+ }
56
+ const base64 = (bytes) => { let s = ''; for (let i = 0; i < bytes.length; i += 0x8000)
57
+ s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(s); };
58
+ /**
59
+ * Wraps SVG reader output as a one-page Taco document.
60
+ * @param result - Layers, components and images returned by the SVG reader.
61
+ * @param name - Display name for the page. Defaults to SVG.
62
+ * @returns The document with the SVG tree as its one top-level layer.
63
+ */
64
+ export function svgDocument(result, name = 'SVG') {
65
+ const nodes = { '@page': { id: '@page', type: 'frame', name, frame: { x: 0, y: 0, width: 0, height: 0 }, children: [result.root.id] } };
66
+ for (const n of result.nodes)
67
+ nodes[n.id] = n;
68
+ const components = {};
69
+ for (const c of result.components) {
70
+ components[c.definition.id] = c.definition;
71
+ for (const n of c.nodes)
72
+ nodes[n.id] = n;
73
+ }
74
+ const assets = {};
75
+ for (const i of result.images)
76
+ assets[i.id] = { id: i.id, kind: 'image', mimeType: i.mimeType, ...(i.width !== undefined ? { width: i.width } : {}), ...(i.height !== undefined ? { height: i.height } : {}), source: { kind: 'data', data: base64(i.data) } };
77
+ return { pageOrder: ['page'], pages: { page: { name, rootId: '@page' } }, nodes, components, assets };
78
+ }
@@ -0,0 +1,31 @@
1
+ import type { Network, Point } from '@moondraft/editor/schema';
2
+ /**
3
+ * Builds a chain of straight segments through the supplied points.
4
+ * @param points - Vertices in path order.
5
+ * @param closed - Whether the last point joins back to the first.
6
+ * @returns The path network.
7
+ */
8
+ export declare function network(points: readonly Point[], closed: boolean): Network;
9
+ /**
10
+ * Builds a clockwise ellipse at the origin, starting at the top.
11
+ * @param w - Width of the ellipse.
12
+ * @param h - Height of the ellipse.
13
+ * @returns The ellipse network.
14
+ */
15
+ export declare function ellipseNetwork(w: number, h: number): Network;
16
+ /**
17
+ * Builds an open elliptical arc centered at its radii.
18
+ * @param rx - Horizontal radius.
19
+ * @param ry - Vertical radius.
20
+ * @param lo - Starting angle in degrees clockwise from the positive x-axis.
21
+ * @param hi - Ending angle in degrees clockwise from the positive x-axis.
22
+ * @returns The arc network.
23
+ */
24
+ export declare function arcNetwork(rx: number, ry: number, lo: number, hi: number): Network;
25
+ /** An SVG elliptical arc (endpoint form, SVG 2 appendix B.2.4) from `p0` to `p1` as cubics of at most 90 degrees each:
26
+ * the points between them and each cubic's handles, relative to its own ends (ha at the start, hb at the end). A zero
27
+ * radius or equal ends is a straight line: no cubics. */
28
+ export declare function arcCubics(p0: Point, p1: Point, radiusX: number, radiusY: number, rotation: number, largeArc: boolean, sweep: boolean): {
29
+ points: Point[];
30
+ handles: [Point, Point][];
31
+ };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Builds a chain of straight segments through the supplied points.
3
+ * @param points - Vertices in path order.
4
+ * @param closed - Whether the last point joins back to the first.
5
+ * @returns The path network.
6
+ */
7
+ export function network(points, closed) {
8
+ const vertices = points.map(([x, y], i) => ({ id: `v${i}`, x, y }));
9
+ const segments = vertices.slice(0, closed ? undefined : -1).map((v, i) => ({ id: `s${i}`, a: v.id, b: vertices[(i + 1) % vertices.length].id, ha: [0, 0], hb: [0, 0] }));
10
+ return { vertices, segments, loops: closed ? [segments.map((s) => [s.id, false])] : [], next: points.length };
11
+ }
12
+ /**
13
+ * Builds a clockwise ellipse at the origin, starting at the top.
14
+ * @param w - Width of the ellipse.
15
+ * @param h - Height of the ellipse.
16
+ * @returns The ellipse network.
17
+ */
18
+ export function ellipseNetwork(w, h) {
19
+ const rx = w / 2, ry = h / 2, K = 0.5522847498, d = [[1, 0], [0, 1], [-1, 0], [0, -1]];
20
+ const net = network([[rx, 0], [w, ry], [rx, h], [0, ry]], true);
21
+ net.segments.forEach((s, i) => { const [x0, y0] = d[i], [x1, y1] = d[(i + 1) % 4]; s.ha = [x0 * K * rx, y0 * K * ry]; s.hb = [-x1 * K * rx, -y1 * K * ry]; });
22
+ return net;
23
+ }
24
+ /**
25
+ * Builds an open elliptical arc centered at its radii.
26
+ * @param rx - Horizontal radius.
27
+ * @param ry - Vertical radius.
28
+ * @param lo - Starting angle in degrees clockwise from the positive x-axis.
29
+ * @param hi - Ending angle in degrees clockwise from the positive x-axis.
30
+ * @returns The arc network.
31
+ */
32
+ export function arcNetwork(rx, ry, lo, hi) {
33
+ const parts = Math.max(1, Math.ceil((hi - lo) / 90)), step = (hi - lo) / parts * Math.PI / 180, k = 4 / 3 * Math.tan(step / 4);
34
+ const at = (i) => lo * Math.PI / 180 + i * step, point = (a) => [rx + rx * Math.cos(a), ry + ry * Math.sin(a)], tangent = (a) => [-rx * Math.sin(a), ry * Math.cos(a)];
35
+ const net = network(Array.from({ length: parts + 1 }, (_, i) => point(at(i))), false);
36
+ net.segments.forEach((s, i) => { const t0 = tangent(at(i)), t1 = tangent(at(i + 1)); s.ha = [k * t0[0], k * t0[1]]; s.hb = [-k * t1[0], -k * t1[1]]; });
37
+ return net;
38
+ }
39
+ /** An SVG elliptical arc (endpoint form, SVG 2 appendix B.2.4) from `p0` to `p1` as cubics of at most 90 degrees each:
40
+ * the points between them and each cubic's handles, relative to its own ends (ha at the start, hb at the end). A zero
41
+ * radius or equal ends is a straight line: no cubics. */
42
+ export function arcCubics(p0, p1, radiusX, radiusY, rotation, largeArc, sweep) {
43
+ let rx = Math.abs(radiusX), ry = Math.abs(radiusY);
44
+ if (!rx || !ry || (p0[0] === p1[0] && p0[1] === p1[1]))
45
+ return { points: [], handles: [] };
46
+ const phi = (rotation * Math.PI) / 180, cos = Math.cos(phi), sin = Math.sin(phi);
47
+ const dx = (p0[0] - p1[0]) / 2, dy = (p0[1] - p1[1]) / 2, x = cos * dx + sin * dy, y = -sin * dx + cos * dy;
48
+ const lambda = (x * x) / (rx * rx) + (y * y) / (ry * ry);
49
+ if (lambda > 1) {
50
+ rx *= Math.sqrt(lambda);
51
+ ry *= Math.sqrt(lambda);
52
+ }
53
+ const num = rx * rx * ry * ry - rx * rx * y * y - ry * ry * x * x, den = rx * rx * y * y + ry * ry * x * x;
54
+ const coef = (largeArc === sweep ? -1 : 1) * Math.sqrt(Math.max(0, num / den));
55
+ const cxp = (coef * rx * y) / ry, cyp = (-coef * ry * x) / rx;
56
+ const cx = cos * cxp - sin * cyp + (p0[0] + p1[0]) / 2, cy = sin * cxp + cos * cyp + (p0[1] + p1[1]) / 2;
57
+ const angle = (ux, uy, vx, vy) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
58
+ const start = angle(1, 0, (x - cxp) / rx, (y - cyp) / ry);
59
+ let delta = angle((x - cxp) / rx, (y - cyp) / ry, (-x - cxp) / rx, (-y - cyp) / ry);
60
+ if (!sweep && delta > 0)
61
+ delta -= 2 * Math.PI;
62
+ else if (sweep && delta < 0)
63
+ delta += 2 * Math.PI;
64
+ const parts = Math.max(1, Math.ceil(Math.abs(delta) / (Math.PI / 2) - 1e-9)), step = delta / parts, k = (4 / 3) * Math.tan(step / 4);
65
+ const point = (a) => [cx + rx * cos * Math.cos(a) - ry * sin * Math.sin(a), cy + rx * sin * Math.cos(a) + ry * cos * Math.sin(a)];
66
+ const tangent = (a) => [-rx * cos * Math.sin(a) - ry * sin * Math.cos(a), -rx * sin * Math.sin(a) + ry * cos * Math.cos(a)];
67
+ const points = [], handles = [];
68
+ for (let i = 0; i < parts; i++) {
69
+ const a0 = start + i * step, a1 = a0 + step, t0 = tangent(a0), t1 = tangent(a1);
70
+ if (i > 0)
71
+ points.push(point(a0));
72
+ handles.push([[k * t0[0], k * t0[1]], [-k * t1[0], -k * t1[1]]]);
73
+ }
74
+ return { points, handles };
75
+ }
@@ -0,0 +1,44 @@
1
+ /** A theme's variable collections, as taco stores them (theme.variableCollections). */
2
+ export interface VariableCollection {
3
+ /** Collection name used in qualified variable references. */
4
+ name: string;
5
+ /** Mode used when the selected mode has no value. */
6
+ defaultModeId?: string;
7
+ /** Mode selected for this collection when the caller supplies no override. */
8
+ activeModeId?: string;
9
+ /** Mode definitions by ID. */
10
+ modes?: Record<string, unknown>;
11
+ /** Mode IDs in display order. */
12
+ modeOrder?: string[];
13
+ /** Variable definitions by ID. */
14
+ variables?: Record<string, {
15
+ /** Variable name within the collection. */
16
+ name: string;
17
+ /** Source type of the variable. */
18
+ type?: string;
19
+ /** Literal or alias values by mode ID. */
20
+ values?: Record<string, unknown>;
21
+ }>;
22
+ }
23
+ /** A resolved scalar variable value. */
24
+ export type VariableValue = number | boolean | string;
25
+ type Modes = Record<string, string>;
26
+ /**
27
+ * Builds a resolver for variables and aliases in the source model.
28
+ * @param collections - Source collections indexed by ID.
29
+ * @returns A resolver that takes a variable name or ID and optional collection modes.
30
+ */
31
+ export declare function variableResolver(collections?: Record<string, VariableCollection>): (name: string, modes?: Modes) => VariableValue | undefined;
32
+ /**
33
+ * The collections as taco's expression evaluator reads them (it follows no aliases, and reads a chosen mode only when
34
+ * the collection's modes table has it): each collection with a modes table (made from the modes it names when it has
35
+ * none), and each value plain and of its variable's type. Aliases are followed as variableResolver follows them, the
36
+ * target's collection in its mode under `modes` (`aliased` says whether there are any, so whether the result depends
37
+ * on `modes`). A value that does not resolve or does not fit its type is left out, so an expression that reads it is
38
+ * not evaluated (and is counted) rather than reading a wrong value.
39
+ */
40
+ export declare function expressionCollections(collections?: Record<string, VariableCollection>): {
41
+ aliased: boolean;
42
+ at: (modes?: Modes) => Record<string, VariableCollection>;
43
+ };
44
+ export {};
@@ -0,0 +1,103 @@
1
+ const aliasTarget = (value) => {
2
+ if (!value || typeof value !== 'object')
3
+ return undefined;
4
+ const v = value;
5
+ return v.alias ?? v.variableId ?? (['alias', 'VARIABLE_ALIAS'].includes(v.type ?? '') ? v.id : undefined);
6
+ };
7
+ const plainValue = (value) => typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string';
8
+ /** The modes a collection has: its modes table, or without one (older exports) the modes its values and defaults name. */
9
+ function modeIdsOf(collection) {
10
+ if (collection.modes)
11
+ return new Set(Object.keys(collection.modes));
12
+ const ids = new Set();
13
+ for (const id of [collection.defaultModeId, collection.activeModeId])
14
+ if (id !== undefined)
15
+ ids.add(id);
16
+ for (const variable of Object.values(collection.variables ?? {}))
17
+ for (const id of Object.keys(variable.values ?? {}))
18
+ ids.add(id);
19
+ return ids;
20
+ }
21
+ function lookup(collections) {
22
+ const byName = new Map(), byId = new Map(), modeIds = new Map();
23
+ for (const [collectionId, collection] of Object.entries(collections)) {
24
+ modeIds.set(collectionId, modeIdsOf(collection));
25
+ for (const [id, variable] of Object.entries(collection.variables ?? {})) {
26
+ const entry = { collectionId, collection, variable, id };
27
+ byName.set(`${collection.name}/${variable.name}`, entry);
28
+ byId.set(id, entry);
29
+ }
30
+ }
31
+ const modeOf = (entry, modes) => {
32
+ const chosen = modes[entry.collectionId];
33
+ return chosen !== undefined && modeIds.get(entry.collectionId).has(chosen) ? chosen : entry.collection.activeModeId ?? entry.collection.defaultModeId;
34
+ };
35
+ // `value`, a variable's stored value, as a plain value: an alias followed (not through a cycle) to its target.
36
+ function plain(value, modes, seen) {
37
+ const target = aliasTarget(value);
38
+ if (target !== undefined)
39
+ return resolve(byId.get(target) ?? byName.get(target), modes, seen);
40
+ return plainValue(value) ? value : undefined;
41
+ }
42
+ function resolve(entry, modes, seen) {
43
+ if (!entry || seen.has(entry.id))
44
+ return undefined;
45
+ seen.add(entry.id);
46
+ const values = entry.variable.values ?? {}, mode = modeOf(entry, modes), fallback = entry.collection.defaultModeId;
47
+ const value = mode !== undefined && Object.hasOwn(values, mode) ? values[mode] : fallback !== undefined && Object.hasOwn(values, fallback) ? values[fallback] : undefined;
48
+ return plain(value, modes, seen);
49
+ }
50
+ return { byName, byId, modeIds, plain, resolve };
51
+ }
52
+ /**
53
+ * Builds a resolver for variables and aliases in the source model.
54
+ * @param collections - Source collections indexed by ID.
55
+ * @returns A resolver that takes a variable name or ID and optional collection modes.
56
+ */
57
+ export function variableResolver(collections = {}) {
58
+ const { byName, byId, resolve } = lookup(collections);
59
+ return (name, modes = {}) => resolve(byName.get(name) ?? byId.get(name), modes, new Set());
60
+ }
61
+ const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
62
+ // Whether `value` is one taco's evaluator reads as a variable of `type` (it reads a colour from a hex string and a
63
+ // number with Number(), so anything else would come out as a wrong colour or NaN).
64
+ const fits = (type, value) => type === 'color' ? typeof value === 'string' && HEX.test(value)
65
+ : type === 'number' ? typeof value === 'number' && Number.isFinite(value)
66
+ : type === 'boolean' ? typeof value === 'boolean'
67
+ : type === 'string' ? typeof value === 'string'
68
+ : true;
69
+ /**
70
+ * The collections as taco's expression evaluator reads them (it follows no aliases, and reads a chosen mode only when
71
+ * the collection's modes table has it): each collection with a modes table (made from the modes it names when it has
72
+ * none), and each value plain and of its variable's type. Aliases are followed as variableResolver follows them, the
73
+ * target's collection in its mode under `modes` (`aliased` says whether there are any, so whether the result depends
74
+ * on `modes`). A value that does not resolve or does not fit its type is left out, so an expression that reads it is
75
+ * not evaluated (and is counted) rather than reading a wrong value.
76
+ */
77
+ export function expressionCollections(collections = {}) {
78
+ const { modeIds, plain } = lookup(collections);
79
+ const aliased = Object.values(collections).some((c) => Object.values(c.variables ?? {}).some((v) => Object.values(v.values ?? {}).some((x) => aliasTarget(x) !== undefined)));
80
+ const at = (modes = {}) => Object.fromEntries(Object.entries(collections).map(([collectionId, collection]) => {
81
+ const ids = [...modeIds.get(collectionId)];
82
+ const variables = Object.fromEntries(Object.entries(collection.variables ?? {}).map(([id, variable]) => {
83
+ const values = {}, stored = variable.values ?? {}, fallback = collection.defaultModeId;
84
+ // An alias within the collection reads the same mode as the value it stands for. A mode without a value reads
85
+ // the default mode's: when that is an alias, it reads its target in that mode, as variableResolver does (taco
86
+ // would read the default mode's value as it stands, the target in the default mode).
87
+ const fallsBack = fallback !== undefined && Object.hasOwn(stored, fallback) && aliasTarget(stored[fallback]) !== undefined;
88
+ for (const mode of fallsBack ? new Set([...Object.keys(stored), ...ids]) : Object.keys(stored)) {
89
+ const v = plain(Object.hasOwn(stored, mode) ? stored[mode] : stored[fallback], { ...modes, [collectionId]: mode }, new Set([id]));
90
+ if (v !== undefined && fits(variable.type, v))
91
+ values[mode] = v;
92
+ }
93
+ return [id, { ...variable, values }];
94
+ }));
95
+ return [collectionId, {
96
+ ...collection,
97
+ modes: collection.modes ?? Object.fromEntries(ids.map((m) => [m, { name: m }])),
98
+ modeOrder: collection.modeOrder ?? ids,
99
+ variables,
100
+ }];
101
+ }));
102
+ return { aliased, at };
103
+ }
@@ -0,0 +1,38 @@
1
+ import type { ImportDocument, ImportEnv, ImportSignal } from '@moondraft/editor/core';
2
+ /** The subset of a module worker used to read a .fig file. */
3
+ export interface WorkerLike {
4
+ /**
5
+ * Sends a request to the worker.
6
+ * @param message - Request data.
7
+ * @param transfer - Buffers transferred with the request.
8
+ */
9
+ postMessage(message: unknown, transfer?: Transferable[]): void;
10
+ /**
11
+ * Subscribes to a worker event.
12
+ * @param type - Event to observe.
13
+ * @param listener - Callback receiving the event.
14
+ */
15
+ addEventListener(type: 'message' | 'messageerror' | 'error', listener: (event: {
16
+ /** Worker reply, for a message event. */
17
+ data?: unknown;
18
+ /** Diagnostic, for an error event. */
19
+ message?: string;
20
+ }) => void): void;
21
+ /** Stops the worker. */
22
+ terminate(): void;
23
+ }
24
+ /** Options for reading a .fig file. */
25
+ export interface OpenFigmaOptions extends Pick<ImportEnv, 'signal' | 'progress'> {
26
+ /** Factory for a dedicated worker. Defaults to a module worker when available. Pass null to read on this thread. */
27
+ worker?: (() => WorkerLike) | null;
28
+ }
29
+ /** @internal Propagates the host's cancellation reason at a Figma read checkpoint. */
30
+ export declare function checkAbort(signal?: ImportSignal): void;
31
+ /**
32
+ * Reads and converts all public pages in a .fig file. Transfers the input buffer when using a worker.
33
+ * @param bytes - Saved Figma design file.
34
+ * @param options - Worker, cancellation and progress options.
35
+ * @returns The converted document and report.
36
+ * @throws The abort reason or a file read or conversion error, as a rejection.
37
+ */
38
+ export declare function openFigmaFile(bytes: Uint8Array, options?: OpenFigmaOptions): Promise<ImportDocument>;
@@ -0,0 +1,97 @@
1
+ const defaultWorker = typeof Worker === 'undefined' ? null
2
+ : () => new Worker(new URL('./figma-worker.js', import.meta.url), { type: 'module', name: 'figma-import' });
3
+ const abortReason = (signal) => 'reason' in signal ? signal.reason : new Error('Import aborted');
4
+ /** @internal Propagates the host's cancellation reason at a Figma read checkpoint. */
5
+ export function checkAbort(signal) {
6
+ if (signal?.aborted)
7
+ throw abortReason(signal);
8
+ }
9
+ /**
10
+ * Reads and converts all public pages in a .fig file. Transfers the input buffer when using a worker.
11
+ * @param bytes - Saved Figma design file.
12
+ * @param options - Worker, cancellation and progress options.
13
+ * @returns The converted document and report.
14
+ * @throws The abort reason or a file read or conversion error, as a rejection.
15
+ */
16
+ export async function openFigmaFile(bytes, options = {}) {
17
+ const { signal, progress } = options, make = options.worker === undefined ? defaultWorker : options.worker;
18
+ checkAbort(signal);
19
+ const worker = make ? await started(make, signal) : null;
20
+ if (signal?.aborted) {
21
+ worker?.terminate();
22
+ throw abortReason(signal);
23
+ }
24
+ if (!worker) {
25
+ const { readFigmaFile } = await import('./figma.js');
26
+ return readFigmaFile(bytes, { signal, progress });
27
+ }
28
+ const own = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
29
+ try {
30
+ return await new Promise((resolve, reject) => {
31
+ const abort = () => { finish(); reject(abortReason(signal)); };
32
+ signal?.addEventListener('abort', abort, { once: true });
33
+ const finish = () => signal?.removeEventListener?.('abort', abort);
34
+ worker.addEventListener('message', ({ data }) => {
35
+ const reply = data;
36
+ if ('progress' in reply) {
37
+ if (!signal?.aborted)
38
+ try {
39
+ progress?.(reply.progress);
40
+ }
41
+ catch (error) {
42
+ finish();
43
+ reject(error);
44
+ }
45
+ return;
46
+ }
47
+ finish();
48
+ if (reply.ok)
49
+ resolve(reply.value);
50
+ else
51
+ reject(new Error(reply.error));
52
+ });
53
+ worker.addEventListener('messageerror', () => { finish(); reject(new Error('the Figma importer sent a reply that could not be read')); });
54
+ worker.addEventListener('error', ({ message }) => { finish(); reject(new Error(`the Figma importer failed to run: ${message ?? 'worker error'}`)); });
55
+ try {
56
+ worker.postMessage(own, [own.buffer]);
57
+ }
58
+ catch (error) {
59
+ finish();
60
+ reject(error);
61
+ }
62
+ });
63
+ }
64
+ finally {
65
+ worker.terminate();
66
+ }
67
+ }
68
+ // Worker startup failures fall back before the input buffer has been transferred.
69
+ function started(make, signal) {
70
+ let worker;
71
+ try {
72
+ worker = make();
73
+ }
74
+ catch {
75
+ return Promise.resolve(null);
76
+ }
77
+ return new Promise((resolve) => {
78
+ let settled = false;
79
+ const abort = () => settle(false);
80
+ const settle = (ok) => {
81
+ if (settled)
82
+ return;
83
+ settled = true;
84
+ signal?.removeEventListener?.('abort', abort);
85
+ if (!ok)
86
+ worker.terminate();
87
+ resolve(ok ? worker : null);
88
+ };
89
+ worker.addEventListener('message', ({ data }) => { if (data?.ready === true)
90
+ settle(true); });
91
+ worker.addEventListener('error', () => settle(false));
92
+ if (signal?.aborted)
93
+ abort();
94
+ else
95
+ signal?.addEventListener('abort', abort, { once: true });
96
+ });
97
+ }
@@ -0,0 +1,11 @@
1
+ import type { ImportDocument, ImportProgress } from '@moondraft/editor/core';
2
+ /** Replies sent by the module worker after it is ready. */
3
+ export type FigmaWorkerReply = {
4
+ progress: ImportProgress;
5
+ } | {
6
+ ok: true;
7
+ value: ImportDocument;
8
+ } | {
9
+ ok: false;
10
+ error: string;
11
+ };
@@ -0,0 +1,12 @@
1
+ import { readFigmaFile } from './figma.js';
2
+ const scope = globalThis;
3
+ scope.onmessage = ({ data }) => {
4
+ try {
5
+ const value = readFigmaFile(data, { progress: (progress) => scope.postMessage({ progress }) });
6
+ scope.postMessage({ ok: true, value });
7
+ }
8
+ catch (error) {
9
+ scope.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) });
10
+ }
11
+ };
12
+ scope.postMessage({ ready: true });
@@ -0,0 +1,26 @@
1
+ import { type ImportDocument, type ImportEnv, type ImportPayload } from '@moondraft/editor/core';
2
+ /**
3
+ * Checks for the markers Figma adds to clipboard HTML.
4
+ * @param html - Clipboard HTML to inspect.
5
+ * @returns Whether both Figma markers are present.
6
+ */
7
+ export declare const holdsFigmaData: (html: string) => boolean;
8
+ /** Report description for images whose bytes are unavailable on the clipboard. */
9
+ export declare const MISSING_IMAGES = "Unresolved images (shown as placeholders)";
10
+ /**
11
+ * Imports Figma clipboard HTML as editable layers.
12
+ * @param html - Clipboard HTML containing Figma data.
13
+ * @returns Paste payload and conversion report.
14
+ * @throws An error if the input contains no readable Figma layers.
15
+ */
16
+ export declare function readFigmaClipboard(html: string): ImportPayload;
17
+ /** Options for reading a Figma file synchronously. */
18
+ export type ReadFigmaOptions = Pick<ImportEnv, 'signal' | 'progress'>;
19
+ /**
20
+ * Reads a saved Figma design file on the calling thread.
21
+ * @param bytes - Saved Figma design file.
22
+ * @param options - Cancellation and progress options.
23
+ * @returns All public pages in file order, editable component and resource records, images and a report of font faces and conversion losses.
24
+ * @throws The abort reason or a file read or conversion error.
25
+ */
26
+ export declare function readFigmaFile(bytes: Uint8Array, options?: ReadFigmaOptions): ImportDocument;
package/dist/figma.js ADDED
@@ -0,0 +1,96 @@
1
+ import { clipboard, createCore } from '@moondraft/editor/core';
2
+ import { figmaDocument, toDocument, toPayload } from './adapter/index.js';
3
+ import { fileComponents } from './adapter/file-components.js';
4
+ import { sha256Hex } from './taco/model/sha256.js';
5
+ import { expandedRadiusRoots, fileResources } from './adapter/file-resources.js';
6
+ import { readFileMessage } from './taco/figma-import/import/walk.js';
7
+ import { allPages } from './adapter/convert.js';
8
+ import { convertEntries, fontEntries, grouped, layersBySource } from './report.js';
9
+ import { checkAbort } from './figma-file.js';
10
+ import { importFigmaMessage, readFigFile, readFigmaClipboardHtml } from './taco/figma-import/index.js';
11
+ /**
12
+ * Checks for the markers Figma adds to clipboard HTML.
13
+ * @param html - Clipboard HTML to inspect.
14
+ * @returns Whether both Figma markers are present.
15
+ */
16
+ export const holdsFigmaData = (html) => html.includes('(figmeta)') && html.includes('(figma)');
17
+ /** Report description for images whose bytes are unavailable on the clipboard. */
18
+ export const MISSING_IMAGES = clipboard.MISSING_IMAGE_REPORT;
19
+ const STAND_IN = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
20
+ const ids = () => { let next = 0; return () => `f${++next}`; };
21
+ function reportOf(result, converted, extra = []) {
22
+ const bySource = layersBySource(converted.doc);
23
+ const pages = converted.doc.models.filter(m => m.kind === 'page');
24
+ const pageIds = new Map(result.pages.map((page, i) => [page.figmaId, pages[i]?.id]));
25
+ const reader = result.report.filter(entry => entry.nodeType !== 'CANVAS' || entry.reason === 'variable mode').map((entry) => {
26
+ const layer = result.layerIds[entry.nodeId];
27
+ const pageId = pageIds.get(entry.nodeId);
28
+ const ids = pageId ? [pageId] : layer === undefined ? undefined : bySource.get(layer);
29
+ return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', what: entry.reason, count: 1, ...(ids && { ids }) };
30
+ });
31
+ return grouped([...reader, ...convertEntries(converted.report, true), ...extra]);
32
+ }
33
+ /**
34
+ * Imports Figma clipboard HTML as editable layers.
35
+ * @param html - Clipboard HTML containing Figma data.
36
+ * @returns Paste payload and conversion report.
37
+ * @throws An error if the input contains no readable Figma layers.
38
+ */
39
+ export function readFigmaClipboard(html) {
40
+ const { message } = readFigmaClipboardHtml(html), missing = new Set();
41
+ const result = importFigmaMessage(message, {
42
+ idSource: ids(), roots: 'clipboard-selection', bindVariables: false, textStyles: false,
43
+ images: (hash) => { missing.add(`figma-image-${hash}`); return { bytes: STAND_IN, mimeType: 'image/png' }; },
44
+ });
45
+ const converted = toDocument(figmaDocument(result, 'Pasted'), 0), { payload } = toPayload(converted);
46
+ const assetIds = [...missing].filter((id) => Object.hasOwn(payload.assets, id));
47
+ for (const id of assetIds)
48
+ delete payload.assets[id];
49
+ return { payload, report: reportOf(result, converted, assetIds.length ? [{ kind: 'left-out', what: MISSING_IMAGES, count: assetIds.length, assetIds }] : []) };
50
+ }
51
+ /**
52
+ * Reads a saved Figma design file on the calling thread.
53
+ * @param bytes - Saved Figma design file.
54
+ * @param options - Cancellation and progress options.
55
+ * @returns All public pages in file order, editable component and resource records, images and a report of font faces and conversion losses.
56
+ * @throws The abort reason or a file read or conversion error.
57
+ */
58
+ export function readFigmaFile(bytes, options = {}) {
59
+ const { signal, progress } = options;
60
+ function checkpoint(stage, done, total) {
61
+ checkAbort(signal);
62
+ progress?.({ stage, done, ...(total !== undefined && { total }) });
63
+ checkAbort(signal);
64
+ }
65
+ checkpoint('decode', 0, 1);
66
+ const file = readFigFile(bytes);
67
+ checkpoint('decode', 1, 1);
68
+ checkpoint('convert', 0);
69
+ const result = readFileMessage(file.message, {
70
+ idSource: ids(), roots: 'pages',
71
+ images: (hash) => { const bytes = file.images.get(hash); return bytes ? { bytes } : undefined; },
72
+ });
73
+ const total = result.pages.length;
74
+ const geometry = figmaDocument(result);
75
+ const expandedRadii = expandedRadiusRoots(result);
76
+ for (const id of expandedRadii.keys())
77
+ geometry.nodes[id] = { ...geometry.nodes[id], fileExpanded: true };
78
+ for (const layer of result.sources.styleLayers.values())
79
+ geometry.nodes[layer.id] = { ...layer, fileStyle: true };
80
+ const converted = allPages(geometry, {
81
+ assetSrc: (_id, asset) => `data:${asset.mimeType};base64,${asset.source.data}`,
82
+ });
83
+ const extra = [];
84
+ const occurrences = fileComponents(result, converted.doc, extra);
85
+ let fileId = file.meta?.fileKey || file.message.fileKey;
86
+ fileResources(result, converted.doc, occurrences, converted.expanded, expandedRadii, extra, () => String(fileId ||= sha256Hex(bytes)));
87
+ const reader = result.report.filter(e => !e.reason.startsWith('variable bindings left out, their values kept:'));
88
+ const report = reportOf({ ...result, report: reader }, converted, [...extra, ...fontEntries(converted.doc)]);
89
+ for (const model of converted.doc.models)
90
+ delete model.sourceId;
91
+ // Use the same derived pass as editor.load so saved literals include mode choices and nested property assignments.
92
+ const document = converted.doc.shared || converted.doc.models.some(m => m.kind === 'frame' && (m.variantSet || m.props))
93
+ ? createCore({ document: converted.doc, trackLayout: false }).toJSON() : converted.doc;
94
+ checkpoint('convert', total, total);
95
+ return { document, report };
96
+ }