@pairdraw/core 0.20.0 → 0.21.1

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 (539) hide show
  1. package/dist/canvas/noise/render.js +1 -1
  2. package/dist/canvas/noise/render.js.map +1 -1
  3. package/dist/canvas/noise/shader.d.ts +6 -3
  4. package/dist/canvas/noise/shader.d.ts.map +1 -1
  5. package/dist/canvas/noise/shader.js +12 -7
  6. package/dist/canvas/noise/shader.js.map +1 -1
  7. package/dist/canvas/noise/tile.d.ts.map +1 -1
  8. package/dist/canvas/noise/tile.js +2 -1
  9. package/dist/canvas/noise/tile.js.map +1 -1
  10. package/dist/canvas/renderer/colors.d.ts +20 -5
  11. package/dist/canvas/renderer/colors.d.ts.map +1 -1
  12. package/dist/canvas/renderer/colors.js +48 -42
  13. package/dist/canvas/renderer/colors.js.map +1 -1
  14. package/dist/canvas/renderer/document-surface.d.ts +25 -0
  15. package/dist/canvas/renderer/document-surface.d.ts.map +1 -0
  16. package/dist/canvas/renderer/document-surface.js +46 -0
  17. package/dist/canvas/renderer/document-surface.js.map +1 -0
  18. package/dist/canvas/renderer/fonts.d.ts.map +1 -1
  19. package/dist/canvas/renderer/fonts.js +6 -4
  20. package/dist/canvas/renderer/fonts.js.map +1 -1
  21. package/dist/canvas/renderer/lifecycle.js +4 -3
  22. package/dist/canvas/renderer/lifecycle.js.map +1 -1
  23. package/dist/canvas/renderer/methods.d.ts.map +1 -1
  24. package/dist/canvas/renderer/methods.js +1 -0
  25. package/dist/canvas/renderer/methods.js.map +1 -1
  26. package/dist/canvas/renderer/pipeline.d.ts.map +1 -1
  27. package/dist/canvas/renderer/pipeline.js +23 -2
  28. package/dist/canvas/renderer/pipeline.js.map +1 -1
  29. package/dist/canvas/renderer/retained-backing.d.ts.map +1 -1
  30. package/dist/canvas/renderer/retained-backing.js +2 -1
  31. package/dist/canvas/renderer/retained-backing.js.map +1 -1
  32. package/dist/canvas/renderer/tiles/surface-pool.d.ts.map +1 -1
  33. package/dist/canvas/renderer/tiles/surface-pool.js +2 -7
  34. package/dist/canvas/renderer/tiles/surface-pool.js.map +1 -1
  35. package/dist/canvas/renderer.d.ts +20 -2
  36. package/dist/canvas/renderer.d.ts.map +1 -1
  37. package/dist/canvas/renderer.js +28 -4
  38. package/dist/canvas/renderer.js.map +1 -1
  39. package/dist/canvas/scene.d.ts.map +1 -1
  40. package/dist/canvas/scene.js +4 -3
  41. package/dist/canvas/scene.js.map +1 -1
  42. package/dist/canvas/shaders/compile.d.ts +3 -1
  43. package/dist/canvas/shaders/compile.d.ts.map +1 -1
  44. package/dist/canvas/shaders/compile.js +12 -3
  45. package/dist/canvas/shaders/compile.js.map +1 -1
  46. package/dist/canvas/shaders/draw.d.ts.map +1 -1
  47. package/dist/canvas/shaders/draw.js +10 -3
  48. package/dist/canvas/shaders/draw.js.map +1 -1
  49. package/dist/canvas/shaders/effect.d.ts.map +1 -1
  50. package/dist/canvas/shaders/effect.js +8 -17
  51. package/dist/canvas/shaders/effect.js.map +1 -1
  52. package/dist/canvas/shadows/shape.d.ts.map +1 -1
  53. package/dist/canvas/shadows/shape.js +4 -2
  54. package/dist/canvas/shadows/shape.js.map +1 -1
  55. package/dist/canvas/shadows.d.ts.map +1 -1
  56. package/dist/canvas/shadows.js +4 -2
  57. package/dist/canvas/shadows.js.map +1 -1
  58. package/dist/canvas/text/decorations.d.ts +2 -2
  59. package/dist/canvas/text/decorations.d.ts.map +1 -1
  60. package/dist/canvas/text/decorations.js +5 -5
  61. package/dist/canvas/text/decorations.js.map +1 -1
  62. package/dist/canvas/text/index.js +1 -1
  63. package/dist/canvas/text/index.js.map +1 -1
  64. package/dist/canvas/text/paragraph/index.d.ts +2 -2
  65. package/dist/canvas/text/paragraph/index.d.ts.map +1 -1
  66. package/dist/canvas/text/paragraph/index.js +16 -5
  67. package/dist/canvas/text/paragraph/index.js.map +1 -1
  68. package/dist/canvas/text/renderer.d.ts +2 -1
  69. package/dist/canvas/text/renderer.d.ts.map +1 -1
  70. package/dist/canvas/text/shape.js +4 -4
  71. package/dist/canvas/text/shape.js.map +1 -1
  72. package/dist/canvas/texture.d.ts.map +1 -1
  73. package/dist/canvas/texture.js +2 -1
  74. package/dist/canvas/texture.js.map +1 -1
  75. package/dist/design-memory/rules.js +1 -1
  76. package/dist/editor/clipboard/assets.d.ts.map +1 -1
  77. package/dist/editor/clipboard/assets.js +2 -2
  78. package/dist/editor/clipboard/assets.js.map +1 -1
  79. package/dist/editor/clipboard/component-matches.d.ts +13 -0
  80. package/dist/editor/clipboard/component-matches.d.ts.map +1 -0
  81. package/dist/editor/clipboard/component-matches.js +50 -0
  82. package/dist/editor/clipboard/component-matches.js.map +1 -0
  83. package/dist/editor/clipboard/dependencies.d.ts +7 -0
  84. package/dist/editor/clipboard/dependencies.d.ts.map +1 -1
  85. package/dist/editor/clipboard/dependencies.js +5 -0
  86. package/dist/editor/clipboard/dependencies.js.map +1 -1
  87. package/dist/editor/clipboard/export.js +2 -2
  88. package/dist/editor/clipboard/export.js.map +1 -1
  89. package/dist/editor/clipboard.d.ts.map +1 -1
  90. package/dist/editor/clipboard.js +48 -19
  91. package/dist/editor/clipboard.js.map +1 -1
  92. package/dist/editor/components/properties.d.ts.map +1 -1
  93. package/dist/editor/components/properties.js +3 -3
  94. package/dist/editor/components/properties.js.map +1 -1
  95. package/dist/editor/eyedropper.d.ts +1 -1
  96. package/dist/editor/eyedropper.d.ts.map +1 -1
  97. package/dist/editor/eyedropper.js +6 -3
  98. package/dist/editor/eyedropper.js.map +1 -1
  99. package/dist/editor/history/atomic-tool.d.ts.map +1 -1
  100. package/dist/editor/history/atomic-tool.js +3 -2
  101. package/dist/editor/history/atomic-tool.js.map +1 -1
  102. package/dist/editor/shapes/pencil.js +1 -1
  103. package/dist/editor/structure/state.d.ts.map +1 -1
  104. package/dist/editor/structure/state.js +2 -2
  105. package/dist/editor/structure/state.js.map +1 -1
  106. package/dist/editor/text.d.ts.map +1 -1
  107. package/dist/editor/text.js +2 -2
  108. package/dist/editor/text.js.map +1 -1
  109. package/dist/editor/variables.js +3 -3
  110. package/dist/editor/variables.js.map +1 -1
  111. package/dist/figma-api/fresh-read.d.ts +15 -0
  112. package/dist/figma-api/fresh-read.d.ts.map +1 -0
  113. package/dist/figma-api/fresh-read.js +54 -0
  114. package/dist/figma-api/fresh-read.js.map +1 -0
  115. package/dist/figma-api/graph-ref.d.ts +9 -0
  116. package/dist/figma-api/graph-ref.d.ts.map +1 -0
  117. package/dist/figma-api/graph-ref.js +14 -0
  118. package/dist/figma-api/graph-ref.js.map +1 -0
  119. package/dist/figma-api/index.d.ts +6 -1
  120. package/dist/figma-api/index.d.ts.map +1 -1
  121. package/dist/figma-api/index.js +12 -5
  122. package/dist/figma-api/index.js.map +1 -1
  123. package/dist/figma-api/pending-layout.d.ts +3 -3
  124. package/dist/figma-api/pending-layout.d.ts.map +1 -1
  125. package/dist/figma-api/pending-layout.js +7 -3
  126. package/dist/figma-api/pending-layout.js.map +1 -1
  127. package/dist/figma-api/pending-sync.d.ts +1 -1
  128. package/dist/figma-api/pending-sync.d.ts.map +1 -1
  129. package/dist/figma-api/pending-sync.js +3 -1
  130. package/dist/figma-api/pending-sync.js.map +1 -1
  131. package/dist/figma-api/proxy.d.ts.map +1 -1
  132. package/dist/figma-api/proxy.js +3 -2
  133. package/dist/figma-api/proxy.js.map +1 -1
  134. package/dist/figma-api/reactions.d.ts +20 -4
  135. package/dist/figma-api/reactions.d.ts.map +1 -1
  136. package/dist/figma-api/reactions.js +49 -3
  137. package/dist/figma-api/reactions.js.map +1 -1
  138. package/dist/figma-api/variables/index.d.ts.map +1 -1
  139. package/dist/figma-api/variables/index.js +2 -2
  140. package/dist/figma-api/variables/index.js.map +1 -1
  141. package/dist/io/formats/design-tokens/css/known.js +1 -1
  142. package/dist/io/formats/design-tokens/css/known.js.map +1 -1
  143. package/dist/io/formats/design-tokens/css/read.d.ts +3 -1
  144. package/dist/io/formats/design-tokens/css/read.d.ts.map +1 -1
  145. package/dist/io/formats/design-tokens/css/read.js +11 -5
  146. package/dist/io/formats/design-tokens/css/read.js.map +1 -1
  147. package/dist/io/formats/design-tokens/css/sync.d.ts.map +1 -1
  148. package/dist/io/formats/design-tokens/css/sync.js +17 -4
  149. package/dist/io/formats/design-tokens/css/sync.js.map +1 -1
  150. package/dist/io/formats/design-tokens/css/values.d.ts +6 -5
  151. package/dist/io/formats/design-tokens/css/values.d.ts.map +1 -1
  152. package/dist/io/formats/design-tokens/css/values.js +24 -8
  153. package/dist/io/formats/design-tokens/css/values.js.map +1 -1
  154. package/dist/io/formats/design-tokens/decode.d.ts +7 -6
  155. package/dist/io/formats/design-tokens/decode.d.ts.map +1 -1
  156. package/dist/io/formats/design-tokens/decode.js +13 -12
  157. package/dist/io/formats/design-tokens/decode.js.map +1 -1
  158. package/dist/io/formats/design-tokens/export.js +3 -3
  159. package/dist/io/formats/design-tokens/export.js.map +1 -1
  160. package/dist/io/formats/design-tokens/plan/index.d.ts.map +1 -1
  161. package/dist/io/formats/design-tokens/plan/index.js +4 -3
  162. package/dist/io/formats/design-tokens/plan/index.js.map +1 -1
  163. package/dist/io/formats/design-tokens/plan/styles.d.ts.map +1 -1
  164. package/dist/io/formats/design-tokens/plan/styles.js +9 -9
  165. package/dist/io/formats/design-tokens/plan/styles.js.map +1 -1
  166. package/dist/io/formats/design-tokens/styles.d.ts +4 -4
  167. package/dist/io/formats/design-tokens/styles.d.ts.map +1 -1
  168. package/dist/io/formats/design-tokens/styles.js +7 -7
  169. package/dist/io/formats/design-tokens/styles.js.map +1 -1
  170. package/dist/io/formats/design-tokens/sync/drift.js +2 -2
  171. package/dist/io/formats/design-tokens/sync/drift.js.map +1 -1
  172. package/dist/io/formats/design-tokens/values.d.ts +10 -5
  173. package/dist/io/formats/design-tokens/values.d.ts.map +1 -1
  174. package/dist/io/formats/design-tokens/values.js +13 -7
  175. package/dist/io/formats/design-tokens/values.js.map +1 -1
  176. package/dist/io/formats/drawio/label.js +1 -1
  177. package/dist/io/formats/drawio/paint.js +1 -1
  178. package/dist/io/formats/drawio/warnings.d.ts +17 -2
  179. package/dist/io/formats/drawio/warnings.d.ts.map +1 -1
  180. package/dist/io/formats/drawio/warnings.js +15 -8
  181. package/dist/io/formats/drawio/warnings.js.map +1 -1
  182. package/dist/io/formats/fig/export/index.d.ts.map +1 -1
  183. package/dist/io/formats/fig/export/index.js +15 -3
  184. package/dist/io/formats/fig/export/index.js.map +1 -1
  185. package/dist/io/formats/fig/export/patch/index.d.ts.map +1 -1
  186. package/dist/io/formats/fig/export/patch/index.js +2 -1
  187. package/dist/io/formats/fig/export/patch/index.js.map +1 -1
  188. package/dist/io/formats/fig/export/setup.d.ts +7 -2
  189. package/dist/io/formats/fig/export/setup.d.ts.map +1 -1
  190. package/dist/io/formats/fig/export/setup.js +12 -13
  191. package/dist/io/formats/fig/export/setup.js.map +1 -1
  192. package/dist/io/formats/fig/export/variables.d.ts.map +1 -1
  193. package/dist/io/formats/fig/export/variables.js +9 -7
  194. package/dist/io/formats/fig/export/variables.js.map +1 -1
  195. package/dist/io/formats/html/index.d.ts +1 -0
  196. package/dist/io/formats/html/index.d.ts.map +1 -1
  197. package/dist/io/formats/html/index.js +5 -3
  198. package/dist/io/formats/html/index.js.map +1 -1
  199. package/dist/io/formats/html/vectors.js +1 -0
  200. package/dist/io/formats/html/vectors.js.map +1 -1
  201. package/dist/io/formats/mermaid/layers.js +2 -2
  202. package/dist/io/formats/mermaid/layers.js.map +1 -1
  203. package/dist/io/formats/mermaid/styles.js +1 -1
  204. package/dist/io/formats/pdf/export.d.ts.map +1 -1
  205. package/dist/io/formats/pdf/export.js +1 -0
  206. package/dist/io/formats/pdf/export.js.map +1 -1
  207. package/dist/io/formats/pdf/prepare.d.ts +4 -4
  208. package/dist/io/formats/pdf/prepare.d.ts.map +1 -1
  209. package/dist/io/formats/pdf/prepare.js +2 -2
  210. package/dist/io/formats/pdf/prepare.js.map +1 -1
  211. package/dist/io/formats/pen/index.d.ts.map +1 -1
  212. package/dist/io/formats/pen/index.js +13 -2
  213. package/dist/io/formats/pen/index.js.map +1 -1
  214. package/dist/io/formats/pptx/style.js +1 -1
  215. package/dist/io/formats/raster/render.d.ts +1 -1
  216. package/dist/io/formats/raster/render.d.ts.map +1 -1
  217. package/dist/io/formats/raster/render.js +9 -4
  218. package/dist/io/formats/raster/render.js.map +1 -1
  219. package/dist/io/formats/svg/defs.d.ts +6 -3
  220. package/dist/io/formats/svg/defs.d.ts.map +1 -1
  221. package/dist/io/formats/svg/defs.js +12 -11
  222. package/dist/io/formats/svg/defs.js.map +1 -1
  223. package/dist/io/formats/svg/effects.js +2 -2
  224. package/dist/io/formats/svg/effects.js.map +1 -1
  225. package/dist/io/formats/svg/export.d.ts +5 -2
  226. package/dist/io/formats/svg/export.d.ts.map +1 -1
  227. package/dist/io/formats/svg/export.js +4 -2
  228. package/dist/io/formats/svg/export.js.map +1 -1
  229. package/dist/io/formats/svg/filter.d.ts +4 -1
  230. package/dist/io/formats/svg/filter.d.ts.map +1 -1
  231. package/dist/io/formats/svg/filter.js +6 -2
  232. package/dist/io/formats/svg/filter.js.map +1 -1
  233. package/dist/io/formats/svg/grain.js +1 -1
  234. package/dist/io/formats/svg/grain.js.map +1 -1
  235. package/dist/io/formats/svg/import.d.ts +4 -2
  236. package/dist/io/formats/svg/import.d.ts.map +1 -1
  237. package/dist/io/formats/svg/import.js +2 -1
  238. package/dist/io/formats/svg/import.js.map +1 -1
  239. package/dist/io/formats/svg/text/export.d.ts.map +1 -1
  240. package/dist/io/formats/svg/text/export.js +8 -8
  241. package/dist/io/formats/svg/text/export.js.map +1 -1
  242. package/dist/io/formats/svg/text/layout.js +2 -2
  243. package/dist/io/formats/svg/text/layout.js.map +1 -1
  244. package/dist/io/formats.d.ts.map +1 -1
  245. package/dist/io/formats.js +11 -4
  246. package/dist/io/formats.js.map +1 -1
  247. package/dist/io/index.d.ts +2 -2
  248. package/dist/io/subgraph.d.ts.map +1 -1
  249. package/dist/io/subgraph.js +1 -1
  250. package/dist/io/subgraph.js.map +1 -1
  251. package/dist/io/types.d.ts +12 -3
  252. package/dist/io/types.d.ts.map +1 -1
  253. package/dist/kiwi/fig/session/options.d.ts +3 -0
  254. package/dist/kiwi/fig/session/options.d.ts.map +1 -1
  255. package/dist/kiwi/fig/session/options.js +4 -0
  256. package/dist/kiwi/fig/session/options.js.map +1 -1
  257. package/dist/layout/yoga-helpers.d.ts +2 -1
  258. package/dist/layout/yoga-helpers.d.ts.map +1 -1
  259. package/dist/layout/yoga-helpers.js +7 -1
  260. package/dist/layout/yoga-helpers.js.map +1 -1
  261. package/dist/layout.js +24 -1
  262. package/dist/layout.js.map +1 -1
  263. package/dist/lint/fixes.js +1 -1
  264. package/dist/lint/linter.js +2 -2
  265. package/dist/lint/linter.js.map +1 -1
  266. package/dist/pairdraw-api/comments.d.ts +4 -1
  267. package/dist/pairdraw-api/comments.d.ts.map +1 -1
  268. package/dist/pairdraw-api/comments.js +5 -0
  269. package/dist/pairdraw-api/comments.js.map +1 -1
  270. package/dist/pairdraw-api/index.d.ts +3 -3
  271. package/dist/pairdraw-api/index.d.ts.map +1 -1
  272. package/dist/pairdraw-api/index.js +5 -5
  273. package/dist/pairdraw-api/index.js.map +1 -1
  274. package/dist/pairdraw-api/nodes.d.ts +1 -1
  275. package/dist/prototype/scene.js +1 -1
  276. package/dist/rpc/analyze-commands.js +1 -1
  277. package/dist/rpc/read-commands.d.ts +2 -2
  278. package/dist/rpc/read-commands.js +3 -3
  279. package/dist/rpc/read-commands.js.map +1 -1
  280. package/dist/rpc/variables-command.js +2 -2
  281. package/dist/rpc/variables-command.js.map +1 -1
  282. package/dist/text/font/provider.d.ts +15 -0
  283. package/dist/text/font/provider.d.ts.map +1 -0
  284. package/dist/text/font/provider.js +18 -0
  285. package/dist/text/font/provider.js.map +1 -0
  286. package/dist/text/font/readiness.d.ts +32 -0
  287. package/dist/text/font/readiness.d.ts.map +1 -0
  288. package/dist/text/font/{status.js → readiness.js} +8 -4
  289. package/dist/text/font/readiness.js.map +1 -0
  290. package/dist/text/index.d.ts +4 -3
  291. package/dist/text/index.js +4 -3
  292. package/dist/text/prepare.d.ts +9 -4
  293. package/dist/text/prepare.d.ts.map +1 -1
  294. package/dist/text/prepare.js +9 -4
  295. package/dist/text/prepare.js.map +1 -1
  296. package/dist/tools/analyze/colors.js +1 -1
  297. package/dist/tools/analyze/responsive/index.js +7 -18
  298. package/dist/tools/analyze/responsive/index.js.map +1 -1
  299. package/dist/tools/analyze/responsive/widths.d.ts +27 -0
  300. package/dist/tools/analyze/responsive/widths.d.ts.map +1 -0
  301. package/dist/tools/analyze/responsive/widths.js +49 -0
  302. package/dist/tools/analyze/responsive/widths.js.map +1 -0
  303. package/dist/tools/analyze.d.ts +2 -1
  304. package/dist/tools/analyze.js +2 -1
  305. package/dist/tools/codegen/tokens.d.ts.map +1 -1
  306. package/dist/tools/codegen/tokens.js +2 -2
  307. package/dist/tools/codegen/tokens.js.map +1 -1
  308. package/dist/tools/comments.d.ts.map +1 -1
  309. package/dist/tools/comments.js +2 -2
  310. package/dist/tools/comments.js.map +1 -1
  311. package/dist/tools/component-catalog.d.ts.map +1 -1
  312. package/dist/tools/component-catalog.js +5 -3
  313. package/dist/tools/component-catalog.js.map +1 -1
  314. package/dist/tools/create/basic.js +1 -1
  315. package/dist/tools/create/behaviours.js +1 -1
  316. package/dist/tools/create/html.d.ts.map +1 -1
  317. package/dist/tools/create/html.js +1 -3
  318. package/dist/tools/create/html.js.map +1 -1
  319. package/dist/tools/create/icons.js +2 -2
  320. package/dist/tools/create/icons.js.map +1 -1
  321. package/dist/tools/create/mermaid.js +1 -1
  322. package/dist/tools/create/render.js +1 -1
  323. package/dist/tools/create/svg.js +5 -2
  324. package/dist/tools/create/svg.js.map +1 -1
  325. package/dist/tools/create/vector.js +3 -3
  326. package/dist/tools/create/vector.js.map +1 -1
  327. package/dist/tools/css/shorthand.d.ts +20 -0
  328. package/dist/tools/css/shorthand.d.ts.map +1 -0
  329. package/dist/tools/css/shorthand.js +54 -0
  330. package/dist/tools/css/shorthand.js.map +1 -0
  331. package/dist/tools/describe/index.js +2 -2
  332. package/dist/tools/describe/index.js.map +1 -1
  333. package/dist/tools/describe/issues.js +1 -1
  334. package/dist/tools/html-host.d.ts.map +1 -1
  335. package/dist/tools/html-host.js +5 -3
  336. package/dist/tools/html-host.js.map +1 -1
  337. package/dist/tools/image-ai/apply.d.ts.map +1 -1
  338. package/dist/tools/image-ai/apply.js +1 -3
  339. package/dist/tools/image-ai/apply.js.map +1 -1
  340. package/dist/tools/image-ai/generate.js +1 -1
  341. package/dist/tools/image-ai/service.d.ts.map +1 -1
  342. package/dist/tools/image-ai/service.js +5 -3
  343. package/dist/tools/image-ai/service.js.map +1 -1
  344. package/dist/tools/index.d.ts +2 -1
  345. package/dist/tools/index.js +2 -1
  346. package/dist/tools/modify/effects.js +1 -1
  347. package/dist/tools/modify/effects.js.map +1 -1
  348. package/dist/tools/modify/geometry.d.ts.map +1 -1
  349. package/dist/tools/modify/geometry.js +14 -3
  350. package/dist/tools/modify/geometry.js.map +1 -1
  351. package/dist/tools/modify/layout.d.ts.map +1 -1
  352. package/dist/tools/modify/layout.js +35 -8
  353. package/dist/tools/modify/layout.js.map +1 -1
  354. package/dist/tools/modify/matching.d.ts.map +1 -1
  355. package/dist/tools/modify/matching.js +10 -10
  356. package/dist/tools/modify/matching.js.map +1 -1
  357. package/dist/tools/modify/paint.d.ts.map +1 -1
  358. package/dist/tools/modify/paint.js +57 -5
  359. package/dist/tools/modify/paint.js.map +1 -1
  360. package/dist/tools/modify/reactions.d.ts.map +1 -1
  361. package/dist/tools/modify/reactions.js +2 -2
  362. package/dist/tools/modify/reactions.js.map +1 -1
  363. package/dist/tools/modify/text.d.ts.map +1 -1
  364. package/dist/tools/modify/text.js +3 -3
  365. package/dist/tools/modify/text.js.map +1 -1
  366. package/dist/tools/prompts/codegen.js +1 -1
  367. package/dist/tools/prompts/codegen.js.map +1 -1
  368. package/dist/tools/read/css.d.ts +14 -0
  369. package/dist/tools/read/css.d.ts.map +1 -0
  370. package/dist/tools/read/css.js +306 -0
  371. package/dist/tools/read/css.js.map +1 -0
  372. package/dist/tools/read/libraries.js +1 -1
  373. package/dist/tools/read/reactions.js +1 -1
  374. package/dist/tools/read/reactions.js.map +1 -1
  375. package/dist/tools/read/space.d.ts.map +1 -1
  376. package/dist/tools/read/space.js +0 -2
  377. package/dist/tools/read/space.js.map +1 -1
  378. package/dist/tools/read.d.ts +2 -1
  379. package/dist/tools/read.js +2 -1
  380. package/dist/tools/registry/core.d.ts +1 -1
  381. package/dist/tools/registry/core.js +3 -1
  382. package/dist/tools/registry/core.js.map +1 -1
  383. package/dist/tools/schema.d.ts +6 -4
  384. package/dist/tools/schema.d.ts.map +1 -1
  385. package/dist/tools/schema.js +9 -5
  386. package/dist/tools/schema.js.map +1 -1
  387. package/dist/tools/script/host.d.ts.map +1 -1
  388. package/dist/tools/script/host.js +5 -3
  389. package/dist/tools/script/host.js.map +1 -1
  390. package/dist/tools/variables/collections.js +1 -1
  391. package/dist/tools/variables/collections.js.map +1 -1
  392. package/dist/tools/variables/values.d.ts.map +1 -1
  393. package/dist/tools/variables/values.js +4 -4
  394. package/dist/tools/variables/values.js.map +1 -1
  395. package/dist/tools/vector/vectorize.d.ts.map +1 -1
  396. package/dist/tools/vector/vectorize.js +6 -4
  397. package/dist/tools/vector/vectorize.js.map +1 -1
  398. package/dist/tools/video-host.d.ts.map +1 -1
  399. package/dist/tools/video-host.js +5 -3
  400. package/dist/tools/video-host.js.map +1 -1
  401. package/dist/vector/vectorize/svg/gradients.d.ts +2 -2
  402. package/dist/vector/vectorize/svg/gradients.d.ts.map +1 -1
  403. package/dist/vector/vectorize/svg/gradients.js +5 -5
  404. package/dist/vector/vectorize/svg/gradients.js.map +1 -1
  405. package/dist/vector/vectorize/svg/to-vectors.d.ts +3 -1
  406. package/dist/vector/vectorize/svg/to-vectors.d.ts.map +1 -1
  407. package/dist/vector/vectorize/svg/to-vectors.js +13 -12
  408. package/dist/vector/vectorize/svg/to-vectors.js.map +1 -1
  409. package/package.json +9 -9
  410. package/src/canvas/noise/render.ts +1 -1
  411. package/src/canvas/noise/shader.ts +13 -5
  412. package/src/canvas/noise/tile.ts +2 -1
  413. package/src/canvas/renderer/colors.ts +76 -50
  414. package/src/canvas/renderer/document-surface.ts +53 -0
  415. package/src/canvas/renderer/fonts.ts +6 -4
  416. package/src/canvas/renderer/lifecycle.ts +4 -4
  417. package/src/canvas/renderer/methods.ts +1 -0
  418. package/src/canvas/renderer/pipeline.ts +21 -3
  419. package/src/canvas/renderer/retained-backing.ts +2 -1
  420. package/src/canvas/renderer/tiles/surface-pool.ts +9 -7
  421. package/src/canvas/renderer.ts +36 -11
  422. package/src/canvas/scene.ts +4 -3
  423. package/src/canvas/shaders/compile.ts +14 -3
  424. package/src/canvas/shaders/draw.ts +11 -4
  425. package/src/canvas/shaders/effect.ts +8 -19
  426. package/src/canvas/shadows/shape.ts +4 -2
  427. package/src/canvas/shadows.ts +5 -2
  428. package/src/canvas/text/decorations.ts +15 -5
  429. package/src/canvas/text/index.ts +9 -1
  430. package/src/canvas/text/paragraph/index.ts +16 -6
  431. package/src/canvas/text/renderer.ts +2 -1
  432. package/src/canvas/text/shape.ts +4 -4
  433. package/src/canvas/texture.ts +2 -1
  434. package/src/editor/clipboard/assets.ts +6 -2
  435. package/src/editor/clipboard/component-matches.ts +65 -0
  436. package/src/editor/clipboard/dependencies.ts +22 -1
  437. package/src/editor/clipboard/export.ts +2 -2
  438. package/src/editor/clipboard.ts +74 -20
  439. package/src/editor/components/properties.ts +3 -2
  440. package/src/editor/eyedropper.ts +14 -4
  441. package/src/editor/history/atomic-tool.ts +3 -2
  442. package/src/editor/structure/state.ts +2 -1
  443. package/src/editor/text.ts +2 -1
  444. package/src/editor/variables.ts +3 -3
  445. package/src/figma-api/fresh-read.ts +57 -0
  446. package/src/figma-api/graph-ref.ts +13 -0
  447. package/src/figma-api/index.ts +12 -4
  448. package/src/figma-api/pending-layout.ts +7 -3
  449. package/src/figma-api/pending-sync.ts +4 -1
  450. package/src/figma-api/proxy.ts +2 -1
  451. package/src/figma-api/reactions.ts +91 -10
  452. package/src/figma-api/variables/index.ts +5 -4
  453. package/src/io/formats/design-tokens/css/known.ts +1 -1
  454. package/src/io/formats/design-tokens/css/read.ts +20 -7
  455. package/src/io/formats/design-tokens/css/sync.ts +9 -4
  456. package/src/io/formats/design-tokens/css/values.ts +37 -9
  457. package/src/io/formats/design-tokens/decode.ts +17 -12
  458. package/src/io/formats/design-tokens/export.ts +3 -3
  459. package/src/io/formats/design-tokens/plan/index.ts +6 -5
  460. package/src/io/formats/design-tokens/plan/styles.ts +37 -10
  461. package/src/io/formats/design-tokens/styles.ts +10 -7
  462. package/src/io/formats/design-tokens/sync/drift.ts +6 -4
  463. package/src/io/formats/design-tokens/values.ts +15 -8
  464. package/src/io/formats/drawio/warnings.ts +28 -9
  465. package/src/io/formats/fig/export/index.ts +36 -3
  466. package/src/io/formats/fig/export/patch/index.ts +4 -1
  467. package/src/io/formats/fig/export/setup.ts +25 -15
  468. package/src/io/formats/fig/export/variables.ts +17 -6
  469. package/src/io/formats/html/index.ts +9 -3
  470. package/src/io/formats/html/vectors.ts +1 -0
  471. package/src/io/formats/mermaid/layers.ts +2 -2
  472. package/src/io/formats/pdf/export.ts +1 -0
  473. package/src/io/formats/pdf/prepare.ts +6 -6
  474. package/src/io/formats/pen/index.ts +15 -4
  475. package/src/io/formats/raster/render.ts +12 -4
  476. package/src/io/formats/svg/defs.ts +26 -14
  477. package/src/io/formats/svg/effects.ts +2 -2
  478. package/src/io/formats/svg/export.ts +17 -3
  479. package/src/io/formats/svg/filter.ts +12 -2
  480. package/src/io/formats/svg/grain.ts +1 -1
  481. package/src/io/formats/svg/import.ts +6 -3
  482. package/src/io/formats/svg/text/export.ts +10 -8
  483. package/src/io/formats/svg/text/layout.ts +2 -2
  484. package/src/io/formats.ts +18 -5
  485. package/src/io/index.ts +1 -0
  486. package/src/io/subgraph.ts +4 -1
  487. package/src/io/types.ts +10 -0
  488. package/src/kiwi/fig/session/options.ts +4 -1
  489. package/src/layout/yoga-helpers.ts +8 -0
  490. package/src/layout.ts +47 -1
  491. package/src/lint/linter.ts +1 -1
  492. package/src/pairdraw-api/comments.ts +6 -0
  493. package/src/pairdraw-api/index.ts +7 -9
  494. package/src/rpc/read-commands.ts +4 -4
  495. package/src/rpc/variables-command.ts +2 -2
  496. package/src/text/font/provider.ts +26 -0
  497. package/src/text/font/{status.ts → readiness.ts} +13 -9
  498. package/src/text/index.ts +2 -1
  499. package/src/text/prepare.ts +9 -4
  500. package/src/tools/analyze/responsive/index.ts +8 -15
  501. package/src/tools/analyze/responsive/widths.ts +63 -0
  502. package/src/tools/analyze.ts +2 -0
  503. package/src/tools/codegen/tokens.ts +4 -2
  504. package/src/tools/comments.ts +6 -4
  505. package/src/tools/component-catalog.ts +5 -3
  506. package/src/tools/create/html.ts +0 -3
  507. package/src/tools/create/icons.ts +1 -1
  508. package/src/tools/create/svg.ts +4 -1
  509. package/src/tools/create/vector.ts +2 -2
  510. package/src/tools/css/shorthand.ts +64 -0
  511. package/src/tools/describe/index.ts +2 -8
  512. package/src/tools/html-host.ts +5 -3
  513. package/src/tools/image-ai/apply.ts +0 -2
  514. package/src/tools/image-ai/service.ts +5 -3
  515. package/src/tools/index.ts +2 -0
  516. package/src/tools/modify/effects.ts +1 -1
  517. package/src/tools/modify/geometry.ts +16 -3
  518. package/src/tools/modify/layout.ts +47 -13
  519. package/src/tools/modify/matching.ts +14 -11
  520. package/src/tools/modify/paint.ts +85 -5
  521. package/src/tools/modify/reactions.ts +3 -2
  522. package/src/tools/modify/text.ts +15 -11
  523. package/src/tools/prompts/codegen.md +2 -1
  524. package/src/tools/read/css.ts +365 -0
  525. package/src/tools/read/reactions.ts +3 -2
  526. package/src/tools/read/space.ts +0 -2
  527. package/src/tools/read.ts +1 -0
  528. package/src/tools/registry/core.ts +3 -2
  529. package/src/tools/schema.ts +14 -5
  530. package/src/tools/script/host.ts +6 -3
  531. package/src/tools/variables/collections.ts +1 -1
  532. package/src/tools/variables/values.ts +16 -5
  533. package/src/tools/vector/vectorize.ts +10 -4
  534. package/src/tools/video-host.ts +5 -3
  535. package/src/vector/vectorize/svg/gradients.ts +8 -5
  536. package/src/vector/vectorize/svg/to-vectors.ts +48 -14
  537. package/dist/text/font/status.d.ts +0 -28
  538. package/dist/text/font/status.d.ts.map +0 -1
  539. package/dist/text/font/status.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"export.js","names":[],"sources":["../../../../src/io/formats/pdf/export.ts"],"sourcesContent":["import type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { computeContentBounds } from '#core/io/formats/raster'\nimport { renderNodesToSVG, type SVGExportOptions, type SVGTextLayout } from '#core/io/formats/svg'\n\nimport { loadSVG2PDF, withPDFDOM, type SVGPageParser } from './dom'\nimport {\n cutFontInstances,\n embeddedFontAlias,\n planFontEmbedding,\n registerEmbeddedFonts,\n type PDFFallbackFontFile,\n type PDFFontFace,\n type PDFFontReport\n} from './fonts'\nimport type { PDFPageSpec } from './plan'\n\nexport interface PDFExportOptions {\n title?: string\n /** The faces the text uses, to embed their files; without them text uses standard PDF fonts. */\n fonts?: readonly PDFFontFace[]\n /** Line breaks of text nodes as the editor laid them out, so paragraphs stay wrapped. */\n textLayout?: SVGTextLayout\n /** The files of fallback faces the text layout draws characters in, to embed them too. */\n fallbackFile?: PDFFallbackFontFile\n}\n\nexport interface PDFExportResult {\n data: Uint8Array\n /** The pages written, in order. Pages with nothing visible are skipped. */\n pages: Array<{ label?: string; width: number; height: number }>\n /** Embedded and fallback faces, when `fonts` was given. */\n fonts?: PDFFontReport\n}\n\ninterface PreparedPage {\n spec: PDFPageSpec\n svgElement: Element\n width: number\n height: number\n}\n\ntype PageSVGOptions = Pick<SVGExportOptions, 'textLayout' | 'fontAlias'>\n\nfunction preparePage(\n graph: SceneGraph,\n spec: PDFPageSpec,\n svgOptions: PageSVGOptions,\n parse: SVGPageParser\n): PreparedPage | null {\n const svg = renderNodesToSVG(graph, spec.pageId, spec.nodeIds, {\n xmlDeclaration: false,\n ...svgOptions\n })\n if (!svg) return null\n\n const bounds = computeContentBounds(graph, spec.nodeIds)\n if (!bounds) return null\n\n const width = bounds.maxX - bounds.minX\n const height = bounds.maxY - bounds.minY\n if (width <= 0 || height <= 0) return null\n\n const svgElement = parse(svg)\n return svgElement ? { spec, svgElement, width, height } : null\n}\n\nconst orientationOf = (page: PreparedPage) => (page.width > page.height ? 'landscape' : 'portrait')\n\n/**\n * A PDF with one page per spec, each sized to its content. Null when no page has anything visible.\n */\nexport function renderPagesToPDFDetailed(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[],\n options: PDFExportOptions = {}\n): Promise<PDFExportResult | null> {\n return withPDFDOM((parse) => renderPages(graph, specs, options, parse))\n}\n\nasync function renderPages(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[],\n options: PDFExportOptions,\n parse: SVGPageParser\n): Promise<PDFExportResult | null> {\n const embedding = options.fonts ? planFontEmbedding(options.fonts, options.fallbackFile) : null\n const svgOptions: PageSVGOptions = {\n textLayout: options.textLayout,\n fontAlias: embedding ? embeddedFontAlias(embedding) : undefined\n }\n const preparePages = () =>\n specs\n .map((spec) => preparePage(graph, spec, svgOptions, parse))\n .filter((page): page is PreparedPage => page !== null)\n let prepared = preparePages()\n if (prepared.length === 0) return null\n const first = prepared[0]\n\n const { jsPDF } = await import('jspdf')\n const svg2pdf = await loadSVG2PDF()\n\n const doc = new jsPDF({\n orientation: orientationOf(first),\n unit: 'pt',\n format: [first.width, first.height],\n compress: true\n })\n\n if (options.title) {\n doc.setProperties({ title: options.title })\n }\n\n // The pages name the variable instances they draw, which are cut now. jsPDF reads a font file\n // when it is registered, so a face it refuses is only known then. Either way, the pages are\n // written again without the names of faces that are not embedded.\n if (embedding) {\n const cut = await cutFontInstances(embedding)\n if (!registerEmbeddedFonts(doc, embedding) || !cut) prepared = preparePages()\n }\n\n for (const [index, page] of prepared.entries()) {\n if (index > 0) doc.addPage([page.width, page.height], orientationOf(page))\n await svg2pdf(page.svgElement, doc, { x: 0, y: 0, width: page.width, height: page.height })\n }\n\n return {\n data: new Uint8Array(doc.output('arraybuffer')),\n pages: prepared.map((page) => ({\n label: page.spec.label,\n width: page.width,\n height: page.height\n })),\n ...(embedding ? { fonts: embedding.report } : {})\n }\n}\n"],"mappings":";;;;;AA4CA,SAAS,YACP,OACA,MACA,YACA,OACqB;CACrB,MAAM,MAAM,iBAAiB,OAAO,KAAK,QAAQ,KAAK,SAAS;EAC7D,gBAAgB;EAChB,GAAG;CACL,CAAC;CACD,IAAI,CAAC,KAAK,OAAO;CAEjB,MAAM,SAAS,qBAAqB,OAAO,KAAK,OAAO;CACvD,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,QAAQ,OAAO,OAAO,OAAO;CACnC,MAAM,SAAS,OAAO,OAAO,OAAO;CACpC,IAAI,SAAS,KAAK,UAAU,GAAG,OAAO;CAEtC,MAAM,aAAa,MAAM,GAAG;CAC5B,OAAO,aAAa;EAAE;EAAM;EAAY;EAAO;CAAO,IAAI;AAC5D;AAEA,MAAM,iBAAiB,SAAwB,KAAK,QAAQ,KAAK,SAAS,cAAc;;;;AAKxF,SAAgB,yBACd,OACA,OACA,UAA4B,CAAC,GACI;CACjC,OAAO,YAAY,UAAU,YAAY,OAAO,OAAO,SAAS,KAAK,CAAC;AACxE;AAEA,eAAe,YACb,OACA,OACA,SACA,OACiC;CACjC,MAAM,YAAY,QAAQ,QAAQ,kBAAkB,QAAQ,OAAO,QAAQ,YAAY,IAAI;CAC3F,MAAM,aAA6B;EACjC,YAAY,QAAQ;EACpB,WAAW,YAAY,kBAAkB,SAAS,IAAI,KAAA;CACxD;CACA,MAAM,qBACJ,MACG,KAAK,SAAS,YAAY,OAAO,MAAM,YAAY,KAAK,CAAC,CAAC,CAC1D,QAAQ,SAA+B,SAAS,IAAI;CACzD,IAAI,WAAW,aAAa;CAC5B,IAAI,SAAS,WAAW,GAAG,OAAO;CAClC,MAAM,QAAQ,SAAS;CAEvB,MAAM,EAAE,UAAU,MAAM,OAAO;CAC/B,MAAM,UAAU,MAAM,YAAY;CAElC,MAAM,MAAM,IAAI,MAAM;EACpB,aAAa,cAAc,KAAK;EAChC,MAAM;EACN,QAAQ,CAAC,MAAM,OAAO,MAAM,MAAM;EAClC,UAAU;CACZ,CAAC;CAED,IAAI,QAAQ,OACV,IAAI,cAAc,EAAE,OAAO,QAAQ,MAAM,CAAC;CAM5C,IAAI,WAAW;EACb,MAAM,MAAM,MAAM,iBAAiB,SAAS;EAC5C,IAAI,CAAC,sBAAsB,KAAK,SAAS,KAAK,CAAC,KAAK,WAAW,aAAa;CAC9E;CAEA,KAAK,MAAM,CAAC,OAAO,SAAS,SAAS,QAAQ,GAAG;EAC9C,IAAI,QAAQ,GAAG,IAAI,QAAQ,CAAC,KAAK,OAAO,KAAK,MAAM,GAAG,cAAc,IAAI,CAAC;EACzE,MAAM,QAAQ,KAAK,YAAY,KAAK;GAAE,GAAG;GAAG,GAAG;GAAG,OAAO,KAAK;GAAO,QAAQ,KAAK;EAAO,CAAC;CAC5F;CAEA,OAAO;EACL,MAAM,IAAI,WAAW,IAAI,OAAO,aAAa,CAAC;EAC9C,OAAO,SAAS,KAAK,UAAU;GAC7B,OAAO,KAAK,KAAK;GACjB,OAAO,KAAK;GACZ,QAAQ,KAAK;EACf,EAAE;EACF,GAAI,YAAY,EAAE,OAAO,UAAU,OAAO,IAAI,CAAC;CACjD;AACF"}
1
+ {"version":3,"file":"export.js","names":[],"sources":["../../../../src/io/formats/pdf/export.ts"],"sourcesContent":["import type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { computeContentBounds } from '#core/io/formats/raster'\nimport { renderNodesToSVG, type SVGExportOptions, type SVGTextLayout } from '#core/io/formats/svg'\n\nimport { loadSVG2PDF, withPDFDOM, type SVGPageParser } from './dom'\nimport {\n cutFontInstances,\n embeddedFontAlias,\n planFontEmbedding,\n registerEmbeddedFonts,\n type PDFFallbackFontFile,\n type PDFFontFace,\n type PDFFontReport\n} from './fonts'\nimport type { PDFPageSpec } from './plan'\n\nexport interface PDFExportOptions {\n title?: string\n /** The faces the text uses, to embed their files; without them text uses standard PDF fonts. */\n fonts?: readonly PDFFontFace[]\n /** Line breaks of text nodes as the editor laid them out, so paragraphs stay wrapped. */\n textLayout?: SVGTextLayout\n /** The files of fallback faces the text layout draws characters in, to embed them too. */\n fallbackFile?: PDFFallbackFontFile\n}\n\nexport interface PDFExportResult {\n data: Uint8Array\n /** The pages written, in order. Pages with nothing visible are skipped. */\n pages: Array<{ label?: string; width: number; height: number }>\n /** Embedded and fallback faces, when `fonts` was given. */\n fonts?: PDFFontReport\n}\n\ninterface PreparedPage {\n spec: PDFPageSpec\n svgElement: Element\n width: number\n height: number\n}\n\ntype PageSVGOptions = Pick<SVGExportOptions, 'textLayout' | 'fontAlias'>\n\nfunction preparePage(\n graph: SceneGraph,\n spec: PDFPageSpec,\n svgOptions: PageSVGOptions,\n parse: SVGPageParser\n): PreparedPage | null {\n const svg = renderNodesToSVG(graph, spec.pageId, spec.nodeIds, {\n xmlDeclaration: false,\n documentColorSpace: graph.documentColorSpace,\n ...svgOptions\n })\n if (!svg) return null\n\n const bounds = computeContentBounds(graph, spec.nodeIds)\n if (!bounds) return null\n\n const width = bounds.maxX - bounds.minX\n const height = bounds.maxY - bounds.minY\n if (width <= 0 || height <= 0) return null\n\n const svgElement = parse(svg)\n return svgElement ? { spec, svgElement, width, height } : null\n}\n\nconst orientationOf = (page: PreparedPage) => (page.width > page.height ? 'landscape' : 'portrait')\n\n/**\n * A PDF with one page per spec, each sized to its content. Null when no page has anything visible.\n */\nexport function renderPagesToPDFDetailed(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[],\n options: PDFExportOptions = {}\n): Promise<PDFExportResult | null> {\n return withPDFDOM((parse) => renderPages(graph, specs, options, parse))\n}\n\nasync function renderPages(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[],\n options: PDFExportOptions,\n parse: SVGPageParser\n): Promise<PDFExportResult | null> {\n const embedding = options.fonts ? planFontEmbedding(options.fonts, options.fallbackFile) : null\n const svgOptions: PageSVGOptions = {\n textLayout: options.textLayout,\n fontAlias: embedding ? embeddedFontAlias(embedding) : undefined\n }\n const preparePages = () =>\n specs\n .map((spec) => preparePage(graph, spec, svgOptions, parse))\n .filter((page): page is PreparedPage => page !== null)\n let prepared = preparePages()\n if (prepared.length === 0) return null\n const first = prepared[0]\n\n const { jsPDF } = await import('jspdf')\n const svg2pdf = await loadSVG2PDF()\n\n const doc = new jsPDF({\n orientation: orientationOf(first),\n unit: 'pt',\n format: [first.width, first.height],\n compress: true\n })\n\n if (options.title) {\n doc.setProperties({ title: options.title })\n }\n\n // The pages name the variable instances they draw, which are cut now. jsPDF reads a font file\n // when it is registered, so a face it refuses is only known then. Either way, the pages are\n // written again without the names of faces that are not embedded.\n if (embedding) {\n const cut = await cutFontInstances(embedding)\n if (!registerEmbeddedFonts(doc, embedding) || !cut) prepared = preparePages()\n }\n\n for (const [index, page] of prepared.entries()) {\n if (index > 0) doc.addPage([page.width, page.height], orientationOf(page))\n await svg2pdf(page.svgElement, doc, { x: 0, y: 0, width: page.width, height: page.height })\n }\n\n return {\n data: new Uint8Array(doc.output('arraybuffer')),\n pages: prepared.map((page) => ({\n label: page.spec.label,\n width: page.width,\n height: page.height\n })),\n ...(embedding ? { fonts: embedding.report } : {})\n }\n}\n"],"mappings":";;;;;AA4CA,SAAS,YACP,OACA,MACA,YACA,OACqB;CACrB,MAAM,MAAM,iBAAiB,OAAO,KAAK,QAAQ,KAAK,SAAS;EAC7D,gBAAgB;EAChB,oBAAoB,MAAM;EAC1B,GAAG;CACL,CAAC;CACD,IAAI,CAAC,KAAK,OAAO;CAEjB,MAAM,SAAS,qBAAqB,OAAO,KAAK,OAAO;CACvD,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,QAAQ,OAAO,OAAO,OAA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IAAI,QAAQ,CAAC,KAAK,OAAO,KAAK,MAAM,GAAG,cAAc,IAAI,CAAC;EACzE,MAAM,QAAQ,KAAK,YAAY,KAAK;GAAE,GAAG;GAAG,GAAG;GAAG,OAAO,KAAK;GAAO,QAAQ,KAAK;EAAO,CAAC;CAC5F;CAEA,OAAO;EACL,MAAM,IAAI,WAAW,IAAI,OAAO,aAAa,CAAC;EAC9C,OAAO,SAAS,KAAK,UAAU;GAC7B,OAAO,KAAK,KAAK;GACjB,OAAO,KAAK;GACZ,QAAQ,KAAK;EACf,EAAE;EACF,GAAI,YAAY,EAAE,OAAO,UAAU,OAAO,IAAI,CAAC;CACjD;AACF"}
@@ -1,4 +1,4 @@
1
- import { DocumentFontStatus } from "../../../text/font/status.js";
1
+ import { FontReadiness } from "../../../text/font/readiness.js";
2
2
  import { SVGTextLayout } from "../svg/text/lines.js";
3
3
  import "../svg/index.js";
4
4
  import { PDFFontFace } from "./fonts.js";
@@ -10,7 +10,7 @@ import { SceneGraph } from "@pairdraw/scene-graph";
10
10
  * characters remote fonts must cover, and the script and emoji fallbacks. Fonts loaded for some
11
11
  * characters only cover the ones jsPDF writes too.
12
12
  */
13
- declare function preparePDFFonts(graph: SceneGraph, specs: readonly PDFPageSpec[]): Promise<DocumentFontStatus>;
13
+ declare function preparePDFFonts(graph: SceneGraph, specs: readonly PDFPageSpec[]): Promise<FontReadiness>;
14
14
  /**
15
15
  * Design pages other than the open one may still be unread, since `.fig` pages load on demand.
16
16
  * Reads the pages a `pages` export asks for, or every page, so planning sees their layers.
@@ -20,9 +20,9 @@ declare function readPDFPages(graph: SceneGraph, pageIds?: readonly string[]): v
20
20
  * Loads the fonts the text of pages read by {@link readPDFPages} needs and lays them out, since
21
21
  * pages other than the open one have no layout yet, so every PDF page is complete.
22
22
  */
23
- declare function preparePagesForPDF(graph: SceneGraph, specs: readonly PDFPageSpec[]): Promise<DocumentFontStatus>;
23
+ declare function preparePagesForPDF(graph: SceneGraph, specs: readonly PDFPageSpec[]): Promise<FontReadiness>;
24
24
  /** The faces the pages' text uses, with the files the canvas draws them from. */
25
- declare function pdfFontFaces(status: DocumentFontStatus): PDFFontFace[];
25
+ declare function pdfFontFaces(status: FontReadiness): PDFFontFace[];
26
26
  /**
27
27
  * Runs `render` with the line breaks the canvas gives each text node (same paragraph builder and
28
28
  * fonts), so a wrapped paragraph stays wrapped in the PDF. Without CanvasKit, `render` gets no
@@ -1 +1 @@
1
- {"version":3,"file":"prepare.d.ts","names":[],"sources":["../../../../src/io/formats/pdf/prepare.ts"],"mappings":";;;;;;;;;;;;iBA2BsB,gBACpB,OAAO,YACP,gBAAgB,gBACf,QAAQ;;;;;iBA4BK,aAAa,OAAO,YAAY;;;;;iBAY1B,mBACpB,OAAO,YACP,gBAAgB,gBACf,QAAQ;;iBASK,aAAa,QAAQ,qBAAqB;;;;;;iBAgBpC,kBAAkB,GACtC,SAAS,YAAY,8BAA8B,QAAQ,KAC1D,QAAQ"}
1
+ {"version":3,"file":"prepare.d.ts","names":[],"sources":["../../../../src/io/formats/pdf/prepare.ts"],"mappings":";;;;;;;;;;;;iBA2BsB,gBACpB,OAAO,YACP,gBAAgB,gBACf,QAAQ;;;;;iBA4BK,aAAa,OAAO,YAAY;;;;;iBAY1B,mBACpB,OAAO,YACP,gBAAgB,gBACf,QAAQ;;iBASK,aAAa,QAAQ,gBAAgB;;;;;;iBAgB/B,kBAAkB,GACtC,SAAS,YAAY,8BAA8B,QAAQ,KAC1D,QAAQ"}
@@ -6,7 +6,7 @@ import { collectGraphFontRequirements } from "../../../text/requirements/collect
6
6
  import { fontManager } from "../../../text/font/manager.js";
7
7
  import { characterFace } from "../../../canvas/text/placed.js";
8
8
  import { withTextShaper } from "../../../canvas/text/shape.js";
9
- import { prepareGraphFonts } from "../../../text/prepare.js";
9
+ import { resolveFontReadiness } from "../../../text/prepare.js";
10
10
  import { populateFigPage } from "../../../kiwi/fig/session/document-state.js";
11
11
  import { computeAllLayouts } from "../../../layout.js";
12
12
  import { uniq } from "es-toolkit";
@@ -18,7 +18,7 @@ import { uniq } from "es-toolkit";
18
18
  */
19
19
  async function preparePDFFonts(graph, specs) {
20
20
  const nodeIds = specs.flatMap((spec) => spec.nodeIds);
21
- return prepareGraphFonts(graph, nodeIds, await pdfWrittenCharacters(graph, nodeIds));
21
+ return resolveFontReadiness(graph, nodeIds, await pdfWrittenCharacters(graph, nodeIds));
22
22
  }
23
23
  /**
24
24
  * Characters jsPDF writes for the text besides its own: it writes Arabic letters as their
@@ -1 +1 @@
1
- {"version":3,"file":"prepare.js","names":[],"sources":["../../../../src/io/formats/pdf/prepare.ts"],"sourcesContent":["import { uniq } from 'es-toolkit'\n\nimport type { ShapedTextGlyph } from '@pairdraw/fig/node-change'\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\nimport { characterFace } from '#core/canvas/text/placed'\nimport { withTextShaper } from '#core/canvas/text/shape'\nimport { getCanvasKit } from '#core/canvaskit'\nimport { populateFigPage } from '#core/io/formats/fig'\nimport type { SVGCharacterEdges, SVGFallbackFace, SVGTextLayout } from '#core/io/formats/svg'\nimport { computeAllLayouts } from '#core/layout'\nimport { shownText } from '#core/text/case'\nimport { EMOJI_METRICS_FAMILY } from '#core/text/emoji'\nimport { ARABIC_CHARACTER } from '#core/text/fallbacks'\nimport { fontManager } from '#core/text/font/manager'\nimport type { DocumentFontStatus } from '#core/text/font/status'\nimport { prepareGraphFonts } from '#core/text/prepare'\nimport { collectGraphFontRequirements } from '#core/text/requirements/collect'\n\nimport type { PDFFontFace } from './fonts'\nimport type { PDFPageSpec } from './plan'\n\n/**\n * Loads every font the text of these pages draws with, as the canvas does: the faces, the\n * characters remote fonts must cover, and the script and emoji fallbacks. Fonts loaded for some\n * characters only cover the ones jsPDF writes too.\n */\nexport async function preparePDFFonts(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[]\n): Promise<DocumentFontStatus> {\n const nodeIds = specs.flatMap((spec) => spec.nodeIds)\n return prepareGraphFonts(graph, nodeIds, await pdfWrittenCharacters(graph, nodeIds))\n}\n\n/**\n * Characters jsPDF writes for the text besides its own: it writes Arabic letters as their\n * presentation forms, picked by the letters around them, so the embedded fonts must map those.\n */\nasync function pdfWrittenCharacters(\n graph: SceneGraph,\n nodeIds: readonly string[]\n): Promise<string> {\n const texts = collectGraphFontRequirements(graph, nodeIds)\n .nodes.filter((node) => node.type === 'TEXT')\n .map(shownText)\n .filter((text) => ARABIC_CHARACTER.test(text))\n if (texts.length === 0) return ''\n const { jsPDF } = await import('jspdf')\n // jsPDF adds its Arabic parser to each document it makes, as the one it writes the text with.\n const writer = new jsPDF()\n return uniq(texts.flatMap((text) => Array.from(writer.processArabic(text)))).join('')\n}\n\n/**\n * Design pages other than the open one may still be unread, since `.fig` pages load on demand.\n * Reads the pages a `pages` export asks for, or every page, so planning sees their layers.\n */\nexport function readPDFPages(graph: SceneGraph, pageIds?: readonly string[]): void {\n // No ids, or an empty list, exports every page, as planPDFPages reads them.\n const ids = pageIds?.length ? pageIds : graph.getPages().map((page) => page.id)\n for (const pageId of ids) {\n populateFigPage(graph, pageId)\n }\n}\n\n/**\n * Loads the fonts the text of pages read by {@link readPDFPages} needs and lays them out, since\n * pages other than the open one have no layout yet, so every PDF page is complete.\n */\nexport async function preparePagesForPDF(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[]\n): Promise<DocumentFontStatus> {\n const status = await preparePDFFonts(graph, specs)\n graph.applyDerivedLayoutDuring(() => {\n for (const spec of specs) computeAllLayouts(graph, spec.pageId)\n })\n return status\n}\n\n/** The faces the pages' text uses, with the files the canvas draws them from. */\nexport function pdfFontFaces(status: DocumentFontStatus): PDFFontFace[] {\n return status.faces.map((face) => {\n const data =\n face.status === 'available' ? fontManager.loadedData(face.family, face.style) : null\n if (data) return { family: face.family, style: face.style, data }\n const missing =\n face.reason === 'unsupported-format' ? 'unsupported font format' : 'font file not available'\n return { family: face.family, style: face.style, data, missing }\n })\n}\n\n/**\n * Runs `render` with the line breaks the canvas gives each text node (same paragraph builder and\n * fonts), so a wrapped paragraph stays wrapped in the PDF. Without CanvasKit, `render` gets no\n * layout and only explicit newlines start a new line.\n */\nexport async function withPDFTextLayout<T>(\n render: (textLayout: SVGTextLayout | undefined) => Promise<T>\n): Promise<T> {\n const ck = await getCanvasKit().catch(() => null)\n if (!ck) return render(undefined)\n return withTextShaper(ck, (shape) =>\n render((node) => {\n // Shaped lines are cut by character index, which the text's case must keep.\n if (shownText(node).length !== node.text.length) return null\n const shaped = shape(node)\n if (!shaped?.baselines.length) return null\n const characters = characterEdges(shaped.glyphs)\n const fallbacks = fallbackFaces(node, characters)\n return shaped.baselines.map((line) => ({\n start: line.firstCharacter,\n end: line.endCharacter,\n x: line.position.x,\n y: line.position.y,\n width: line.width,\n characters,\n fallbacks\n }))\n })\n )\n}\n\n/**\n * The face of each drawn character the canvas draws from another file than its text's own: a\n * fallback font, such as for Chinese in Inter, or a shard of a font split by unicode-range. Emoji\n * keep their own family: the face the canvas lays them out with has no glyphs to embed.\n */\nfunction fallbackFaces(\n node: SceneNode,\n characters: ReadonlyMap<number, SVGCharacterEdges>\n): Map<number, SVGFallbackFace> {\n const text = shownText(node)\n const fallbacks = new Map<number, SVGFallbackFace>()\n for (const index of characters.keys()) {\n const face = characterFace(node, text, index)\n if (!face || (!face.fallback && face.file === 0) || face.family === EMOJI_METRICS_FAMILY)\n continue\n fallbacks.set(index, { family: face.family, style: face.style, file: face.file })\n }\n return fallbacks\n}\n\n/** The left and right edges of the glyphs each character is drawn with. */\nfunction characterEdges(glyphs: readonly ShapedTextGlyph[]): Map<number, SVGCharacterEdges> {\n const edges = new Map<number, SVGCharacterEdges>()\n for (const glyph of glyphs) {\n if (glyph.firstCharacter === undefined) continue\n const left = glyph.x\n const right = glyph.x + glyph.advance\n const known = edges.get(glyph.firstCharacter)\n edges.set(\n glyph.firstCharacter,\n known\n ? { left: Math.min(known.left, left), right: Math.max(known.right, right) }\n : { left, right }\n )\n }\n return edges\n}\n"],"mappings":";;;;;;;;;;;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AQ,MAAM,IAAI,MAAM,cAAc;EAC5C,MAAM,IACJ,MAAM,gBACN,QACI;GAAE,MAAM,KAAK,IAAI,MAAM,MAAM,IAAI;GAAG,OAAO,KAAK,IAAI,MAAM,OAAO,KAAK;EAAE,IACxE;GAAE;GAAM;EAAM,CACpB;CACF;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"prepare.js","names":[],"sources":["../../../../src/io/formats/pdf/prepare.ts"],"sourcesContent":["import { uniq } from 'es-toolkit'\n\nimport type { ShapedTextGlyph } from '@pairdraw/fig/node-change'\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\nimport { characterFace } from '#core/canvas/text/placed'\nimport { withTextShaper } from '#core/canvas/text/shape'\nimport { getCanvasKit } from '#core/canvaskit'\nimport { populateFigPage } from '#core/io/formats/fig'\nimport type { SVGCharacterEdges, SVGFallbackFace, SVGTextLayout } from '#core/io/formats/svg'\nimport { computeAllLayouts } from '#core/layout'\nimport { shownText } from '#core/text/case'\nimport { EMOJI_METRICS_FAMILY } from '#core/text/emoji'\nimport { ARABIC_CHARACTER } from '#core/text/fallbacks'\nimport { fontManager } from '#core/text/font/manager'\nimport type { FontReadiness } from '#core/text/font/readiness'\nimport { resolveFontReadiness } from '#core/text/prepare'\nimport { collectGraphFontRequirements } from '#core/text/requirements/collect'\n\nimport type { PDFFontFace } from './fonts'\nimport type { PDFPageSpec } from './plan'\n\n/**\n * Loads every font the text of these pages draws with, as the canvas does: the faces, the\n * characters remote fonts must cover, and the script and emoji fallbacks. Fonts loaded for some\n * characters only cover the ones jsPDF writes too.\n */\nexport async function preparePDFFonts(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[]\n): Promise<FontReadiness> {\n const nodeIds = specs.flatMap((spec) => spec.nodeIds)\n return resolveFontReadiness(graph, nodeIds, await pdfWrittenCharacters(graph, nodeIds))\n}\n\n/**\n * Characters jsPDF writes for the text besides its own: it writes Arabic letters as their\n * presentation forms, picked by the letters around them, so the embedded fonts must map those.\n */\nasync function pdfWrittenCharacters(\n graph: SceneGraph,\n nodeIds: readonly string[]\n): Promise<string> {\n const texts = collectGraphFontRequirements(graph, nodeIds)\n .nodes.filter((node) => node.type === 'TEXT')\n .map(shownText)\n .filter((text) => ARABIC_CHARACTER.test(text))\n if (texts.length === 0) return ''\n const { jsPDF } = await import('jspdf')\n // jsPDF adds its Arabic parser to each document it makes, as the one it writes the text with.\n const writer = new jsPDF()\n return uniq(texts.flatMap((text) => Array.from(writer.processArabic(text)))).join('')\n}\n\n/**\n * Design pages other than the open one may still be unread, since `.fig` pages load on demand.\n * Reads the pages a `pages` export asks for, or every page, so planning sees their layers.\n */\nexport function readPDFPages(graph: SceneGraph, pageIds?: readonly string[]): void {\n // No ids, or an empty list, exports every page, as planPDFPages reads them.\n const ids = pageIds?.length ? pageIds : graph.getPages().map((page) => page.id)\n for (const pageId of ids) {\n populateFigPage(graph, pageId)\n }\n}\n\n/**\n * Loads the fonts the text of pages read by {@link readPDFPages} needs and lays them out, since\n * pages other than the open one have no layout yet, so every PDF page is complete.\n */\nexport async function preparePagesForPDF(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[]\n): Promise<FontReadiness> {\n const status = await preparePDFFonts(graph, specs)\n graph.applyDerivedLayoutDuring(() => {\n for (const spec of specs) computeAllLayouts(graph, spec.pageId)\n })\n return status\n}\n\n/** The faces the pages' text uses, with the files the canvas draws them from. */\nexport function pdfFontFaces(status: FontReadiness): PDFFontFace[] {\n return status.faces.map((face) => {\n const data =\n face.status === 'available' ? fontManager.loadedData(face.family, face.style) : null\n if (data) return { family: face.family, style: face.style, data }\n const missing =\n face.reason === 'unsupported-format' ? 'unsupported font format' : 'font file not available'\n return { family: face.family, style: face.style, data, missing }\n })\n}\n\n/**\n * Runs `render` with the line breaks the canvas gives each text node (same paragraph builder and\n * fonts), so a wrapped paragraph stays wrapped in the PDF. Without CanvasKit, `render` gets no\n * layout and only explicit newlines start a new line.\n */\nexport async function withPDFTextLayout<T>(\n render: (textLayout: SVGTextLayout | undefined) => Promise<T>\n): Promise<T> {\n const ck = await getCanvasKit().catch(() => null)\n if (!ck) return render(undefined)\n return withTextShaper(ck, (shape) =>\n render((node) => {\n // Shaped lines are cut by character index, which the text's case must keep.\n if (shownText(node).length !== node.text.length) return null\n const shaped = shape(node)\n if (!shaped?.baselines.length) return null\n const characters = characterEdges(shaped.glyphs)\n const fallbacks = fallbackFaces(node, characters)\n return shaped.baselines.map((line) => ({\n start: line.firstCharacter,\n end: line.endCharacter,\n x: line.position.x,\n y: line.position.y,\n width: line.width,\n characters,\n fallbacks\n }))\n })\n )\n}\n\n/**\n * The face of each drawn character the canvas draws from another file than its text's own: a\n * fallback font, such as for Chinese in Inter, or a shard of a font split by unicode-range. Emoji\n * keep their own family: the face the canvas lays them out with has no glyphs to embed.\n */\nfunction fallbackFaces(\n node: SceneNode,\n characters: ReadonlyMap<number, SVGCharacterEdges>\n): Map<number, SVGFallbackFace> {\n const text = shownText(node)\n const fallbacks = new Map<number, SVGFallbackFace>()\n for (const index of characters.keys()) {\n const face = characterFace(node, text, index)\n if (!face || (!face.fallback && face.file === 0) || face.family === EMOJI_METRICS_FAMILY)\n continue\n fallbacks.set(index, { family: face.family, style: face.style, file: face.file })\n }\n return fallbacks\n}\n\n/** The left and right edges of the glyphs each character is drawn with. */\nfunction characterEdges(glyphs: readonly ShapedTextGlyph[]): Map<number, SVGCharacterEdges> {\n const edges = new Map<number, SVGCharacterEdges>()\n for (const glyph of glyphs) {\n if (glyph.firstCharacter === undefined) continue\n const left = glyph.x\n const right = glyph.x + glyph.advance\n const known = edges.get(glyph.firstCharacter)\n edges.set(\n glyph.firstCharacter,\n known\n ? { left: Math.min(known.left, left), right: Math.max(known.right, right) }\n : { left, right }\n )\n }\n return edges\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,eAAsB,gBACpB,OACA,OACwB;CACxB,MAAM,UAAU,MAAM,SAAS,SAAS,KAAK,OAAO;CACpD,OAAO,qBAAqB,OAAO,SAAS,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AAI,MAAM,OAAO,KAAK;EAAE,IACxE;GAAE;GAAM;EAAM,CACpB;CACF;CACA,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/io/formats/pen/index.ts"],"mappings":";;cAoJa,WAAW"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/io/formats/pen/index.ts"],"mappings":";;cA0Ja,WAAW"}
@@ -151,13 +151,24 @@ const penFormat = {
151
151
  };
152
152
  },
153
153
  async writeDocument(graph) {
154
- return {
154
+ const warnings = [];
155
+ const warningDetails = [];
156
+ const written = {
155
157
  format: "pen",
156
158
  mimeType: "application/json",
157
159
  extension: "pen",
158
- data: writePenDocument(graph),
160
+ data: writePenDocument(graph, {
161
+ warnings,
162
+ warningDetails
163
+ }),
159
164
  encoding: "utf8"
160
165
  };
166
+ if (warningDetails.length === 0) return written;
167
+ return {
168
+ ...written,
169
+ warnings,
170
+ warningDetails
171
+ };
161
172
  }
162
173
  };
163
174
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/io/formats/pen/index.ts"],"sourcesContent":["import { groupBy } from 'es-toolkit'\n\nimport {\n buildPenGraph,\n isDataURL,\n parseImportedImageURL,\n parsePenDocument,\n penAssets,\n withUsedImports,\n writePenDocument,\n type PenIconRequest,\n type PenIconSource\n} from '@pairdraw/pen'\n\nimport { defaultIcons, drawIcon, type IconData, type IconProvider } from '#core/icons'\nimport type { IOFormatAdapter, ReadDocumentInput, ReadDocumentWarning } from '#core/io/types'\nimport { layoutAuthoredNodes } from '#core/layout'\n\nimport { loadPenFonts } from './fonts'\nimport { loadPenImports, readImportedImage, UnresolvedImports, type OpenedImport } from './imports'\n\n/** The size icons are fetched at; each is scaled to the box it is drawn in. */\nconst PEN_ICON_SIZE = 24\n\n/** How many names one warning lists, so a broken document cannot flood the host's notice. */\nconst WARNING_NAMES = 10\n\n/** One warning for the names found, capped, or none when nothing was found. */\nfunction warningList<K extends 'unknown-variable' | 'missing-image' | 'unknown-node'>(\n kind: K,\n field: K extends 'unknown-variable' ? 'names' : K extends 'missing-image' ? 'urls' : 'types',\n names: ReadonlySet<string>\n): ReadDocumentWarning[] {\n return names.size > 0\n ? [{ kind, [field]: [...names].slice(0, WARNING_NAMES) } as ReadDocumentWarning]\n : []\n}\n\n/**\n * The path a percent-encoded image URL names, decoded one step at a time: a step that would become\n * a separator or a parent keeps its escape, so a URL cannot name a file outside its folder.\n */\nfunction decodeAssetPath(url: string): string {\n return url\n .split('/')\n .map((segment) => {\n let decoded: string\n try {\n decoded = decodeURIComponent(segment)\n } catch {\n return segment\n }\n if (decoded === '.' || decoded === '..') return segment\n return decoded.replaceAll('/', '%2F').replaceAll('\\\\', '%5C')\n })\n .join('/')\n}\n\n/**\n * An image's bytes: a data URL decoded by the platform's own URL handling, an imported document's\n * file beside that document, and any other file through the host; null when that fails.\n */\nasync function loadPenFile(\n url: string,\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<Uint8Array | null> {\n try {\n if (parseImportedImageURL(url)) return await readImportedImage(opened, url)\n // pen.dev writes the path percent-encoded, as `My%20Design-assets/…`.\n if (!isDataURL(url)) return (await input.readAsset?.(decodeAssetPath(url))) ?? null\n // Through `URL`, which lowercases the scheme for runtimes that only fetch `data:`.\n return new Uint8Array(await (await fetch(new URL(url))).arrayBuffer())\n } catch {\n return null\n }\n}\n\n/**\n * The shader files the document's paints and effects name, as their source text. One whose file the\n * host cannot read is left out, so its shader draws nothing rather than an empty frame.\n */\nasync function loadPenShaders(\n urls: readonly string[],\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<Map<string, string>> {\n const shaders = new Map<string, string>()\n await Promise.all(\n urls.map(async (url) => {\n const bytes = await loadPenFile(url, input, opened)\n if (bytes) shaders.set(url, new TextDecoder().decode(bytes))\n })\n )\n return shaders\n}\n\n/** The images the host has, and the URLs it does not, whose paints are dropped. */\nasync function loadPenImages(\n urls: readonly string[],\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<{ images: Map<string, Uint8Array>; missing: Set<string> }> {\n const images = new Map<string, Uint8Array>()\n const missing = new Set<string>()\n await Promise.all(\n urls.map(async (url) => {\n const bytes = await loadPenFile(url, input, opened)\n if (bytes) images.set(url, bytes)\n else missing.add(url)\n })\n )\n return { images, missing }\n}\n\n/** A request's options as a key, so requests drawn the same way share a fetch. */\nconst optionsKey = (options: Record<string, number> | undefined) => JSON.stringify(options ?? null)\n\n/**\n * Icons from `provider`, fetched once for each way they are drawn; a document whose icons cannot\n * be fetched opens with empty icons.\n */\nasync function loadPenIcons(\n requests: readonly PenIconRequest[],\n provider: IconProvider\n): Promise<PenIconSource> {\n const glyphs = new Map<string, IconData>()\n const byOptions = groupBy(requests, (request) => optionsKey(request.options))\n await Promise.all(\n Object.values(byOptions).map(async (group) => {\n const names = group.map((request) => request.name)\n const found = await provider\n .icons(names, PEN_ICON_SIZE, group[0]?.options)\n .catch(() => new Map<string, IconData>())\n for (const [name, icon] of found)\n glyphs.set(`${name}\\0${optionsKey(group[0]?.options)}`, icon)\n })\n )\n return {\n draw(graph, frameId, name, size, color, options) {\n const icon = glyphs.get(`${name}\\0${optionsKey(options)}`)\n if (!icon) return false\n drawIcon(graph, frameId, icon, size, color)\n return true\n }\n }\n}\n\nexport const penFormat: IOFormatAdapter<'pen'> = {\n id: 'pen',\n label: 'Pencil Document',\n role: 'interchange-document',\n category: 'document',\n extensions: ['pen'],\n mimeTypes: ['application/json', 'text/plain'],\n support: {\n readDocument: true,\n writeDocument: true\n },\n laysOutOnRead: true,\n matchesFile(fileName, mimeType) {\n return fileName.toLowerCase().endsWith('.pen') || mimeType === 'application/json'\n },\n async readDocument(input, context) {\n const doc = parsePenDocument(new TextDecoder().decode(input.data))\n // The libraries it imports, whose components it uses draw as library components; what the host\n // cannot read draws as placeholders the warnings tell the host about.\n const unresolved = new UnresolvedImports()\n const unknownVariables = new Set<string>()\n const unknownNodes = new Set<string>()\n const { imports, opened } = await loadPenImports(doc, input, unresolved)\n const importsIncomplete = unresolved.warnings().length > 0\n const assets = penAssets(withUsedImports(doc, imports))\n const [{ images, missing }, shaders, icons, fonts] = await Promise.all([\n loadPenImages(assets.images, input, opened),\n loadPenShaders(assets.shaders, input, opened),\n loadPenIcons(assets.icons, context?.icons ?? defaultIcons),\n loadPenFonts(doc.fonts ?? [], (url) => loadPenFile(url, input, opened))\n ])\n // A .pen file stores its layout intent, not the sizes and positions it implies; the hidden\n // library page's components are laid out too, as instances of them copy their layers.\n const graph = buildPenGraph(doc, {\n images,\n shaders,\n icons,\n fonts,\n imports,\n onUnknownVariable: (name) => {\n // A variable of a library that opened without its own imports is covered by that warning.\n if (name.includes(':') && importsIncomplete) return\n unknownVariables.add(name)\n },\n onUnknownNodeType: (type) => unknownNodes.add(type),\n layout: (target) =>\n layoutAuthoredNodes(\n target,\n target.getPages(true).map((page) => page.id)\n )\n })\n const warnings: ReadDocumentWarning[] = [\n ...unresolved.warnings(),\n ...warningList('unknown-variable', 'names', unknownVariables),\n ...warningList('missing-image', 'urls', missing),\n ...warningList('unknown-node', 'types', unknownNodes)\n ]\n return warnings.length > 0\n ? { graph, sourceFormat: 'pen', warnings }\n : { graph, sourceFormat: 'pen' }\n },\n async writeDocument(graph) {\n return {\n format: 'pen',\n mimeType: 'application/json',\n extension: 'pen',\n data: writePenDocument(graph),\n encoding: 'utf8'\n }\n }\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,gBAAgB;;AAGtB,MAAM,gBAAgB;;AAGtB,SAAS,YACP,MACA,OACA,OACuB;CACvB,OAAO,MAAM,OAAO,IAChB,CAAC;EAAE;GAAO,QAAQ,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,GAAG,aAAa;CAAE,CAAwB,IAC7E,CAAC;AACP;;;;;AAMA,SAAS,gBAAgB,KAAqB;CAC5C,OAAO,IACJ,MAAM,GAAG,CAAC,CACV,KAAK,YAAY;E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;EACvE,MAAM,oBAAoB,WAAW,SAAS,CAAC,CAAC,SAAS;EACzD,MAAM,SAAS,UAAU,gBAAgB,KAAK,OAAO,CAAC;EACtD,MAAM,CAAC,EAAE,QAAQ,WAAW,SAAS,OAAO,SAAS,MAAM,QAAQ,IAAI;GACrE,cAAc,OAAO,QAAQ,OAAO,MAAM;GAC1C,eAAe,OAAO,SAAS,OAAO,MAAM;GAC5C,aAAa,OAAO,OAAO,SAAS,SAAS,YAAY;GACzD,aAAa,IAAI,SAAS,CAAC,IAAI,QAAQ,YAAY,KAAK,OAAO,MAAM,CAAC;EACxE,CAAC;EAGD,MAAM,QAAQ,cAAc,KAAK;GAC/B;GACA;GACA;GACA;GACA;GACA,oBAAoB,SAAS;IAE3B,IAAI,KAAK,SAAS,GAAG,KAAK,mBAAmB;IAC7C,iBAAiB,IAAI,IAAI;GAC3B;GACA,oBAAoB,SAAS,aAAa,IAAI,IAAI;GAClD,SAAS,WACP,oBACE,QACA,OAAO,SAAS,IAAI,CAAC,CAAC,KAAK,SAAS,KAAK,EAAE,CAC7C;EACJ,CAAC;EACD,MAAM,WAAkC;GACtC,GAAG,WAAW,SAAS;GACvB,GAAG,YAAY,oBAAoB,SAAS,gBAAgB;GAC5D,GAAG,YAAY,iBAAiB,QAAQ,OAAO;GAC/C,GAAG,YAAY,gBAAgB,SAAS,YAAY;EACtD;EACA,OAAO,SAAS,SAAS,IACrB;GAAE;GAAO,cAAc;GAAO;EAAS,IACvC;GAAE;GAAO,cAAc;EAAM;CACnC;CACA,MAAM,cAAc,OAAO;EACzB,OAAO;GACL,QAAQ;GACR,UAAU;GACV,WAAW;GACX,MAAM,iBAAiB,KAAK;GAC5B,UAAU;EACZ;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/io/formats/pen/index.ts"],"sourcesContent":["import { groupBy } from 'es-toolkit'\n\nimport {\n buildPenGraph,\n isDataURL,\n parseImportedImageURL,\n parsePenDocument,\n penAssets,\n withUsedImports,\n writePenDocument,\n type PenIconRequest,\n type PenIconSource,\n type PenWriteWarning\n} from '@pairdraw/pen'\n\nimport { defaultIcons, drawIcon, type IconData, type IconProvider } from '#core/icons'\nimport type {\n ExportResult,\n IOFormatAdapter,\n ReadDocumentInput,\n ReadDocumentWarning\n} from '#core/io/types'\nimport { layoutAuthoredNodes } from '#core/layout'\n\nimport { loadPenFonts } from './fonts'\nimport { loadPenImports, readImportedImage, UnresolvedImports, type OpenedImport } from './imports'\n\n/** The size icons are fetched at; each is scaled to the box it is drawn in. */\nconst PEN_ICON_SIZE = 24\n\n/** How many names one warning lists, so a broken document cannot flood the host's notice. */\nconst WARNING_NAMES = 10\n\n/** One warning for the names found, capped, or none when nothing was found. */\nfunction warningList<K extends 'unknown-variable' | 'missing-image' | 'unknown-node'>(\n kind: K,\n field: K extends 'unknown-variable' ? 'names' : K extends 'missing-image' ? 'urls' : 'types',\n names: ReadonlySet<string>\n): ReadDocumentWarning[] {\n return names.size > 0\n ? [{ kind, [field]: [...names].slice(0, WARNING_NAMES) } as ReadDocumentWarning]\n : []\n}\n\n/**\n * The path a percent-encoded image URL names, decoded one step at a time: a step that would become\n * a separator or a parent keeps its escape, so a URL cannot name a file outside its folder.\n */\nfunction decodeAssetPath(url: string): string {\n return url\n .split('/')\n .map((segment) => {\n let decoded: string\n try {\n decoded = decodeURIComponent(segment)\n } catch {\n return segment\n }\n if (decoded === '.' || decoded === '..') return segment\n return decoded.replaceAll('/', '%2F').replaceAll('\\\\', '%5C')\n })\n .join('/')\n}\n\n/**\n * An image's bytes: a data URL decoded by the platform's own URL handling, an imported document's\n * file beside that document, and any other file through the host; null when that fails.\n */\nasync function loadPenFile(\n url: string,\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<Uint8Array | null> {\n try {\n if (parseImportedImageURL(url)) return await readImportedImage(opened, url)\n // pen.dev writes the path percent-encoded, as `My%20Design-assets/…`.\n if (!isDataURL(url)) return (await input.readAsset?.(decodeAssetPath(url))) ?? null\n // Through `URL`, which lowercases the scheme for runtimes that only fetch `data:`.\n return new Uint8Array(await (await fetch(new URL(url))).arrayBuffer())\n } catch {\n return null\n }\n}\n\n/**\n * The shader files the document's paints and effects name, as their source text. One whose file the\n * host cannot read is left out, so its shader draws nothing rather than an empty frame.\n */\nasync function loadPenShaders(\n urls: readonly string[],\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<Map<string, string>> {\n const shaders = new Map<string, string>()\n await Promise.all(\n urls.map(async (url) => {\n const bytes = await loadPenFile(url, input, opened)\n if (bytes) shaders.set(url, new TextDecoder().decode(bytes))\n })\n )\n return shaders\n}\n\n/** The images the host has, and the URLs it does not, whose paints are dropped. */\nasync function loadPenImages(\n urls: readonly string[],\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<{ images: Map<string, Uint8Array>; missing: Set<string> }> {\n const images = new Map<string, Uint8Array>()\n const missing = new Set<string>()\n await Promise.all(\n urls.map(async (url) => {\n const bytes = await loadPenFile(url, input, opened)\n if (bytes) images.set(url, bytes)\n else missing.add(url)\n })\n )\n return { images, missing }\n}\n\n/** A request's options as a key, so requests drawn the same way share a fetch. */\nconst optionsKey = (options: Record<string, number> | undefined) => JSON.stringify(options ?? null)\n\n/**\n * Icons from `provider`, fetched once for each way they are drawn; a document whose icons cannot\n * be fetched opens with empty icons.\n */\nasync function loadPenIcons(\n requests: readonly PenIconRequest[],\n provider: IconProvider\n): Promise<PenIconSource> {\n const glyphs = new Map<string, IconData>()\n const byOptions = groupBy(requests, (request) => optionsKey(request.options))\n await Promise.all(\n Object.values(byOptions).map(async (group) => {\n const names = group.map((request) => request.name)\n const found = await provider\n .icons(names, PEN_ICON_SIZE, group[0]?.options)\n .catch(() => new Map<string, IconData>())\n for (const [name, icon] of found)\n glyphs.set(`${name}\\0${optionsKey(group[0]?.options)}`, icon)\n })\n )\n return {\n draw(graph, frameId, name, size, color, options) {\n const icon = glyphs.get(`${name}\\0${optionsKey(options)}`)\n if (!icon) return false\n drawIcon(graph, frameId, icon, size, color)\n return true\n }\n }\n}\n\nexport const penFormat: IOFormatAdapter<'pen'> = {\n id: 'pen',\n label: 'Pencil Document',\n role: 'interchange-document',\n category: 'document',\n extensions: ['pen'],\n mimeTypes: ['application/json', 'text/plain'],\n support: {\n readDocument: true,\n writeDocument: true\n },\n laysOutOnRead: true,\n matchesFile(fileName, mimeType) {\n return fileName.toLowerCase().endsWith('.pen') || mimeType === 'application/json'\n },\n async readDocument(input, context) {\n const doc = parsePenDocument(new TextDecoder().decode(input.data))\n // The libraries it imports, whose components it uses draw as library components; what the host\n // cannot read draws as placeholders the warnings tell the host about.\n const unresolved = new UnresolvedImports()\n const unknownVariables = new Set<string>()\n const unknownNodes = new Set<string>()\n const { imports, opened } = await loadPenImports(doc, input, unresolved)\n const importsIncomplete = unresolved.warnings().length > 0\n const assets = penAssets(withUsedImports(doc, imports))\n const [{ images, missing }, shaders, icons, fonts] = await Promise.all([\n loadPenImages(assets.images, input, opened),\n loadPenShaders(assets.shaders, input, opened),\n loadPenIcons(assets.icons, context?.icons ?? defaultIcons),\n loadPenFonts(doc.fonts ?? [], (url) => loadPenFile(url, input, opened))\n ])\n // A .pen file stores its layout intent, not the sizes and positions it implies; the hidden\n // library page's components are laid out too, as instances of them copy their layers.\n const graph = buildPenGraph(doc, {\n images,\n shaders,\n icons,\n fonts,\n imports,\n onUnknownVariable: (name) => {\n // A variable of a library that opened without its own imports is covered by that warning.\n if (name.includes(':') && importsIncomplete) return\n unknownVariables.add(name)\n },\n onUnknownNodeType: (type) => unknownNodes.add(type),\n layout: (target) =>\n layoutAuthoredNodes(\n target,\n target.getPages(true).map((page) => page.id)\n )\n })\n const warnings: ReadDocumentWarning[] = [\n ...unresolved.warnings(),\n ...warningList('unknown-variable', 'names', unknownVariables),\n ...warningList('missing-image', 'urls', missing),\n ...warningList('unknown-node', 'types', unknownNodes)\n ]\n return warnings.length > 0\n ? { graph, sourceFormat: 'pen', warnings }\n : { graph, sourceFormat: 'pen' }\n },\n async writeDocument(graph) {\n const warnings: string[] = []\n const warningDetails: PenWriteWarning[] = []\n const data = writePenDocument(graph, { warnings, warningDetails })\n const written: ExportResult = {\n format: 'pen',\n mimeType: 'application/json',\n extension: 'pen',\n data,\n encoding: 'utf8'\n }\n if (warningDetails.length === 0) return written\n return { ...written, warnings, warningDetails }\n }\n}\n"],"mappings":";;;;;;;;;AA4BA,MAAM,gBAAgB;;AAGtB,MAAM,gBAAgB;;AAGtB,SAAS,YACP,MACA,OACA,OACuB;CACvB,OAAO,MAAM,OAAO,IAChB,CAAC;EAAE;GAAO,QAAQ,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,GAAG,aAAa;CAAE,CAAwB,IAC7E,CAAC;AACP;;;;;AAMA,SAAS,gBAAgB,KAAqB;CAC5C,OAAO,IACJ,MAAM,GAAG,CAAC,CACV,KAAK,YAAY;EAChB,IAAI;EACJ,IAAI;GACF,UAAU,mBAAmB,OAAO;EACtC,QAAQ;GACN,OAAO;EACT;EACA,IAAI,YAAY,OAAO,YAAY,MAAM,OAAO;EAChD,OAAO,QAAQ,WAAW,KAAK,KAAK,CAAC,CAAC,WAAW,MAAM,KAAK;CAC9D,CAAC,CAAC,CACD,KAAK,GAAG;AACb;;;;;AAMA,eAAe,YACb,KACA,OACA,QAC4B;CAC5B,IAAI;EACF,IAAI,sBAAsB,GAAG,GAAG,OAAO,MAAM,kBAAkB,QAAQ,GAAG;EAE1E,IAAI,CAAC,UAAU,GAAG,GAAG,OAAQ,MAAM,MAAM,YAAY,gBAAgB,GAAG,CAAC,KAAM;EAE/E,OAAO,IAAI,WAAW,OAAO,MAAM,MAAM,IAAI,IAAI,GAAG,CAAC,EAAA,CAAG,YAAY,CAAC;CACvE,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,eAAe,eACb,MACA,OACA,QAC8B;CAC9B,MAAM,0BAAU,IAAI,IAAoB;CACxC,MAAM,QAAQ,IACZ,KAAK,IAAI,O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,CAAC;EACD,MAAM,WAAkC;GACtC,GAAG,WAAW,SAAS;GACvB,GAAG,YAAY,oBAAoB,SAAS,gBAAgB;GAC5D,GAAG,YAAY,iBAAiB,QAAQ,OAAO;GAC/C,GAAG,YAAY,gBAAgB,SAAS,YAAY;EACtD;EACA,OAAO,SAAS,SAAS,IACrB;GAAE;GAAO,cAAc;GAAO;EAAS,IACvC;GAAE;GAAO,cAAc;EAAM;CACnC;CACA,MAAM,cAAc,OAAO;EACzB,MAAM,WAAqB,CAAC;EAC5B,MAAM,iBAAoC,CAAC;EAE3C,MAAM,UAAwB;GAC5B,QAAQ;GACR,UAAU;GACV,WAAW;GACX,MALW,iBAAiB,OAAO;IAAE;IAAU;GAAe,CAK3D;GACH,UAAU;EACZ;EACA,IAAI,eAAe,WAAW,GAAG,OAAO;EACxC,OAAO;GAAE,GAAG;GAAS;GAAU;EAAe;CAChD;AACF"}
@@ -1,5 +1,5 @@
1
- import { clamp } from "es-toolkit";
2
1
  import { colorToHex } from "@pairdraw/scene-graph/color";
2
+ import { clamp } from "es-toolkit";
3
3
  //#region src/io/formats/pptx/style.ts
4
4
  /** Scene paint/effect/text style → PPT property mapping (no slide geometry). */
5
5
  function firstVisibleFill(node) {
@@ -2,8 +2,8 @@ import "../../../canvas/index.js";
2
2
  import { SkiaRenderer } from "../../../canvas/renderer.js";
3
3
  import { CanvasKit } from "canvaskit-wasm";
4
4
  import { VisualBounds } from "@pairdraw/scene-graph/geometry";
5
- import { SceneGraph } from "@pairdraw/scene-graph";
6
5
  import { RenderColorSpace } from "@pairdraw/scene-graph/color";
6
+ import { SceneGraph } from "@pairdraw/scene-graph";
7
7
  //#region src/io/formats/raster/render.d.ts
8
8
  type RasterExportFormat = 'PNG' | 'JPG' | 'WEBP';
9
9
  type ExportFormat = RasterExportFormat | 'SVG';
@@ -1 +1 @@
1
- {"version":3,"file":"render.d.ts","names":[],"sources":["../../../../src/io/formats/raster/render.ts"],"mappings":";;;;;;;KAaY;KACA,eAAe;UAEjB;EACR;EACA,QAAQ;EACR;EACA,aAAa;EACb;;;cAIW;;iBAKG,iBAAiB,eAAe;;iBAShC,kBAAkB,eAAe;iBAQjC,qBAAqB,OAAO,YAAY,oBAAiB;iBA4PzD,4BACd,QAAQ,YACR,aAAa,YACb,gBACA;iBA0Cc,mBACd,IAAI,WACJ,UAAU,cACV,OAAO,YACP,gBACA,mBACA,SAAS,gBACR,WAAW;UA0CG;;EAEf,QAAQ;EACR;;EAEA;EACA;;;iBAIc,eACd,OAAO,YACP,gBACA,eACA,iBACC;iBAoBa,gBACd,IAAI,WACJ,UAAU,cACV,OAAO,YACP,gBACA,eACA,gBACA,SAAQ,oBACR,mBACC,WAAW;;iBAeE,kBACd,IAAI,WACJ,UAAU,cACV,OAAO,YACP,gBACA,QAAQ,cACR,gBACC,WAAW"}
1
+ {"version":3,"file":"render.d.ts","names":[],"sources":["../../../../src/io/formats/raster/render.ts"],"mappings":";;;;;;;KAcY;KACA,eAAe;UAEjB;EACR;EACA,QAAQ;EACR;EACA,aAAa;EACb;;;cAIW;;iBAKG,iBAAiB,eAAe;;iBAShC,kBAAkB,eAAe;iBAQjC,qBAAqB,OAAO,YAAY,oBAAiB;iBA8PzD,4BACd,QAAQ,YACR,aAAa,YACb,gBACA;iBA0Cc,mBACd,IAAI,WACJ,UAAU,cACV,OAAO,YACP,gBACA,mBACA,SAAS,gBACR,WAAW;UA0CG;;EAEf,QAAQ;EACR;;EAEA;EACA;;;iBAIc,eACd,OAAO,YACP,gBACA,eACA,iBACC;iBAoBa,gBACd,IAAI,WACJ,UAAU,cACV,OAAO,YACP,gBACA,eACA,gBACA,SAAQ,oBACR,mBACC,WAAW;;iBAkBE,kBACd,IAAI,WACJ,UAAU,cACV,OAAO,YACP,gBACA,QAAQ,cACR,gBACC,WAAW"}
@@ -1,4 +1,5 @@
1
1
  import { getPageColor } from "../../../figma-api/page-backgrounds.js";
2
+ import { skColorSpace } from "../../../canvas/renderer/colors.js";
2
3
  import { extractExportGraph, findPageId } from "../../subgraph.js";
3
4
  import { getWorldMatrix } from "@pairdraw/scene-graph/coordinate";
4
5
  import { computeDescendantVisualBounds } from "@pairdraw/scene-graph/geometry";
@@ -80,6 +81,8 @@ function encodeImage(ck, renderer, image, width, height, format, quality) {
80
81
  return raw instanceof Uint8Array ? renderer.encodeRasterFallback(raw, width, height, format, quality) : null;
81
82
  }
82
83
  function renderToSurface(ck, renderer, renderGraph, pageId, width, height, format, quality, setup, trimTransparent = false) {
84
+ renderer.useDocumentColorSpace(renderGraph.documentColorSpace);
85
+ const documentSpace = skColorSpace(ck, renderGraph.documentColorSpace);
83
86
  const renderScale = exportRenderScale(width, height);
84
87
  const renderWidth = width * renderScale;
85
88
  const renderHeight = height * renderScale;
@@ -87,7 +90,7 @@ function renderToSurface(ck, renderer, renderGraph, pageId, width, height, forma
87
90
  const surface = ck.MakeRasterDirectSurface({
88
91
  alphaType: ck.AlphaType.Premul,
89
92
  colorType: ck.ColorType.RGBA_8888,
90
- colorSpace: ck.ColorSpace.SRGB,
93
+ colorSpace: documentSpace,
91
94
  width: renderWidth,
92
95
  height: renderHeight
93
96
  }, pixels, renderWidth * 4);
@@ -113,7 +116,7 @@ function renderToSurface(ck, renderer, renderGraph, pageId, width, height, forma
113
116
  const downsampleSurface = ck.MakeRasterDirectSurface({
114
117
  alphaType: ck.AlphaType.Premul,
115
118
  colorType: ck.ColorType.RGBA_8888,
116
- colorSpace: ck.ColorSpace.SRGB,
119
+ colorSpace: documentSpace,
117
120
  width,
118
121
  height
119
122
  }, downsamplePixels, width * 4);
@@ -256,8 +259,9 @@ function renderThumbnail(ck, renderer, graph, pageId, width, height, format = "P
256
259
  const frame = thumbnailFrame(graph, pageId, width, height);
257
260
  if (!frame) return null;
258
261
  const { bounds, scale, width: pixelW, height: pixelH } = frame;
259
- const background = getPageColor(graph.getNode(pageId));
262
+ const stored = getPageColor(graph.getNode(pageId));
260
263
  return renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, format, quality, (canvas) => {
264
+ const background = renderer.renderColor(stored);
261
265
  canvas.clear(ck.Color4f(background.r, background.g, background.b, 1));
262
266
  canvas.translate(-bounds.minX * scale, -bounds.minY * scale);
263
267
  canvas.scale(scale, scale);
@@ -269,7 +273,8 @@ function drawRegionToImage(ck, renderer, graph, pageId, bounds, scale) {
269
273
  const pixelH = Math.max(1, Math.round((bounds.maxY - bounds.minY) * scale));
270
274
  if (!graph.getNode(pageId) || !Number.isFinite(pixelW * pixelH)) return null;
271
275
  return renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, "PNG", 100, (canvas) => {
272
- canvas.clear(ck.Color4f(renderer.pageColor.r, renderer.pageColor.g, renderer.pageColor.b, 1));
276
+ const pageBackground = renderer.renderColor(renderer.pageColor);
277
+ canvas.clear(ck.Color4f(pageBackground.r, pageBackground.g, pageBackground.b, 1));
273
278
  canvas.scale(scale, scale);
274
279
  canvas.translate(-bounds.minX, -bounds.minY);
275
280
  });
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","names":[],"sources":["../../../../src/io/formats/raster/render.ts"],"sourcesContent":["import type { CanvasKit, Canvas, Image as CanvasImage } from 'canvaskit-wasm'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport type { RenderColorSpace } from '@pairdraw/scene-graph/color'\nimport { getWorldMatrix } from '@pairdraw/scene-graph/coordinate'\nimport { computeDescendantVisualBounds, type VisualBounds } from '@pairdraw/scene-graph/geometry'\nimport Matrix, { type Mat3 } from '@pairdraw/scene-graph/matrix'\nimport { resolvedVariableModes } from '@pairdraw/scene-graph/variables'\n\nimport type { SkiaRenderer } from '#core/canvas'\nimport { getPageColor } from '#core/figma-api/page-backgrounds'\nimport { extractExportGraph, findPageId } from '#core/io/subgraph'\n\nexport type RasterExportFormat = 'PNG' | 'JPG' | 'WEBP'\nexport type ExportFormat = RasterExportFormat | 'SVG'\n\ninterface RenderOptions {\n scale: number\n format: ExportFormat\n quality?: number\n colorSpace?: RenderColorSpace\n trimTransparent?: boolean\n}\n\n/** Pixels an export may hold before it is refused, keeping a large scale from aborting CanvasKit. */\nexport const MAX_EXPORT_PIXELS = 150_000_000\n/** Intermediate pixels above which the 2× supersampling that sharpens small exports is dropped. */\nconst SUPERSAMPLE_PIXELS = 150_000_000\n\n/** Throws when an export of `width`×`height` pixels is larger than the renderer may allocate. */\nexport function assertExportSize(width: number, height: number): void {\n if (width * height > MAX_EXPORT_PIXELS) {\n throw new Error(\n `Export is too large: ${width}×${height} pixels (limit ${MAX_EXPORT_PIXELS}). Reduce the scale.`\n )\n }\n}\n\n/** The scale an export renders at before downsampling: 2× while it stays within the budget. */\nexport function exportRenderScale(width: number, height: number): number {\n return width * height * 4 <= SUPERSAMPLE_PIXELS ? 2 : 1\n}\n\nfunction ensureSinglePageSelection(graph: SceneGraph, pageId: string, nodeIds: string[]): boolean {\n return nodeIds.every((nodeId) => findPageId(graph, nodeId) === pageId)\n}\n\nexport function computeContentBounds(graph: SceneGraph, nodeIds: string[]) {\n return computeDescendantVisualBounds(\n nodeIds,\n (id) => graph.getNode(id),\n (id) => graph.getAbsolutePosition(id)\n )\n}\n\nfunction ckImageFormat(ck: CanvasKit, format: ExportFormat) {\n switch (format) {\n case 'JPG':\n return ck.ImageFormat.JPEG\n case 'WEBP':\n return ck.ImageFormat.WEBP\n default:\n return ck.ImageFormat.PNG\n }\n}\n\nfunction findAlphaBounds(ck: CanvasKit, canvas: Canvas, width: number, height: number) {\n const pixels = canvas.readPixels(0, 0, {\n alphaType: ck.AlphaType.Unpremul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: ck.ColorSpace.SRGB,\n width,\n height\n })\n if (!pixels) return null\n\n let minX = width\n let minY = height\n let maxX = -1\n let maxY = -1\n\n for (let y = 0; y < height; y++) {\n const row = y * width * 4\n for (let x = 0; x < width; x++) {\n if (pixels[row + x * 4 + 3] === 0) continue\n minX = Math.min(minX, x)\n minY = Math.min(minY, y)\n maxX = Math.max(maxX, x + 1)\n maxY = Math.max(maxY, y + 1)\n }\n }\n\n if (maxX < minX || maxY < minY) return null\n return { minX, minY, maxX, maxY }\n}\n\nconst MIN_TRANSPARENT_TRIM_INSET = 2\n\nfunction shouldTrimAlphaBounds(\n alphaBounds: NonNullable<ReturnType<typeof findAlphaBounds>>,\n width: number,\n height: number\n): boolean {\n return (\n Math.max(\n alphaBounds.minX,\n alphaBounds.minY,\n width - alphaBounds.maxX,\n height - alphaBounds.maxY\n ) >= MIN_TRANSPARENT_TRIM_INSET\n )\n}\n\n/** Encodes `image`, whose pixels are `width`×`height`, falling back to the host's encoder. */\nfunction encodeImage(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n image: CanvasImage,\n width: number,\n height: number,\n format: ExportFormat,\n quality: number\n): Uint8Array<ArrayBuffer> | null {\n const encoded = image.encodeToBytes(ckImageFormat(ck, format), quality)\n if (encoded) return new Uint8Array(encoded)\n if (format !== 'JPG' && format !== 'WEBP') return null\n const raw = image.readPixels(0, 0, {\n alphaType: ck.AlphaType.Unpremul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: ck.ColorSpace.SRGB,\n width,\n height\n })\n return raw instanceof Uint8Array\n ? renderer.encodeRasterFallback(raw, width, height, format, quality)\n : null\n}\n\nfunction renderToSurface(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n renderGraph: SceneGraph,\n pageId: string,\n width: number,\n height: number,\n format: ExportFormat,\n quality: number,\n setup: (canvas: Canvas) => void,\n trimTransparent = false\n): Uint8Array<ArrayBuffer> | null {\n const renderScale = exportRenderScale(width, height)\n const renderWidth = width * renderScale\n const renderHeight = height * renderScale\n const pixels = ck.Malloc(Uint8Array, renderWidth * renderHeight * 4)\n const surface = ck.MakeRasterDirectSurface(\n {\n alphaType: ck.AlphaType.Premul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: ck.ColorSpace.SRGB,\n width: renderWidth,\n height: renderHeight\n },\n pixels,\n renderWidth * 4\n )\n if (!surface) {\n ck.Free(pixels)\n throw new Error(`Could not allocate a ${renderWidth}×${renderHeight} export surface.`)\n }\n\n const drawnFor = renderer.supersampledOutput\n try {\n const canvas = surface.getCanvas()\n canvas.scale(renderScale, renderScale)\n setup(canvas)\n renderer.supersampledOutput =\n renderScale > 1\n ? {\n outputFromWorld: Matrix.multiply(\n Matrix.scaled(1 / renderScale, 1 / renderScale),\n canvas.getTotalMatrix()\n )\n }\n : null\n renderer.renderSceneToCanvas(canvas, renderGraph, pageId)\n surface.flush()\n\n const highResImage = surface.makeImageSnapshot()\n // At the export's own scale the snapshot is already the output: encode it without a second\n // full-size surface, which a large export would not have room for.\n if (renderScale === 1 && !trimTransparent) {\n const directBytes = encodeImage(ck, renderer, highResImage, width, height, format, quality)\n highResImage.delete()\n return directBytes\n }\n const downsamplePixels = ck.Malloc(Uint8Array, width * height * 4)\n const downsampleSurface = ck.MakeRasterDirectSurface(\n {\n alphaType: ck.AlphaType.Premul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: ck.ColorSpace.SRGB,\n width,\n height\n },\n downsamplePixels,\n width * 4\n )\n if (!downsampleSurface) {\n ck.Free(downsamplePixels)\n highResImage.delete()\n throw new Error(`Could not allocate a ${width}×${height} export surface.`)\n }\n const downsampleCanvas = downsampleSurface.getCanvas()\n downsampleCanvas.clear(ck.TRANSPARENT)\n downsampleCanvas.drawImageRectOptions(\n highResImage,\n ck.LTRBRect(0, 0, renderWidth, renderHeight),\n ck.LTRBRect(0, 0, width, height),\n ck.FilterMode.Linear,\n ck.MipmapMode.None,\n null\n )\n downsampleSurface.flush()\n highResImage.delete()\n\n const foundAlphaBounds = trimTransparent\n ? findAlphaBounds(ck, downsampleCanvas, width, height)\n : null\n const alphaBounds =\n foundAlphaBounds && shouldTrimAlphaBounds(foundAlphaBounds, width, height)\n ? foundAlphaBounds\n : null\n const image = alphaBounds\n ? downsampleSurface.makeImageSnapshot([\n alphaBounds.minX,\n alphaBounds.minY,\n alphaBounds.maxX,\n alphaBounds.maxY\n ])\n : downsampleSurface.makeImageSnapshot()\n const encoded = image.encodeToBytes(ckImageFormat(ck, format), quality)\n let resultBytes: Uint8Array<ArrayBuffer> | null = encoded ? new Uint8Array(encoded) : null\n\n // CanvasKit's `encodeToBytes` returns null for JPEG/WEBP in this build, so\n // fall back to encoding the raw pixels through the browser canvas.\n if (!resultBytes && (format === 'JPG' || format === 'WEBP')) {\n const exportWidth = alphaBounds ? alphaBounds.maxX - alphaBounds.minX : width\n const exportHeight = alphaBounds ? alphaBounds.maxY - alphaBounds.minY : height\n const exportMinX = alphaBounds ? alphaBounds.minX : 0\n const exportMinY = alphaBounds ? alphaBounds.minY : 0\n\n const rawPixels = downsampleCanvas.readPixels(exportMinX, exportMinY, {\n alphaType: ck.AlphaType.Unpremul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: ck.ColorSpace.SRGB,\n width: exportWidth,\n height: exportHeight\n })\n\n if (rawPixels instanceof Uint8Array) {\n resultBytes = renderer.encodeRasterFallback(\n rawPixels,\n exportWidth,\n exportHeight,\n format,\n quality\n )\n }\n }\n\n image.delete()\n downsampleSurface.delete()\n ck.Free(downsamplePixels)\n return resultBytes\n } finally {\n renderer.supersampledOutput = drawnFor\n surface.dispose()\n ck.Free(pixels)\n }\n}\n\n/**\n * `nodeIds` in the order the source page paints them, bottom to top, whatever order they came in,\n * without those a selected ancestor already paints.\n */\nfunction inPaintOrder(source: SceneGraph, pageId: string, nodeIds: readonly string[]): string[] {\n const selected = new Set(nodeIds)\n const ordered: string[] = []\n const visit = (id: string): void => {\n if (selected.has(id)) {\n ordered.push(id)\n return\n }\n for (const childId of source.getNode(id)?.childIds ?? []) visit(childId)\n }\n visit(pageId)\n return ordered\n}\n\nexport function prepareSelectionRenderGraph(\n source: SceneGraph,\n renderGraph: SceneGraph,\n pageId: string,\n nodeIds: string[]\n): void {\n const page = renderGraph.getNode(pageId)\n if (!page) return\n\n page.childIds = inPaintOrder(source, pageId, nodeIds).filter(\n (nodeId) => renderGraph.getNode(nodeId) !== undefined\n )\n for (const nodeId of page.childIds) {\n const node = renderGraph.getNode(nodeId)\n const sourceNode = source.getNode(nodeId)\n if (!node || !sourceNode) continue\n if (sourceNode.parentId === pageId) continue\n const world = getWorldMatrix(sourceNode, source)\n node.parentId = pageId\n // The page is now the parent, so the modes the ancestors set must stay on the node.\n node.variableModes = resolvedVariableModes(source, nodeId)\n applyWorldTransform(node, world)\n }\n renderGraph.clearAbsPosCache()\n}\n\nfunction applyWorldTransform(node: SceneNode, matrix: Mat3): void {\n const determinant = matrix[0] * matrix[4] - matrix[1] * matrix[3]\n const flipX = determinant < 0\n const rotation = Math.atan2(matrix[3], flipX ? matrix[4] : matrix[0])\n const cos = Math.cos(rotation)\n const sin = Math.sin(rotation)\n const centerX = node.width / 2\n const centerY = node.height / 2\n const m00 = flipX ? -cos : cos\n const m01 = flipX ? sin : -sin\n const m10 = sin\n const m11 = cos\n\n node.x = matrix[2] - centerX + m00 * centerX + m01 * centerY\n node.y = matrix[5] - centerY + m10 * centerX + m11 * centerY\n node.rotation = rotation * (180 / Math.PI)\n node.flipX = flipX\n node.flipY = false\n}\n\nexport function renderNodesToImage(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n graph: SceneGraph,\n pageId: string,\n nodeIds: string[],\n options: RenderOptions\n): Uint8Array<ArrayBuffer> | null {\n if (!ensureSinglePageSelection(graph, pageId, nodeIds)) {\n throw new Error('Raster export selection must stay on a single page')\n }\n\n const bounds = computeContentBounds(graph, nodeIds)\n if (!bounds) return null\n\n const contentW = bounds.maxX - bounds.minX\n const contentH = bounds.maxY - bounds.minY\n if (contentW <= 0 || contentH <= 0) return null\n\n const pixelW = Math.ceil(contentW * options.scale)\n const pixelH = Math.ceil(contentH * options.scale)\n if (pixelW <= 0 || pixelH <= 0) return null\n assertExportSize(pixelW, pixelH)\n\n // Figma exports a layer by itself, without the page behind it, even when it blends.\n const extracted = extractExportGraph(graph, { scope: 'selection', nodeIds })\n if (!extracted.pageId) return null\n prepareSelectionRenderGraph(graph, extracted.graph, extracted.pageId, nodeIds)\n\n const quality = options.quality ?? (options.format === 'PNG' ? 100 : 90)\n return renderToSurface(\n ck,\n renderer,\n extracted.graph,\n extracted.pageId,\n pixelW,\n pixelH,\n options.format,\n quality,\n (canvas) => {\n // JPEG has no transparency; Figma fills whatever the layer leaves clear with white.\n canvas.clear(options.format === 'JPG' ? ck.WHITE : ck.TRANSPARENT)\n canvas.scale(options.scale, options.scale)\n canvas.translate(-bounds.minX, -bounds.minY)\n },\n options.trimTransparent\n )\n}\n\nexport interface ThumbnailFrame {\n /** The page content the thumbnail shows. */\n bounds: VisualBounds\n scale: number\n /** The thumbnail's size in pixels. */\n width: number\n height: number\n}\n\n/** The page region a thumbnail fitted into `width` by `height` pixels shows, and its size. */\nexport function thumbnailFrame(\n graph: SceneGraph,\n pageId: string,\n width: number,\n height: number\n): ThumbnailFrame | null {\n const page = graph.getNode(pageId)\n if (!page || page.childIds.length === 0) return null\n\n const bounds = computeContentBounds(graph, page.childIds)\n if (!bounds) return null\n\n const contentW = bounds.maxX - bounds.minX\n const contentH = bounds.maxY - bounds.minY\n if (contentW <= 0 || contentH <= 0) return null\n\n const scale = Math.min(width / contentW, height / contentH)\n return {\n bounds,\n scale,\n width: Math.max(1, Math.round(contentW * scale)),\n height: Math.max(1, Math.round(contentH * scale))\n }\n}\n\nexport function renderThumbnail(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n graph: SceneGraph,\n pageId: string,\n width: number,\n height: number,\n format: RasterExportFormat = 'PNG',\n quality = 100\n): Uint8Array<ArrayBuffer> | null {\n const frame = thumbnailFrame(graph, pageId, width, height)\n if (!frame) return null\n const { bounds, scale, width: pixelW, height: pixelH } = frame\n // The page's own background, which the editor's page colour matches only while it is open.\n const background = getPageColor(graph.getNode(pageId))\n\n return renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, format, quality, (canvas) => {\n canvas.clear(ck.Color4f(background.r, background.g, background.b, 1))\n canvas.translate(-bounds.minX * scale, -bounds.minY * scale)\n canvas.scale(scale, scale)\n })\n}\n\n/** Draws a page region with `renderer`; `region.ts` gives it a renderer of its own. */\nexport function drawRegionToImage(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n graph: SceneGraph,\n pageId: string,\n bounds: VisualBounds,\n scale: number\n): Uint8Array<ArrayBuffer> | null {\n const pixelW = Math.max(1, Math.round((bounds.maxX - bounds.minX) * scale))\n const pixelH = Math.max(1, Math.round((bounds.maxY - bounds.minY) * scale))\n if (!graph.getNode(pageId) || !Number.isFinite(pixelW * pixelH)) return null\n return renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, 'PNG', 100, (canvas) => {\n canvas.clear(ck.Color4f(renderer.pageColor.r, renderer.pageColor.g, renderer.pageColor.b, 1))\n canvas.scale(scale, scale)\n canvas.translate(-bounds.minX, -bounds.minY)\n })\n}\n"],"mappings":";;;;;;;;AAyBA,MAAa,oBAAoB;;AAEjC,MAAM,qBAAqB;;AAG3B,SAAgB,iBAAiB,OAAe,QAAsB;CACpE,IAAI,QAAQ,SAAA,MACV,MAAM,IAAI,MACR,wBAAwB,MAAM,GAAG,OAAO,iBAAiB,kBAAkB,qBAC7E;AAEJ;;AAGA,SAAgB,kBAAkB,OAAe,QAAwB;CACvE,OAAO,QAAQ,SAAS,KAAK,qBAAqB,IAAI;AACxD;AAEA,SAAS,0BAA0B,OAAmB,QAAgB,SAA4B;CAChG,OAAO,QAAQ,OAAO,WAAW,WAAW,OAAO,MAAM,MAAM,MAAM;AACvE;AAEA,SAAgB,qBAAqB,OAAmB,SAAmB;CACzE,OAAO,8BACL,UACC,OAAO,MAAM,QAAQ,EAAE,IACvB,OAAO,MAAM,oBAAoB,EAAE,CACtC;AACF;AAEA,SAAS,cAAc,IAAe,QAAsB;CAC1D,QAAQ,QAAR;EACE,KAAK,OACH,OAAO,GAAG,YAAY;EACxB,KAAK,QACH,OAAO,GAAG,YAAY;EACxB,SACE,OAAO,GAAG,YAAY;CAC1B;AACF;AAEA,SAAS,gBAAgB,IAAe,QAAgB,OAAe,QAAgB;C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AI,GAAG,KAAK,OAAO,OAAO,OAAO,OAAO,QAAQ,KAAK,CAAC;CAC1E,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,OAAO,OAAO,OAAO,OAAO,QAAQ,KAAK,CAAC;CAC1E,IAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,CAAC,OAAO,SAAS,SAAS,MAAM,GAAG,OAAO;CACxE,OAAO,gBAAgB,IAAI,UAAU,OAAO,QAAQ,QAAQ,QAAQ,OAAO,MAAM,WAAW;EAC1F,OAAO,MAAM,GAAG,QAAQ,SAAS,UAAU,GAAG,SAAS,UAAU,GAAG,SAAS,UAAU,GAAG,CAAC,CAAC;EAC5F,OAAO,MAAM,OAAO,KAAK;EACzB,OAAO,UAAU,CAAC,OAAO,MAAM,CAAC,OAAO,IAAI;CAC7C,CAAC;AACH"}
1
+ {"version":3,"file":"render.js","names":[],"sources":["../../../../src/io/formats/raster/render.ts"],"sourcesContent":["import type { CanvasKit, Canvas, Image as CanvasImage } from 'canvaskit-wasm'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport type { RenderColorSpace } from '@pairdraw/scene-graph/color'\nimport { getWorldMatrix } from '@pairdraw/scene-graph/coordinate'\nimport { computeDescendantVisualBounds, type VisualBounds } from '@pairdraw/scene-graph/geometry'\nimport Matrix, { type Mat3 } from '@pairdraw/scene-graph/matrix'\nimport { resolvedVariableModes } from '@pairdraw/scene-graph/variables'\n\nimport type { SkiaRenderer } from '#core/canvas'\nimport { skColorSpace } from '#core/canvas/renderer/colors'\nimport { getPageColor } from '#core/figma-api/page-backgrounds'\nimport { extractExportGraph, findPageId } from '#core/io/subgraph'\n\nexport type RasterExportFormat = 'PNG' | 'JPG' | 'WEBP'\nexport type ExportFormat = RasterExportFormat | 'SVG'\n\ninterface RenderOptions {\n scale: number\n format: ExportFormat\n quality?: number\n colorSpace?: RenderColorSpace\n trimTransparent?: boolean\n}\n\n/** Pixels an export may hold before it is refused, keeping a large scale from aborting CanvasKit. */\nexport const MAX_EXPORT_PIXELS = 150_000_000\n/** Intermediate pixels above which the 2× supersampling that sharpens small exports is dropped. */\nconst SUPERSAMPLE_PIXELS = 150_000_000\n\n/** Throws when an export of `width`×`height` pixels is larger than the renderer may allocate. */\nexport function assertExportSize(width: number, height: number): void {\n if (width * height > MAX_EXPORT_PIXELS) {\n throw new Error(\n `Export is too large: ${width}×${height} pixels (limit ${MAX_EXPORT_PIXELS}). Reduce the scale.`\n )\n }\n}\n\n/** The scale an export renders at before downsampling: 2× while it stays within the budget. */\nexport function exportRenderScale(width: number, height: number): number {\n return width * height * 4 <= SUPERSAMPLE_PIXELS ? 2 : 1\n}\n\nfunction ensureSinglePageSelection(graph: SceneGraph, pageId: string, nodeIds: string[]): boolean {\n return nodeIds.every((nodeId) => findPageId(graph, nodeId) === pageId)\n}\n\nexport function computeContentBounds(graph: SceneGraph, nodeIds: string[]) {\n return computeDescendantVisualBounds(\n nodeIds,\n (id) => graph.getNode(id),\n (id) => graph.getAbsolutePosition(id)\n )\n}\n\nfunction ckImageFormat(ck: CanvasKit, format: ExportFormat) {\n switch (format) {\n case 'JPG':\n return ck.ImageFormat.JPEG\n case 'WEBP':\n return ck.ImageFormat.WEBP\n default:\n return ck.ImageFormat.PNG\n }\n}\n\nfunction findAlphaBounds(ck: CanvasKit, canvas: Canvas, width: number, height: number) {\n const pixels = canvas.readPixels(0, 0, {\n alphaType: ck.AlphaType.Unpremul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: ck.ColorSpace.SRGB,\n width,\n height\n })\n if (!pixels) return null\n\n let minX = width\n let minY = height\n let maxX = -1\n let maxY = -1\n\n for (let y = 0; y < height; y++) {\n const row = y * width * 4\n for (let x = 0; x < width; x++) {\n if (pixels[row + x * 4 + 3] === 0) continue\n minX = Math.min(minX, x)\n minY = Math.min(minY, y)\n maxX = Math.max(maxX, x + 1)\n maxY = Math.max(maxY, y + 1)\n }\n }\n\n if (maxX < minX || maxY < minY) return null\n return { minX, minY, maxX, maxY }\n}\n\nconst MIN_TRANSPARENT_TRIM_INSET = 2\n\nfunction shouldTrimAlphaBounds(\n alphaBounds: NonNullable<ReturnType<typeof findAlphaBounds>>,\n width: number,\n height: number\n): boolean {\n return (\n Math.max(\n alphaBounds.minX,\n alphaBounds.minY,\n width - alphaBounds.maxX,\n height - alphaBounds.maxY\n ) >= MIN_TRANSPARENT_TRIM_INSET\n )\n}\n\n/** Encodes `image`, whose pixels are `width`×`height`, falling back to the host's encoder. */\nfunction encodeImage(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n image: CanvasImage,\n width: number,\n height: number,\n format: ExportFormat,\n quality: number\n): Uint8Array<ArrayBuffer> | null {\n const encoded = image.encodeToBytes(ckImageFormat(ck, format), quality)\n if (encoded) return new Uint8Array(encoded)\n if (format !== 'JPG' && format !== 'WEBP') return null\n const raw = image.readPixels(0, 0, {\n alphaType: ck.AlphaType.Unpremul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: ck.ColorSpace.SRGB,\n width,\n height\n })\n return raw instanceof Uint8Array\n ? renderer.encodeRasterFallback(raw, width, height, format, quality)\n : null\n}\n\nfunction renderToSurface(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n renderGraph: SceneGraph,\n pageId: string,\n width: number,\n height: number,\n format: ExportFormat,\n quality: number,\n setup: (canvas: Canvas) => void,\n trimTransparent = false\n): Uint8Array<ArrayBuffer> | null {\n renderer.useDocumentColorSpace(renderGraph.documentColorSpace)\n const documentSpace = skColorSpace(ck, renderGraph.documentColorSpace)\n const renderScale = exportRenderScale(width, height)\n const renderWidth = width * renderScale\n const renderHeight = height * renderScale\n const pixels = ck.Malloc(Uint8Array, renderWidth * renderHeight * 4)\n const surface = ck.MakeRasterDirectSurface(\n {\n alphaType: ck.AlphaType.Premul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: documentSpace,\n width: renderWidth,\n height: renderHeight\n },\n pixels,\n renderWidth * 4\n )\n if (!surface) {\n ck.Free(pixels)\n throw new Error(`Could not allocate a ${renderWidth}×${renderHeight} export surface.`)\n }\n\n const drawnFor = renderer.supersampledOutput\n try {\n const canvas = surface.getCanvas()\n canvas.scale(renderScale, renderScale)\n setup(canvas)\n renderer.supersampledOutput =\n renderScale > 1\n ? {\n outputFromWorld: Matrix.multiply(\n Matrix.scaled(1 / renderScale, 1 / renderScale),\n canvas.getTotalMatrix()\n )\n }\n : null\n renderer.renderSceneToCanvas(canvas, renderGraph, pageId)\n surface.flush()\n\n const highResImage = surface.makeImageSnapshot()\n // At the export's own scale the snapshot is already the output: encode it without a second\n // full-size surface, which a large export would not have room for.\n if (renderScale === 1 && !trimTransparent) {\n const directBytes = encodeImage(ck, renderer, highResImage, width, height, format, quality)\n highResImage.delete()\n return directBytes\n }\n const downsamplePixels = ck.Malloc(Uint8Array, width * height * 4)\n const downsampleSurface = ck.MakeRasterDirectSurface(\n {\n alphaType: ck.AlphaType.Premul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: documentSpace,\n width,\n height\n },\n downsamplePixels,\n width * 4\n )\n if (!downsampleSurface) {\n ck.Free(downsamplePixels)\n highResImage.delete()\n throw new Error(`Could not allocate a ${width}×${height} export surface.`)\n }\n const downsampleCanvas = downsampleSurface.getCanvas()\n downsampleCanvas.clear(ck.TRANSPARENT)\n downsampleCanvas.drawImageRectOptions(\n highResImage,\n ck.LTRBRect(0, 0, renderWidth, renderHeight),\n ck.LTRBRect(0, 0, width, height),\n ck.FilterMode.Linear,\n ck.MipmapMode.None,\n null\n )\n downsampleSurface.flush()\n highResImage.delete()\n\n const foundAlphaBounds = trimTransparent\n ? findAlphaBounds(ck, downsampleCanvas, width, height)\n : null\n const alphaBounds =\n foundAlphaBounds && shouldTrimAlphaBounds(foundAlphaBounds, width, height)\n ? foundAlphaBounds\n : null\n const image = alphaBounds\n ? downsampleSurface.makeImageSnapshot([\n alphaBounds.minX,\n alphaBounds.minY,\n alphaBounds.maxX,\n alphaBounds.maxY\n ])\n : downsampleSurface.makeImageSnapshot()\n const encoded = image.encodeToBytes(ckImageFormat(ck, format), quality)\n let resultBytes: Uint8Array<ArrayBuffer> | null = encoded ? new Uint8Array(encoded) : null\n\n // CanvasKit's `encodeToBytes` returns null for JPEG/WEBP in this build, so\n // fall back to encoding the raw pixels through the browser canvas.\n if (!resultBytes && (format === 'JPG' || format === 'WEBP')) {\n const exportWidth = alphaBounds ? alphaBounds.maxX - alphaBounds.minX : width\n const exportHeight = alphaBounds ? alphaBounds.maxY - alphaBounds.minY : height\n const exportMinX = alphaBounds ? alphaBounds.minX : 0\n const exportMinY = alphaBounds ? alphaBounds.minY : 0\n\n const rawPixels = downsampleCanvas.readPixels(exportMinX, exportMinY, {\n alphaType: ck.AlphaType.Unpremul,\n colorType: ck.ColorType.RGBA_8888,\n colorSpace: ck.ColorSpace.SRGB,\n width: exportWidth,\n height: exportHeight\n })\n\n if (rawPixels instanceof Uint8Array) {\n resultBytes = renderer.encodeRasterFallback(\n rawPixels,\n exportWidth,\n exportHeight,\n format,\n quality\n )\n }\n }\n\n image.delete()\n downsampleSurface.delete()\n ck.Free(downsamplePixels)\n return resultBytes\n } finally {\n renderer.supersampledOutput = drawnFor\n surface.dispose()\n ck.Free(pixels)\n }\n}\n\n/**\n * `nodeIds` in the order the source page paints them, bottom to top, whatever order they came in,\n * without those a selected ancestor already paints.\n */\nfunction inPaintOrder(source: SceneGraph, pageId: string, nodeIds: readonly string[]): string[] {\n const selected = new Set(nodeIds)\n const ordered: string[] = []\n const visit = (id: string): void => {\n if (selected.has(id)) {\n ordered.push(id)\n return\n }\n for (const childId of source.getNode(id)?.childIds ?? []) visit(childId)\n }\n visit(pageId)\n return ordered\n}\n\nexport function prepareSelectionRenderGraph(\n source: SceneGraph,\n renderGraph: SceneGraph,\n pageId: string,\n nodeIds: string[]\n): void {\n const page = renderGraph.getNode(pageId)\n if (!page) return\n\n page.childIds = inPaintOrder(source, pageId, nodeIds).filter(\n (nodeId) => renderGraph.getNode(nodeId) !== undefined\n )\n for (const nodeId of page.childIds) {\n const node = renderGraph.getNode(nodeId)\n const sourceNode = source.getNode(nodeId)\n if (!node || !sourceNode) continue\n if (sourceNode.parentId === pageId) continue\n const world = getWorldMatrix(sourceNode, source)\n node.parentId = pageId\n // The page is now the parent, so the modes the ancestors set must stay on the node.\n node.variableModes = resolvedVariableModes(source, nodeId)\n applyWorldTransform(node, world)\n }\n renderGraph.clearAbsPosCache()\n}\n\nfunction applyWorldTransform(node: SceneNode, matrix: Mat3): void {\n const determinant = matrix[0] * matrix[4] - matrix[1] * matrix[3]\n const flipX = determinant < 0\n const rotation = Math.atan2(matrix[3], flipX ? matrix[4] : matrix[0])\n const cos = Math.cos(rotation)\n const sin = Math.sin(rotation)\n const centerX = node.width / 2\n const centerY = node.height / 2\n const m00 = flipX ? -cos : cos\n const m01 = flipX ? sin : -sin\n const m10 = sin\n const m11 = cos\n\n node.x = matrix[2] - centerX + m00 * centerX + m01 * centerY\n node.y = matrix[5] - centerY + m10 * centerX + m11 * centerY\n node.rotation = rotation * (180 / Math.PI)\n node.flipX = flipX\n node.flipY = false\n}\n\nexport function renderNodesToImage(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n graph: SceneGraph,\n pageId: string,\n nodeIds: string[],\n options: RenderOptions\n): Uint8Array<ArrayBuffer> | null {\n if (!ensureSinglePageSelection(graph, pageId, nodeIds)) {\n throw new Error('Raster export selection must stay on a single page')\n }\n\n const bounds = computeContentBounds(graph, nodeIds)\n if (!bounds) return null\n\n const contentW = bounds.maxX - bounds.minX\n const contentH = bounds.maxY - bounds.minY\n if (contentW <= 0 || contentH <= 0) return null\n\n const pixelW = Math.ceil(contentW * options.scale)\n const pixelH = Math.ceil(contentH * options.scale)\n if (pixelW <= 0 || pixelH <= 0) return null\n assertExportSize(pixelW, pixelH)\n\n // Figma exports a layer by itself, without the page behind it, even when it blends.\n const extracted = extractExportGraph(graph, { scope: 'selection', nodeIds })\n if (!extracted.pageId) return null\n prepareSelectionRenderGraph(graph, extracted.graph, extracted.pageId, nodeIds)\n\n const quality = options.quality ?? (options.format === 'PNG' ? 100 : 90)\n return renderToSurface(\n ck,\n renderer,\n extracted.graph,\n extracted.pageId,\n pixelW,\n pixelH,\n options.format,\n quality,\n (canvas) => {\n // JPEG has no transparency; Figma fills whatever the layer leaves clear with white.\n canvas.clear(options.format === 'JPG' ? ck.WHITE : ck.TRANSPARENT)\n canvas.scale(options.scale, options.scale)\n canvas.translate(-bounds.minX, -bounds.minY)\n },\n options.trimTransparent\n )\n}\n\nexport interface ThumbnailFrame {\n /** The page content the thumbnail shows. */\n bounds: VisualBounds\n scale: number\n /** The thumbnail's size in pixels. */\n width: number\n height: number\n}\n\n/** The page region a thumbnail fitted into `width` by `height` pixels shows, and its size. */\nexport function thumbnailFrame(\n graph: SceneGraph,\n pageId: string,\n width: number,\n height: number\n): ThumbnailFrame | null {\n const page = graph.getNode(pageId)\n if (!page || page.childIds.length === 0) return null\n\n const bounds = computeContentBounds(graph, page.childIds)\n if (!bounds) return null\n\n const contentW = bounds.maxX - bounds.minX\n const contentH = bounds.maxY - bounds.minY\n if (contentW <= 0 || contentH <= 0) return null\n\n const scale = Math.min(width / contentW, height / contentH)\n return {\n bounds,\n scale,\n width: Math.max(1, Math.round(contentW * scale)),\n height: Math.max(1, Math.round(contentH * scale))\n }\n}\n\nexport function renderThumbnail(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n graph: SceneGraph,\n pageId: string,\n width: number,\n height: number,\n format: RasterExportFormat = 'PNG',\n quality = 100\n): Uint8Array<ArrayBuffer> | null {\n const frame = thumbnailFrame(graph, pageId, width, height)\n if (!frame) return null\n const { bounds, scale, width: pixelW, height: pixelH } = frame\n // The page's own background, which the editor's page colour matches only while it is open.\n const stored = getPageColor(graph.getNode(pageId))\n\n return renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, format, quality, (canvas) => {\n // The page's color is stored in the document's profile, and `renderToSurface` has just told\n // the renderer which that is; converting before that call would use the previous document's.\n const background = renderer.renderColor(stored)\n canvas.clear(ck.Color4f(background.r, background.g, background.b, 1))\n canvas.translate(-bounds.minX * scale, -bounds.minY * scale)\n canvas.scale(scale, scale)\n })\n}\n\n/** Draws a page region with `renderer`; `region.ts` gives it a renderer of its own. */\nexport function drawRegionToImage(\n ck: CanvasKit,\n renderer: SkiaRenderer,\n graph: SceneGraph,\n pageId: string,\n bounds: VisualBounds,\n scale: number\n): Uint8Array<ArrayBuffer> | null {\n const pixelW = Math.max(1, Math.round((bounds.maxX - bounds.minX) * scale))\n const pixelH = Math.max(1, Math.round((bounds.maxY - bounds.minY) * scale))\n if (!graph.getNode(pageId) || !Number.isFinite(pixelW * pixelH)) return null\n return renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, 'PNG', 100, (canvas) => {\n // `renderToSurface` has just set the renderer's profile, so the page color converts in it.\n const pageBackground = renderer.renderColor(renderer.pageColor)\n canvas.clear(ck.Color4f(pageBackground.r, pageBackground.g, pageBackground.b, 1))\n canvas.scale(scale, scale)\n canvas.translate(-bounds.minX, -bounds.minY)\n })\n}\n"],"mappings":";;;;;;;;;AA0BA,MAAa,oBAAoB;;AAEjC,MAAM,qBAAqB;;AAG3B,SAAgB,iBAAiB,OAAe,QAAsB;CACpE,IAAI,QAAQ,SAAA,MACV,MAAM,IAAI,MACR,wBAAwB,MAAM,GAAG,OAAO,iBAAiB,kBAAkB,qBAC7E;AAEJ;;AAGA,SAAgB,kBAAkB,OAAe,QAAwB;CACvE,OAAO,QAAQ,SAAS,KAAK,qBAAqB,IAAI;AACxD;AAEA,SAAS,0BAA0B,OAAmB,QAAgB,SAA4B;CAChG,OAAO,QAAQ,OAAO,WAAW,WAAW,OAAO,MAAM,MAAM,MAAM;AACvE;AAEA,SAAgB,qBAAqB,OAAmB,SAAmB;CACzE,OAAO,8BACL,UACC,OAAO,MAAM,QAAQ,EAAE,IACvB,OAAO,MAAM,oBAAoB,EAAE,CACtC;AACF;AAEA,SAAS,cAAc,IAAe,QAAsB;CAC1D,QAAQ,QAAR;EACE,KAAK,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,WAAW,GAAG,WAAW,GAAG,WAAW,GAAG,CAAC,CAAC;EACpE,OAAO,UAAU,CAAC,OAAO,OAAO,OAAO,CAAC,OAAO,OAAO,KAAK;EAC3D,OAAO,MAAM,OAAO,KAAK;CAC3B,CAAC;AACH;;AAGA,SAAgB,kBACd,IACA,UACA,OACA,QACA,QACA,OACgC;CAChC,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,OAAO,OAAO,OAAO,OAAO,QAAQ,KAAK,CAAC;CAC1E,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,OAAO,OAAO,OAAO,OAAO,QAAQ,KAAK,CAAC;CAC1E,IAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,CAAC,OAAO,SAAS,SAAS,MAAM,GAAG,OAAO;CACxE,OAAO,gBAAgB,IAAI,UAAU,OAAO,QAAQ,QAAQ,QAAQ,OAAO,MAAM,WAAW;EAE1F,MAAM,iBAAiB,SAAS,YAAY,SAAS,SAAS;EAC9D,OAAO,MAAM,GAAG,QAAQ,eAAe,GAAG,eAAe,GAAG,eAAe,GAAG,CAAC,CAAC;EAChF,OAAO,MAAM,OAAO,KAAK;EACzB,OAAO,UAAU,CAAC,OAAO,MAAM,CAAC,OAAO,IAAI;CAC7C,CAAC;AACH"}
@@ -2,8 +2,8 @@ import { FontFaceRef } from "../../../text/font/faces.js";
2
2
  import { BooleanPathResolver } from "../boolean-path.js";
3
3
  import { SVGNode } from "./node.js";
4
4
  import { SVGTextLayout } from "./text/lines.js";
5
- import { Fill, FontVariation, SceneGraph, SceneNode } from "@pairdraw/scene-graph";
6
5
  import { RenderColorSpace } from "@pairdraw/scene-graph/color";
6
+ import { ColorProfile, Fill, FontVariation, SceneGraph, SceneNode } from "@pairdraw/scene-graph";
7
7
  import { Color } from "@pairdraw/scene-graph/primitives";
8
8
  //#region src/io/formats/svg/defs.d.ts
9
9
  /**
@@ -23,7 +23,10 @@ interface SVGExportContext {
23
23
  defs: SVGNode[];
24
24
  defIdCounter: number;
25
25
  graph: SceneGraph;
26
+ /** The space the export writes colors in. */
26
27
  colorSpace: RenderColorSpace;
28
+ /** The document's profile: the space its stored color components are in. */
29
+ documentColorSpace: ColorProfile;
27
30
  /** Starts every def id, so SVGs inlined on one page cannot reference each other's defs. */
28
31
  idPrefix?: string;
29
32
  /** Paints drawn in `currentColor`, such as an icon's tinted paths, so CSS `color` sets them. */
@@ -35,13 +38,13 @@ interface SVGExportContext {
35
38
  booleanPath?: BooleanPathResolver;
36
39
  }
37
40
  declare function nextDefId(ctx: SVGExportContext, prefix: string): string;
38
- declare function formatColor(color: Color, opacity?: number, colorSpace?: RenderColorSpace): string;
41
+ declare function formatColor(color: Color, opacity?: number, colorSpace?: RenderColorSpace, documentSpace?: ColorProfile): string;
39
42
  /**
40
43
  * A solid paint's SVG color. The canvas paints `opacity` and drops color alpha: `setAlphaf`
41
44
  * replaces it, and `.pen` stores a hex alpha in both fields. Display P3 carries that painted
42
45
  * alpha in the color. sRGB hex cannot, so `solidFillOpacity` emits it beside the color.
43
46
  */
44
- declare function formatSolidColor(color: Color, opacity: number, colorSpace: RenderColorSpace): string;
47
+ declare function formatSolidColor(color: Color, opacity: number, colorSpace: RenderColorSpace, documentSpace?: ColorProfile): string;
45
48
  /**
46
49
  * `fill-opacity` for a solid paint. Omitted at full opacity so an opaque export stays unchanged.
47
50
  * Display P3 already carries the same alpha in the color `formatSolidColor` returns, unless
@@ -1 +1 @@
1
- {"version":3,"file":"defs.d.ts","names":[],"sources":["../../../../src/io/formats/svg/defs.ts"],"mappings":";;;;;;;;;;;;UA4BiB,uBAAuB;;EAEtC;EACA;EACA,qBAAqB;EACrB;;;KAIU,gBAAgB,MAAM;UAEjB;EACf,MAAM;EACN;EACA,OAAO;EACP,YAAY;;EAEZ;;EAEA,QAAQ,MAAM;;EAEd,aAAa;EACb,YAAY;;EAEZ,cAAc;;iBAGA,UAAU,KAAK,kBAAkB;iBAIjC,YACd,OAAO,OACP,kBACA,aAAY;;;;;;iBAeE,iBACd,OAAO,OACP,iBACA,YAAY;;;;;;iBAaE,iBACd,MAAM,MACN,YAAY,kBACZ;iBAyHc,YAAY,MAAM,MAAM,MAAM,WAAW,KAAK;cAqCjD,gBAAgB;cAMhB,iBAAiB;cAMjB,gBAAgB"}
1
+ {"version":3,"file":"defs.d.ts","names":[],"sources":["../../../../src/io/formats/svg/defs.ts"],"mappings":";;;;;;;;;;;;UAmCiB,uBAAuB;;EAEtC;EACA;EACA,qBAAqB;EACrB;;;KAIU,gBAAgB,MAAM;UAEjB;EACf,MAAM;EACN;EACA,OAAO;;EAEP,YAAY;;EAEZ,oBAAoB;;EAEpB;;EAEA,QAAQ,MAAM;;EAEd,aAAa;EACb,YAAY;;EAEZ,cAAc;;iBAGA,UAAU,KAAK,kBAAkB;iBAIjC,YACd,OAAO,OACP,kBACA,aAAY,kBACZ,gBAAe;;;;;;iBAeD,iBACd,OAAO,OACP,iBACA,YAAY,kBACZ,gBAAe;;;;;;iBAaD,iBACd,MAAM,MACN,YAAY,kBACZ;iBAyHc,YAAY,MAAM,MAAM,MAAM,WAAW,KAAK;cAqCjD,gBAAgB;cAMhB,iBAAiB;cAMjB,gBAAgB"}
@@ -1,19 +1,20 @@
1
1
  import { svg } from "./node.js";
2
2
  import { round } from "./paths.js";
3
3
  import { fromUint8Array } from "js-base64";
4
+ import { colorToHex, colorToProfileCSS, convertColor, getDefaultRenderColorSpace } from "@pairdraw/scene-graph/color";
4
5
  import { gradientPoint, invertGradientTransform, isIdentityGradientTransform } from "@pairdraw/scene-graph/gradient";
5
- import { colorToDisplayCSS, colorToHex, getDefaultRenderColorSpace } from "@pairdraw/scene-graph/color";
6
6
  import { imageMimeType } from "@pairdraw/scene-graph/images";
7
7
  //#region src/io/formats/svg/defs.ts
8
8
  function nextDefId(ctx, prefix) {
9
9
  return `${ctx.idPrefix ?? ""}${prefix}${ctx.defIdCounter++}`;
10
10
  }
11
- function formatColor(color, opacity = 1, colorSpace = getDefaultRenderColorSpace()) {
12
- const alphaColor = {
11
+ function formatColor(color, opacity = 1, colorSpace = getDefaultRenderColorSpace(), documentSpace = "srgb") {
12
+ const painted = {
13
13
  ...color,
14
14
  a: color.a * opacity
15
15
  };
16
- if (colorSpace === "display-p3") return colorToDisplayCSS(alphaColor, { colorSpace });
16
+ if (colorSpace === "display-p3") return colorToProfileCSS(painted, documentSpace, "display-p3");
17
+ const alphaColor = convertColor(painted, documentSpace, "srgb");
17
18
  return colorToHex(alphaColor);
18
19
  }
19
20
  /**
@@ -21,12 +22,12 @@ function formatColor(color, opacity = 1, colorSpace = getDefaultRenderColorSpace
21
22
  * replaces it, and `.pen` stores a hex alpha in both fields. Display P3 carries that painted
22
23
  * alpha in the color. sRGB hex cannot, so `solidFillOpacity` emits it beside the color.
23
24
  */
24
- function formatSolidColor(color, opacity, colorSpace) {
25
+ function formatSolidColor(color, opacity, colorSpace, documentSpace = "srgb") {
25
26
  if (colorSpace === "display-p3") return formatColor({
26
27
  ...color,
27
28
  a: 1
28
- }, round(opacity), colorSpace);
29
- return formatColor(color, 1, colorSpace);
29
+ }, round(opacity), colorSpace, documentSpace);
30
+ return formatColor(color, 1, colorSpace, documentSpace);
30
31
  }
31
32
  /**
32
33
  * `fill-opacity` for a solid paint. Omitted at full opacity so an opaque export stays unchanged.
@@ -44,7 +45,7 @@ function createGradientDef(fill, node, ctx) {
44
45
  if (!stops || !t) return null;
45
46
  const stopNodes = stops.map((s) => svg("stop", {
46
47
  offset: `${round(s.position * 100)}%`,
47
- "stop-color": formatColor(s.color, 1, ctx.colorSpace),
48
+ "stop-color": formatColor(s.color, 1, ctx.colorSpace, ctx.documentColorSpace),
48
49
  "stop-opacity": s.color.a < 1 ? round(s.color.a) : void 0
49
50
  }));
50
51
  const id = nextDefId(ctx, "grad");
@@ -126,9 +127,9 @@ function createImagePattern(fill, node, ctx) {
126
127
  }
127
128
  function resolveFill(fill, node, ctx) {
128
129
  if (!fill.visible) return null;
129
- if (fill.type === "SOLID") return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace);
130
- if (fill.type === "MESH") return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace);
131
- if (fill.type === "PATTERN" || fill.type === "NOISE" || fill.type === "CUSTOM") return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace);
130
+ if (fill.type === "SOLID") return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace, ctx.documentColorSpace);
131
+ if (fill.type === "MESH") return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace, ctx.documentColorSpace);
132
+ if (fill.type === "PATTERN" || fill.type === "NOISE" || fill.type === "CUSTOM") return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace, ctx.documentColorSpace);
132
133
  if (fill.type.startsWith("GRADIENT")) {
133
134
  const grad = createGradientDef(fill, node, ctx);
134
135
  if (grad) {
@@ -1 +1 @@
1
- {"version":3,"file":"defs.js","names":[],"sources":["../../../../src/io/formats/svg/defs.ts"],"sourcesContent":["import { fromUint8Array } from 'js-base64'\n\nimport type { Fill, FontVariation, SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n colorToHex,\n colorToDisplayCSS,\n getDefaultRenderColorSpace,\n type RenderColorSpace\n} from '@pairdraw/scene-graph/color'\nimport {\n gradientPoint,\n invertGradientTransform,\n isIdentityGradientTransform\n} from '@pairdraw/scene-graph/gradient'\nimport { imageMimeType } from '@pairdraw/scene-graph/images'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { BooleanPathResolver } from '#core/io/formats/boolean-path'\nimport type { FontFaceRef } from '#core/text/font/faces'\n\nimport { svg, type SVGNode } from './node'\nimport { round } from './paths'\nimport type { SVGTextLayout } from './text/lines'\n\n/**\n * A face text is drawn in, with what sets its axes: the font size the optical size follows unless\n * `opticalSizeFromFontSize` is off, and the axes the text sets.\n */\nexport interface SVGFontRequest extends FontFaceRef {\n /** Which of the style's files draws the text, 0 for its own then its shards; 0 when left out. */\n file?: number\n fontSize: number\n variations: readonly FontVariation[]\n opticalSizeFromFontSize: boolean\n}\n\n/** The family to name a font face by instead of its own, or null to keep the face. */\nexport type SVGFontAlias = (font: SVGFontRequest) => string | null\n\nexport interface SVGExportContext {\n defs: SVGNode[]\n defIdCounter: number\n graph: SceneGraph\n colorSpace: RenderColorSpace\n /** Starts every def id, so SVGs inlined on one page cannot reference each other's defs. */\n idPrefix?: string\n /** Paints drawn in `currentColor`, such as an icon's tinted paths, so CSS `color` sets them. */\n tint?: (node: SceneNode) => readonly ('fill' | 'stroke')[]\n /** Measured line breaks. Without them, only explicit newlines start a new baseline. */\n textLayout?: SVGTextLayout\n fontAlias?: SVGFontAlias\n /** The live result path of a boolean made in Pairdraw, which stores none. */\n booleanPath?: BooleanPathResolver\n}\n\nexport function nextDefId(ctx: SVGExportContext, prefix: string): string {\n return `${ctx.idPrefix ?? ''}${prefix}${ctx.defIdCounter++}`\n}\n\nexport function formatColor(\n color: Color,\n opacity = 1,\n colorSpace: RenderColorSpace = getDefaultRenderColorSpace()\n): string {\n const alphaColor = { ...color, a: color.a * opacity }\n if (colorSpace === 'display-p3') {\n return colorToDisplayCSS(alphaColor, { colorSpace })\n }\n // Hex has no alpha. Stops and shadows already emit theirs; solid fills use `solidFillOpacity`.\n return colorToHex(alphaColor)\n}\n\n/**\n * A solid paint's SVG color. The canvas paints `opacity` and drops color alpha: `setAlphaf`\n * replaces it, and `.pen` stores a hex alpha in both fields. Display P3 carries that painted\n * alpha in the color. sRGB hex cannot, so `solidFillOpacity` emits it beside the color.\n */\nexport function formatSolidColor(\n color: Color,\n opacity: number,\n colorSpace: RenderColorSpace\n): string {\n if (colorSpace === 'display-p3') {\n return formatColor({ ...color, a: 1 }, round(opacity), colorSpace)\n }\n return formatColor(color, 1, colorSpace)\n}\n\n/**\n * `fill-opacity` for a solid paint. Omitted at full opacity so an opaque export stays unchanged.\n * Display P3 already carries the same alpha in the color `formatSolidColor` returns, unless\n * `separate` is set because that color was replaced and can no longer carry it.\n */\nexport function solidFillOpacity(\n fill: Fill,\n colorSpace: RenderColorSpace,\n separate = false\n): number | undefined {\n if (fill.type !== 'SOLID' || (colorSpace === 'display-p3' && !separate)) return undefined\n const alpha = round(fill.opacity)\n return alpha < 1 ? alpha : undefined\n}\n\nfunction createGradientDef(\n fill: Fill,\n node: SceneNode,\n ctx: SVGExportContext\n): { id: string; node: SVGNode } | null {\n const stops = fill.gradientStops\n const t = fill.gradientTransform\n if (!stops || !t) return null\n\n const stopNodes = stops.map((s) =>\n svg('stop', {\n offset: `${round(s.position * 100)}%`,\n 'stop-color': formatColor(s.color, 1, ctx.colorSpace),\n 'stop-opacity': s.color.a < 1 ? round(s.color.a) : undefined\n })\n )\n\n const id = nextDefId(ctx, 'grad')\n\n // Gradient space in bounding-box units, mapped onto the layer as the canvas draws it.\n const toLayer = invertGradientTransform(t)\n const transform = isIdentityGradientTransform(toLayer)\n ? undefined\n : `matrix(${[toLayer.m00, toLayer.m10, toLayer.m01, toLayer.m11, toLayer.m02, toLayer.m12].map((v) => round(v, 6)).join(' ')})`\n\n if (fill.type === 'GRADIENT_LINEAR') {\n return {\n id,\n node: svg(\n 'linearGradient',\n {\n id,\n x1: 0,\n y1: 0.5,\n x2: 1,\n y2: 0.5,\n gradientUnits: 'objectBoundingBox',\n gradientTransform: transform\n },\n ...stopNodes\n )\n }\n }\n\n // SVG has no diamond gradient, so a diamond exports as the radial one it is closest to.\n if (fill.type === 'GRADIENT_RADIAL' || fill.type === 'GRADIENT_DIAMOND') {\n return {\n id,\n node: svg(\n 'radialGradient',\n {\n id,\n cx: 0.5,\n cy: 0.5,\n r: 0.5,\n gradientUnits: 'objectBoundingBox',\n gradientTransform: transform\n },\n ...stopNodes\n )\n }\n }\n\n // Nor an angular one: it exports as a radial gradient around its centre.\n if (fill.type === 'GRADIENT_ANGULAR') {\n const center = gradientPoint(t, { x: 0.5, y: 0.5 })\n const cx = round(center.x * node.width)\n const cy = round(center.y * node.height)\n const r = Math.max(node.width, node.height)\n return {\n id,\n node: svg('radialGradient', { id, cx, cy, r, gradientUnits: 'userSpaceOnUse' }, ...stopNodes)\n }\n }\n\n return null\n}\n\nfunction createImagePattern(\n fill: Fill,\n node: SceneNode,\n ctx: SVGExportContext\n): { id: string; node: SVGNode } | null {\n if (!fill.imageHash) return null\n const data = ctx.graph.images.get(fill.imageHash)\n if (!data) return null\n\n const id = nextDefId(ctx, 'img')\n const base64 = fromUint8Array(data)\n const mime = imageMimeType(data)\n\n return {\n id,\n node: svg(\n 'pattern',\n {\n id,\n patternUnits: 'objectBoundingBox',\n width: 1,\n height: 1,\n patternTransform: fill.imageRotation\n ? `rotate(${round(fill.imageRotation)} 0.5 0.5)`\n : undefined\n },\n svg('image', {\n href: `data:${mime};base64,${base64}`,\n width: node.width,\n height: node.height,\n preserveAspectRatio: fill.imageScaleMode === 'FIT' ? 'xMidYMid meet' : 'xMidYMid slice'\n })\n )\n }\n}\n\nexport function resolveFill(fill: Fill, node: SceneNode, ctx: SVGExportContext): string | null {\n if (!fill.visible) return null\n\n if (fill.type === 'SOLID') {\n return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace)\n }\n\n // SVG has no mesh element: a mesh exports its own color, as `.fig` records carry it.\n if (fill.type === 'MESH') {\n return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace)\n }\n\n // The canvas draws a pattern, noise or custom paint as its own colour when the format has no\n // element for it, so the export must not drop the layer.\n if (fill.type === 'PATTERN' || fill.type === 'NOISE' || fill.type === 'CUSTOM') {\n return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace)\n }\n\n if (fill.type.startsWith('GRADIENT')) {\n const grad = createGradientDef(fill, node, ctx)\n if (grad) {\n ctx.defs.push(grad.node)\n return `url(#${grad.id})`\n }\n }\n\n if (fill.type === 'IMAGE') {\n const pattern = createImagePattern(fill, node, ctx)\n if (pattern) {\n ctx.defs.push(pattern.node)\n return `url(#${pattern.id})`\n }\n }\n\n return null\n}\n\nexport const SVG_STROKE_CAP: Record<string, string> = {\n NONE: 'butt',\n ROUND: 'round',\n SQUARE: 'square'\n}\n\nexport const SVG_STROKE_JOIN: Record<string, string> = {\n MITER: 'miter',\n ROUND: 'round',\n BEVEL: 'bevel'\n}\n\nexport const SVG_BLEND_MODE: Record<string, string> = {\n NORMAL: 'normal',\n DARKEN: 'darken',\n MULTIPLY: 'multiply',\n COLOR_BURN: 'color-burn',\n LIGHTEN: 'lighten',\n LINEAR_BURN: 'plus-darker',\n SCREEN: 'screen',\n LINEAR_DODGE: 'plus-lighter',\n COLOR_DODGE: 'color-dodge',\n OVERLAY: 'overlay',\n SOFT_LIGHT: 'soft-light',\n HARD_LIGHT: 'hard-light',\n DIFFERENCE: 'difference',\n EXCLUSION: 'exclusion',\n HUE: 'hue',\n SATURATION: 'saturation',\n COLOR: 'color',\n LUMINOSITY: 'luminosity'\n}\n"],"mappings":";;;;;;;AAuDA,SAAgB,UAAU,KAAuB,QAAwB;CACvE,OAAO,GAAG,IAAI,YAAY,KAAK,SAAS,IAAI;AAC9C;AAEA,SAAgB,YACd,OACA,UAAU,GACV,aAA+B,2BAA2B,GAClD;CACR,MAAM,aAAa;EAAE,GAAG;EAAO,GAAG,MAAM,IAAI;CAAQ;CACpD,IAAI,eAAe,cACjB,OAAO,kBAAkB,YAAY,EAAE,WAAW,CAAC;CAGrD,OAAO,WAAW,UAAU;AAC9B;;;;;;AAOA,SAAgB,iBACd,OACA,SACA,YACQ;CACR,IAAI,eAAe,cACjB,OAAO,YAAY;EAAE,GAAG;EAAO,GAAG;CAAE,GAAG,MAAM,OAAO,GAAG,UAAU;CAEnE,OAAO,YAAY,OAAO,GAAG,UAAU;AACzC;;;;;;AAOA,SAAgB,iBACd,MACA,YACA,WAAW,OACS;CACpB,IAAI,KAAK,SAAS,WAAY,eAAe,gBAAgB,CAAC,UAAW,OAAO,KAAA;CAChF,MAAM,QAAQ,MAAM,KAAK,OAAO;CAChC,OAAO,QAAQ,IAAI,QAAQ,KAAA;AAC7B;AAEA,SAAS,kBACP,MACA,MACA,KACsC;CACtC,MAAM,QAAQ,KAAK;CACnB,MAAM,I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B,MAAM,MAAM,GAAG;EAClD,IAAI,SAAS;GACX,IAAI,KAAK,KAAK,QAAQ,IAAI;GAC1B,OAAO,QAAQ,QAAQ,GAAG;EAC5B;CACF;CAEA,OAAO;AACT;AAEA,MAAa,iBAAyC;CACpD,MAAM;CACN,OAAO;CACP,QAAQ;AACV;AAEA,MAAa,kBAA0C;CACrD,OAAO;CACP,OAAO;CACP,OAAO;AACT;AAEA,MAAa,iBAAyC;CACpD,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,SAAS;CACT,aAAa;CACb,QAAQ;CACR,cAAc;CACd,aAAa;CACb,SAAS;CACT,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,WAAW;CACX,KAAK;CACL,YAAY;CACZ,OAAO;CACP,YAAY;AACd"}
1
+ {"version":3,"file":"defs.js","names":[],"sources":["../../../../src/io/formats/svg/defs.ts"],"sourcesContent":["import { fromUint8Array } from 'js-base64'\n\nimport type {\n ColorProfile,\n Fill,\n FontVariation,\n SceneGraph,\n SceneNode\n} from '@pairdraw/scene-graph'\nimport {\n colorToHex,\n colorToProfileCSS,\n convertColor,\n getDefaultRenderColorSpace,\n type RenderColorSpace\n} from '@pairdraw/scene-graph/color'\nimport {\n gradientPoint,\n invertGradientTransform,\n isIdentityGradientTransform\n} from '@pairdraw/scene-graph/gradient'\nimport { imageMimeType } from '@pairdraw/scene-graph/images'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { BooleanPathResolver } from '#core/io/formats/boolean-path'\nimport type { FontFaceRef } from '#core/text/font/faces'\n\nimport { svg, type SVGNode } from './node'\nimport { round } from './paths'\nimport type { SVGTextLayout } from './text/lines'\n\n/**\n * A face text is drawn in, with what sets its axes: the font size the optical size follows unless\n * `opticalSizeFromFontSize` is off, and the axes the text sets.\n */\nexport interface SVGFontRequest extends FontFaceRef {\n /** Which of the style's files draws the text, 0 for its own then its shards; 0 when left out. */\n file?: number\n fontSize: number\n variations: readonly FontVariation[]\n opticalSizeFromFontSize: boolean\n}\n\n/** The family to name a font face by instead of its own, or null to keep the face. */\nexport type SVGFontAlias = (font: SVGFontRequest) => string | null\n\nexport interface SVGExportContext {\n defs: SVGNode[]\n defIdCounter: number\n graph: SceneGraph\n /** The space the export writes colors in. */\n colorSpace: RenderColorSpace\n /** The document's profile: the space its stored color components are in. */\n documentColorSpace: ColorProfile\n /** Starts every def id, so SVGs inlined on one page cannot reference each other's defs. */\n idPrefix?: string\n /** Paints drawn in `currentColor`, such as an icon's tinted paths, so CSS `color` sets them. */\n tint?: (node: SceneNode) => readonly ('fill' | 'stroke')[]\n /** Measured line breaks. Without them, only explicit newlines start a new baseline. */\n textLayout?: SVGTextLayout\n fontAlias?: SVGFontAlias\n /** The live result path of a boolean made in Pairdraw, which stores none. */\n booleanPath?: BooleanPathResolver\n}\n\nexport function nextDefId(ctx: SVGExportContext, prefix: string): string {\n return `${ctx.idPrefix ?? ''}${prefix}${ctx.defIdCounter++}`\n}\n\nexport function formatColor(\n color: Color,\n opacity = 1,\n colorSpace: RenderColorSpace = getDefaultRenderColorSpace(),\n documentSpace: ColorProfile = 'srgb'\n): string {\n const painted = { ...color, a: color.a * opacity }\n // Stored components sit in the document's profile; write the color in the profile it is shown in.\n if (colorSpace === 'display-p3') return colorToProfileCSS(painted, documentSpace, 'display-p3')\n const alphaColor = convertColor(painted, documentSpace, 'srgb')\n // Hex has no alpha. Stops and shadows already emit theirs; solid fills use `solidFillOpacity`.\n return colorToHex(alphaColor)\n}\n\n/**\n * A solid paint's SVG color. The canvas paints `opacity` and drops color alpha: `setAlphaf`\n * replaces it, and `.pen` stores a hex alpha in both fields. Display P3 carries that painted\n * alpha in the color. sRGB hex cannot, so `solidFillOpacity` emits it beside the color.\n */\nexport function formatSolidColor(\n color: Color,\n opacity: number,\n colorSpace: RenderColorSpace,\n documentSpace: ColorProfile = 'srgb'\n): string {\n if (colorSpace === 'display-p3') {\n return formatColor({ ...color, a: 1 }, round(opacity), colorSpace, documentSpace)\n }\n return formatColor(color, 1, colorSpace, documentSpace)\n}\n\n/**\n * `fill-opacity` for a solid paint. Omitted at full opacity so an opaque export stays unchanged.\n * Display P3 already carries the same alpha in the color `formatSolidColor` returns, unless\n * `separate` is set because that color was replaced and can no longer carry it.\n */\nexport function solidFillOpacity(\n fill: Fill,\n colorSpace: RenderColorSpace,\n separate = false\n): number | undefined {\n if (fill.type !== 'SOLID' || (colorSpace === 'display-p3' && !separate)) return undefined\n const alpha = round(fill.opacity)\n return alpha < 1 ? alpha : undefined\n}\n\nfunction createGradientDef(\n fill: Fill,\n node: SceneNode,\n ctx: SVGExportContext\n): { id: string; node: SVGNode } | null {\n const stops = fill.gradientStops\n const t = fill.gradientTransform\n if (!stops || !t) return null\n\n const stopNodes = stops.map((s) =>\n svg('stop', {\n offset: `${round(s.position * 100)}%`,\n 'stop-color': formatColor(s.color, 1, ctx.colorSpace, ctx.documentColorSpace),\n 'stop-opacity': s.color.a < 1 ? round(s.color.a) : undefined\n })\n )\n\n const id = nextDefId(ctx, 'grad')\n\n // Gradient space in bounding-box units, mapped onto the layer as the canvas draws it.\n const toLayer = invertGradientTransform(t)\n const transform = isIdentityGradientTransform(toLayer)\n ? undefined\n : `matrix(${[toLayer.m00, toLayer.m10, toLayer.m01, toLayer.m11, toLayer.m02, toLayer.m12].map((v) => round(v, 6)).join(' ')})`\n\n if (fill.type === 'GRADIENT_LINEAR') {\n return {\n id,\n node: svg(\n 'linearGradient',\n {\n id,\n x1: 0,\n y1: 0.5,\n x2: 1,\n y2: 0.5,\n gradientUnits: 'objectBoundingBox',\n gradientTransform: transform\n },\n ...stopNodes\n )\n }\n }\n\n // SVG has no diamond gradient, so a diamond exports as the radial one it is closest to.\n if (fill.type === 'GRADIENT_RADIAL' || fill.type === 'GRADIENT_DIAMOND') {\n return {\n id,\n node: svg(\n 'radialGradient',\n {\n id,\n cx: 0.5,\n cy: 0.5,\n r: 0.5,\n gradientUnits: 'objectBoundingBox',\n gradientTransform: transform\n },\n ...stopNodes\n )\n }\n }\n\n // Nor an angular one: it exports as a radial gradient around its centre.\n if (fill.type === 'GRADIENT_ANGULAR') {\n const center = gradientPoint(t, { x: 0.5, y: 0.5 })\n const cx = round(center.x * node.width)\n const cy = round(center.y * node.height)\n const r = Math.max(node.width, node.height)\n return {\n id,\n node: svg('radialGradient', { id, cx, cy, r, gradientUnits: 'userSpaceOnUse' }, ...stopNodes)\n }\n }\n\n return null\n}\n\nfunction createImagePattern(\n fill: Fill,\n node: SceneNode,\n ctx: SVGExportContext\n): { id: string; node: SVGNode } | null {\n if (!fill.imageHash) return null\n const data = ctx.graph.images.get(fill.imageHash)\n if (!data) return null\n\n const id = nextDefId(ctx, 'img')\n const base64 = fromUint8Array(data)\n const mime = imageMimeType(data)\n\n return {\n id,\n node: svg(\n 'pattern',\n {\n id,\n patternUnits: 'objectBoundingBox',\n width: 1,\n height: 1,\n patternTransform: fill.imageRotation\n ? `rotate(${round(fill.imageRotation)} 0.5 0.5)`\n : undefined\n },\n svg('image', {\n href: `data:${mime};base64,${base64}`,\n width: node.width,\n height: node.height,\n preserveAspectRatio: fill.imageScaleMode === 'FIT' ? 'xMidYMid meet' : 'xMidYMid slice'\n })\n )\n }\n}\n\nexport function resolveFill(fill: Fill, node: SceneNode, ctx: SVGExportContext): string | null {\n if (!fill.visible) return null\n\n if (fill.type === 'SOLID') {\n return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace, ctx.documentColorSpace)\n }\n\n // SVG has no mesh element: a mesh exports its own color, as `.fig` records carry it.\n if (fill.type === 'MESH') {\n return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace, ctx.documentColorSpace)\n }\n\n // The canvas draws a pattern, noise or custom paint as its own colour when the format has no\n // element for it, so the export must not drop the layer.\n if (fill.type === 'PATTERN' || fill.type === 'NOISE' || fill.type === 'CUSTOM') {\n return formatSolidColor(fill.color, fill.opacity, ctx.colorSpace, ctx.documentColorSpace)\n }\n\n if (fill.type.startsWith('GRADIENT')) {\n const grad = createGradientDef(fill, node, ctx)\n if (grad) {\n ctx.defs.push(grad.node)\n return `url(#${grad.id})`\n }\n }\n\n if (fill.type === 'IMAGE') {\n const pattern = createImagePattern(fill, node, ctx)\n if (pattern) {\n ctx.defs.push(pattern.node)\n return `url(#${pattern.id})`\n }\n }\n\n return null\n}\n\nexport const SVG_STROKE_CAP: Record<string, string> = {\n NONE: 'butt',\n ROUND: 'round',\n SQUARE: 'square'\n}\n\nexport const SVG_STROKE_JOIN: Record<string, string> = {\n MITER: 'miter',\n ROUND: 'round',\n BEVEL: 'bevel'\n}\n\nexport const SVG_BLEND_MODE: Record<string, string> = {\n NORMAL: 'normal',\n DARKEN: 'darken',\n MULTIPLY: 'multiply',\n COLOR_BURN: 'color-burn',\n LIGHTEN: 'lighten',\n LINEAR_BURN: 'plus-darker',\n SCREEN: 'screen',\n LINEAR_DODGE: 'plus-lighter',\n COLOR_DODGE: 'color-dodge',\n OVERLAY: 'overlay',\n SOFT_LIGHT: 'soft-light',\n HARD_LIGHT: 'hard-light',\n DIFFERENCE: 'difference',\n EXCLUSION: 'exclusion',\n HUE: 'hue',\n SATURATION: 'saturation',\n COLOR: 'color',\n LUMINOSITY: 'luminosity'\n}\n"],"mappings":";;;;;;;AAiEA,SAAgB,UAAU,KAAuB,QAAwB;CACvE,OAAO,GAAG,IAAI,YAAY,KAAK,SAAS,IAAI;AAC9C;AAEA,SAAgB,YACd,OACA,UAAU,GACV,aAA+B,2BAA2B,GAC1D,gBAA8B,QACtB;CACR,MAAM,UAAU;EAAE,GAAG;EAAO,GAAG,MAAM,IAAI;CAAQ;CAEjD,IAAI,eAAe,cAAc,OAAO,kBAAkB,SAAS,eAAe,YAAY;CAC9F,MAAM,aAAa,aAAa,SAAS,eAAe,MAAM;CAE9D,OAAO,WAAW,UAAU;AAC9B;;;;;;AAOA,SAAgB,iBACd,OACA,SACA,YACA,gBAA8B,QACtB;CACR,IAAI,eAAe,cACjB,OAAO,YAAY;EAAE,GAAG;EAAO,GAAG;CAAE,GAAG,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