@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":"index.js","names":[],"sources":["../../../../src/canvas/text/paragraph/index.ts"],"sourcesContent":["import type {\n CanvasKit,\n FontStyle,\n Paint,\n Paragraph,\n ParagraphBuilder,\n TextFontFeatures,\n TextFontVariations,\n TextHeightBehavior\n} from 'canvaskit-wasm'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { resolveRGBAForPreview } from '@pairdraw/scene-graph/color'\nimport { faceStyleKey, type NamedFace } from '@pairdraw/scene-graph/font-style'\nimport { rangeFontStyle } from '@pairdraw/scene-graph/shared-styles'\nimport { lineHeightPixels, textLengthPixels } from '@pairdraw/scene-graph/text'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport {\n drawnFontVariations,\n loadedFace,\n resolveParagraphFontFamilies\n} from '#core/canvas/text/font-families'\nimport { laidOutText } from '#core/canvas/text/keycap'\nimport {\n pushParagraphStyle,\n type ParagraphPaintStyle,\n type ParagraphBuildOptions\n} from '#core/canvas/text/paint'\nimport type { TextRenderer } from '#core/canvas/text/renderer'\nimport { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'\nimport { autoWidthWrapWidth } from '#core/layout/text-measurement'\nimport { shownTextSlice } from '#core/text/case'\nimport { ELLIPSIS } from '#core/text/ellipsis'\nimport { makeParagraphBuilder } from '#core/text/font/collection'\nimport { fontManager } from '#core/text/font/manager'\n\nimport type { ParagraphNode } from './inputs'\n\nexport function resolveParagraphLayoutWidth(node: ParagraphNode, maxWidth?: number): number {\n if (maxWidth !== undefined) return maxWidth\n if (node.textAutoResize === 'WIDTH_AND_HEIGHT') {\n return autoWidthWrapWidth(node) ?? 1e6\n }\n return node.width || 1e6\n}\n\n/**\n * The lines a truncating box shows: what `maxLines` allows, else as many as its height holds, as\n * Figma keeps the last and ends it with an ellipsis. A text box set to truncate truncates even\n * where nothing turned on `textTruncation`, which is how the auto-resize mode is chosen.\n */\nexport function buildTruncateOpts(node: ParagraphNode): { maxLines?: number; ellipsis?: string } {\n if (node.textTruncation !== 'ENDING' && node.textAutoResize !== 'TRUNCATE') return {}\n // A box that truncates only by its height is measured as it is, then capped by the lines that\n // fit and built again with that count.\n if (node.maxLines == null || node.maxLines <= 0) {\n return node.textAutoResize === 'TRUNCATE' ? {} : { ellipsis: ELLIPSIS }\n }\n return { maxLines: node.maxLines, ellipsis: ELLIPSIS }\n}\n\nfunction getParagraphTextAlign(\n ck: CanvasKit,\n node: Pick<SceneNode, 'textAlignHorizontal' | 'textDirection' | 'text'>\n) {\n const direction = resolveNodeTextDirection(node)\n switch (node.textAlignHorizontal) {\n case 'CENTER':\n return ck.TextAlign.Center\n case 'RIGHT':\n return direction === 'RTL' ? ck.TextAlign.Left : ck.TextAlign.Right\n case 'JUSTIFIED':\n return ck.TextAlign.Justify\n default:\n return direction === 'RTL' ? ck.TextAlign.Right : ck.TextAlign.Left\n }\n}\n\n/** Explicit axes win over the named-instance axes of a variable face (`implicit`). */\nexport function textFontVariations(\n variations: SceneNode['fontVariations'] | undefined,\n implicit: SceneNode['fontVariations'] | null = null\n): TextFontVariations[] | undefined {\n const explicitAxes = new Set(variations?.map((variation) => variation.axis))\n const merged = [\n ...(implicit ?? []).filter((variation) => !explicitAxes.has(variation.axis)),\n ...(variations ?? [])\n ]\n if (merged.length === 0) return undefined\n return merged.map((variation) => ({ axis: variation.axis, value: variation.value }))\n}\n\nexport function textFontFeatures(\n features: SceneNode['fontFeatures'] | undefined\n): TextFontFeatures[] | undefined {\n if (!features || features.length === 0) return undefined\n return features.map((feature) => ({\n name: feature.tag.toLowerCase(),\n value: feature.enabled ? 1 : 0\n }))\n}\n\nexport function textHeightBehaviorValue<T>(\n ck: { TextHeightBehavior: { DisableAll: T } },\n leadingTrim: SceneNode['leadingTrim']\n): T | undefined {\n return leadingTrim === 'CAP_HEIGHT' ? ck.TextHeightBehavior.DisableAll : undefined\n}\n\n/** Which edges of the text a paragraph is: leading trim only trims the text's own edges. */\nexport interface ParagraphEdges {\n first: boolean\n last: boolean\n}\n\nfunction blockHeightBehavior(\n ck: CanvasKit,\n leadingTrim: SceneNode['leadingTrim'],\n edges: ParagraphEdges | undefined\n): TextHeightBehavior | undefined {\n if (!edges) return textHeightBehaviorValue(ck, leadingTrim)\n const { first, last } = edges\n if (leadingTrim !== 'CAP_HEIGHT') return undefined\n if (first && last) return ck.TextHeightBehavior.DisableAll\n if (first) return ck.TextHeightBehavior.DisableFirstAscent\n if (last) return ck.TextHeightBehavior.DisableLastDescent\n return ck.TextHeightBehavior.All\n}\n\n/**\n * The style a paragraph asks CanvasKit for: the face of the family that is loaded. Asked for a\n * face it lacks, CanvasKit slants and emboldens another, which neither Figma, a browser, nor a\n * native text stack draws the same, so a missing face is drawn as the face that exists and\n * reported missing, as Figma does. A family with no face loaded asks for the style as given.\n */\nfunction drawnFontStyle(\n ck: CanvasKit,\n family: string,\n weight: number,\n italic: boolean,\n style: string\n): FontStyle {\n const face = loadedFace(family, weight, italic, style) ?? { weight, italic }\n return {\n weight: { value: face.weight },\n slant: face.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright\n }\n}\n\n/** The colour a style run's text is drawn in: its first visible solid fill, or `baseColor`. */\nexport function styleRunColor(\n ck: CanvasKit,\n style: SceneNode['styleRuns'][number]['style'],\n baseColor: Float32Array\n): Float32Array {\n const visibleFill = style.fills?.find((fill) => fill.visible && fill.type === 'SOLID')\n if (!visibleFill) return baseColor\n const color = resolveRGBAForPreview(visibleFill.color).color\n return ck.Color4f(color.r, color.g, color.b, color.a * visibleFill.opacity)\n}\n\nfunction styleRunLanguage(\n style: SceneNode['styleRuns'][number]['style'],\n node: Pick<ParagraphNode, 'textLanguage'>\n): string | undefined {\n return (style.textLanguage !== undefined ? style.textLanguage : node.textLanguage) ?? undefined\n}\n\nfunction pushStyleRun(\n r: TextRenderer,\n builder: ParagraphBuilder,\n node: ParagraphNode,\n run: SceneNode['styleRuns'][number],\n baseColor: Float32Array,\n baseFontSize: number,\n fontFamilies: (primary: string, face: NamedFace) => string[],\n halfLeading: boolean,\n paintStyle?: ParagraphPaintStyle\n): void {\n const ck = r.ck\n const style = run.style\n const runFontSize = style.fontSize ?? baseFontSize\n // A percent follows the run's own font size, as in Figma.\n const runLineHeight = lineHeightPixels(\n style.lineHeight !== undefined ? style.lineHeight : node.lineHeight,\n runFontSize\n )\n const runFamily = style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)\n const runWeight = style.fontWeight ?? node.fontWeight\n const runItalic = style.italic ?? node.italic\n const runFace = {\n fontWeight: runWeight,\n italic: runItalic,\n fontStyle: rangeFontStyle(node, style)\n }\n const runKey = faceStyleKey(runFace)\n\n const textStyle = new ck.TextStyle({\n color: styleRunColor(ck, style, baseColor),\n fontFamilies: fontFamilies(runFamily, runFace),\n fontSize: runFontSize,\n locale: styleRunLanguage(style, node),\n fontStyle: drawnFontStyle(ck, runFamily, runWeight, runItalic, runKey),\n fontVariations: textFontVariations(\n drawnFontVariations({\n family: runFamily,\n weight: runWeight,\n italic: runItalic,\n style: runKey,\n fontSize: runFontSize,\n variations: style.fontVariations ?? node.fontVariations,\n opticalSizeFromFontSize: style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize\n })\n ),\n fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),\n letterSpacing: textLengthPixels(style.letterSpacing ?? node.letterSpacing, runFontSize),\n heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,\n halfLeading\n })\n pushParagraphStyle(builder, textStyle, paintStyle)\n}\n\n/** `text[start, end)` in the case each of its characters has. */\nfunction addParagraphText(\n builder: ParagraphBuilder,\n node: ParagraphNode,\n start: number,\n end: number\n): void {\n builder.addText(laidOutText(shownTextSlice(node, start, end)))\n}\n\nfunction addStyledRuns(\n r: TextRenderer,\n builder: ParagraphBuilder,\n node: ParagraphNode,\n baseColor: Float32Array,\n baseFontSize: number,\n fontFamilies: (primary: string, face: NamedFace) => string[],\n halfLeading: boolean,\n paintStyle?: ParagraphPaintStyle\n): void {\n const text = node.text\n let pos = 0\n\n for (const run of node.styleRuns) {\n if (pos < run.start) addParagraphText(builder, node, pos, run.start)\n pushStyleRun(\n r,\n builder,\n node,\n run,\n baseColor,\n baseFontSize,\n fontFamilies,\n halfLeading,\n paintStyle\n )\n addParagraphText(builder, node, run.start, run.start + run.length)\n builder.pop()\n pos = run.start + run.length\n }\n\n if (pos < text.length) addParagraphText(builder, node, pos, text.length)\n}\n\n/** What a paragraph that is one block of a longer text needs beyond its node's own style. */\nexport interface ParagraphBlockOptions {\n /** Room before the first line, as a plain paragraph's first-line indent. */\n firstLineIndent?: number\n /** Truncation for this block in place of the node's. */\n truncation?: { maxLines?: number; ellipsis?: string }\n edges?: ParagraphEdges\n}\n\n/** Room before a paragraph's first line, as an empty placeholder on its baseline. */\nfunction addFirstLineIndent(ck: CanvasKit, builder: ParagraphBuilder, width: number): void {\n builder.addPlaceholder(width, 0, ck.PlaceholderAlignment.Baseline, ck.TextBaseline.Alphabetic, 0)\n}\n\n/**\n * A native paragraph for `node`'s text in its style runs, not yet laid out. A first-line\n * indent is a placeholder before the text, which takes the first character index.\n */\nexport function buildSkParagraph(\n r: TextRenderer,\n node: ParagraphNode,\n color?: Float32Array,\n { halfLeading = false, foregroundPaint }: ParagraphBuildOptions = {},\n block: ParagraphBlockOptions = {}\n): Paragraph {\n const ck = r.ck\n const baseColor = color ?? ck.BLACK\n const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE\n const baseLineHeight = lineHeightPixels(node.lineHeight, baseFontSize)\n const cjkFallbacks = fontManager.getCJKFallbackFamilies()\n const letterFallbacks = fontManager.getLetterFallbackFamilies()\n const textDirection = resolveNodeTextDirection(node)\n\n const truncateOpts = block.truncation ?? buildTruncateOpts(node)\n\n const fontFamilies = (primary: string, face: NamedFace) =>\n resolveParagraphFontFamilies(\n primary,\n { weight: face.fontWeight, italic: face.italic, style: faceStyleKey(face) },\n letterFallbacks,\n cjkFallbacks\n )\n const nodeKey = faceStyleKey(node)\n\n const baseTextStyle = {\n color: baseColor,\n fontFamilies: fontFamilies(node.fontFamily || DEFAULT_FONT_FAMILY, node),\n fontSize: baseFontSize,\n locale: node.textLanguage ?? undefined,\n fontStyle: drawnFontStyle(\n ck,\n node.fontFamily || DEFAULT_FONT_FAMILY,\n node.fontWeight,\n node.italic,\n nodeKey\n ),\n fontVariations: textFontVariations(\n drawnFontVariations({\n family: node.fontFamily || DEFAULT_FONT_FAMILY,\n weight: node.fontWeight,\n italic: node.italic,\n style: nodeKey,\n fontSize: baseFontSize,\n variations: node.fontVariations,\n opticalSizeFromFontSize: node.opticalSizeFromFontSize\n })\n ),\n fontFeatures: textFontFeatures(node.fontFeatures),\n letterSpacing: textLengthPixels(node.letterSpacing, baseFontSize),\n heightMultiplier: baseLineHeight ? baseLineHeight / baseFontSize : undefined,\n halfLeading\n }\n const paraStyle = new ck.ParagraphStyle({\n textAlign: getParagraphTextAlign(ck, node),\n textDirection: textDirection === 'RTL' ? ck.TextDirection.RTL : ck.TextDirection.LTR,\n textHeightBehavior: blockHeightBehavior(ck, node.leadingTrim, block.edges),\n ...truncateOpts,\n textStyle: baseTextStyle\n })\n\n if (!r.fontProvider) throw new Error('Font provider not initialized')\n const builder = makeParagraphBuilder(ck, paraStyle, r.fontProvider)\n\n let background: Paint | undefined\n try {\n let paintStyle: ParagraphPaintStyle | undefined\n if (foregroundPaint) {\n background = new ck.Paint()\n background.setColor(ck.TRANSPARENT)\n paintStyle = { foreground: foregroundPaint, background }\n builder.pushPaintStyle(new ck.TextStyle(baseTextStyle), foregroundPaint, background)\n }\n if (block.firstLineIndent) addFirstLineIndent(ck, builder, block.firstLineIndent)\n if (node.styleRuns.length === 0) {\n addParagraphText(builder, node, 0, node.text.length)\n } else {\n addStyledRuns(\n r,\n builder,\n node,\n baseColor,\n baseFontSize,\n fontFamilies,\n halfLeading,\n paintStyle\n )\n }\n\n return builder.build()\n } finally {\n builder.delete()\n background?.delete()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuCA,SAAgB,4BAA4B,MAAqB,UAA2B;CAC1F,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,IAAI,KAAK,mBAAmB,oBAC1B,OAAO,mBAAmB,IAAI,KAAK;CAErC,OAAO,KAAK,SAAS;AACvB;;;;;;AAOA,SAAgB,kBAAkB,MAA+D;CAC/F,IAAI,KAAK,mBAAmB,YAAY,KAAK,mBAAmB,YAAY,OAAO,CAAC;CAGpF,IAAI,KAAK,YAAY,QAAQ,KAAK,YAAY,GAC5C,OAAO,KAAK,mBAAmB,aAAa,CAAC,IAAI,EAAE,UAAA,IAAmB;CAExE,OAAO;EAAE,UAAU,KAAK;EAAU,UAAA;CAAmB;AACvD;AAEA,SAAS,sBACP,IACA,MACA;CACA,MAAM,YAAY,yBAAyB,IAAI;CAC/C,QAAQ,KAAK,qBAAb;EACE,KAAK,UACH,OAAO,GAAG,UAAU;EACtB,KAAK,SACH,OAAO,cAAc,QAAQ,GAAG,UAAU,OAAO,GAAG,UAAU;EAChE,KAAK,aACH,OAAO,GAAG,UAAU;EACtB,SACE,OAAO,cAAc,QAAQ,GAAG,UAAU,QAAQ,GAAG,UAAU;CACnE;AACF;;AAGA,SAAgB,mBACd,YACA,WAA+C,MACb;CAClC,MAAM,eAAe,IAAI,IAAI,YAAY,KAAK,cAAc,UAAU,IAAI,CAAC;CAC3E,MAAM,SAAS,CACb,IAAI,YAAY,CAAC,EAAA,CAAG,QAAQ,cAAc,CAAC,aAAa,IAAI,UAA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":[],"sources":["../../../../src/canvas/text/paragraph/index.ts"],"sourcesContent":["import type {\n CanvasKit,\n FontStyle,\n Paint,\n Paragraph,\n ParagraphBuilder,\n TextFontFeatures,\n TextFontVariations,\n TextHeightBehavior\n} from 'canvaskit-wasm'\n\nimport type { ColorProfile, SceneNode } from '@pairdraw/scene-graph'\nimport { normalizeColor, toExtendedSRGB } from '@pairdraw/scene-graph/color'\nimport { faceStyleKey, type NamedFace } from '@pairdraw/scene-graph/font-style'\nimport { rangeFontStyle } from '@pairdraw/scene-graph/shared-styles'\nimport { lineHeightPixels, textLengthPixels } from '@pairdraw/scene-graph/text'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport {\n drawnFontVariations,\n loadedFace,\n resolveParagraphFontFamilies\n} from '#core/canvas/text/font-families'\nimport { laidOutText } from '#core/canvas/text/keycap'\nimport {\n pushParagraphStyle,\n type ParagraphPaintStyle,\n type ParagraphBuildOptions\n} from '#core/canvas/text/paint'\nimport type { TextRenderer } from '#core/canvas/text/renderer'\nimport { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'\nimport { autoWidthWrapWidth } from '#core/layout/text-measurement'\nimport { shownTextSlice } from '#core/text/case'\nimport { ELLIPSIS } from '#core/text/ellipsis'\nimport { makeParagraphBuilder } from '#core/text/font/collection'\nimport { fontManager } from '#core/text/font/manager'\n\nimport type { ParagraphNode } from './inputs'\n\nexport function resolveParagraphLayoutWidth(node: ParagraphNode, maxWidth?: number): number {\n if (maxWidth !== undefined) return maxWidth\n if (node.textAutoResize === 'WIDTH_AND_HEIGHT') {\n return autoWidthWrapWidth(node) ?? 1e6\n }\n return node.width || 1e6\n}\n\n/**\n * The lines a truncating box shows: what `maxLines` allows, else as many as its height holds, as\n * Figma keeps the last and ends it with an ellipsis. A text box set to truncate truncates even\n * where nothing turned on `textTruncation`, which is how the auto-resize mode is chosen.\n */\nexport function buildTruncateOpts(node: ParagraphNode): { maxLines?: number; ellipsis?: string } {\n if (node.textTruncation !== 'ENDING' && node.textAutoResize !== 'TRUNCATE') return {}\n // A box that truncates only by its height is measured as it is, then capped by the lines that\n // fit and built again with that count.\n if (node.maxLines == null || node.maxLines <= 0) {\n return node.textAutoResize === 'TRUNCATE' ? {} : { ellipsis: ELLIPSIS }\n }\n return { maxLines: node.maxLines, ellipsis: ELLIPSIS }\n}\n\nfunction getParagraphTextAlign(\n ck: CanvasKit,\n node: Pick<SceneNode, 'textAlignHorizontal' | 'textDirection' | 'text'>\n) {\n const direction = resolveNodeTextDirection(node)\n switch (node.textAlignHorizontal) {\n case 'CENTER':\n return ck.TextAlign.Center\n case 'RIGHT':\n return direction === 'RTL' ? ck.TextAlign.Left : ck.TextAlign.Right\n case 'JUSTIFIED':\n return ck.TextAlign.Justify\n default:\n return direction === 'RTL' ? ck.TextAlign.Right : ck.TextAlign.Left\n }\n}\n\n/** Explicit axes win over the named-instance axes of a variable face (`implicit`). */\nexport function textFontVariations(\n variations: SceneNode['fontVariations'] | undefined,\n implicit: SceneNode['fontVariations'] | null = null\n): TextFontVariations[] | undefined {\n const explicitAxes = new Set(variations?.map((variation) => variation.axis))\n const merged = [\n ...(implicit ?? []).filter((variation) => !explicitAxes.has(variation.axis)),\n ...(variations ?? [])\n ]\n if (merged.length === 0) return undefined\n return merged.map((variation) => ({ axis: variation.axis, value: variation.value }))\n}\n\nexport function textFontFeatures(\n features: SceneNode['fontFeatures'] | undefined\n): TextFontFeatures[] | undefined {\n if (!features || features.length === 0) return undefined\n return features.map((feature) => ({\n name: feature.tag.toLowerCase(),\n value: feature.enabled ? 1 : 0\n }))\n}\n\nexport function textHeightBehaviorValue<T>(\n ck: { TextHeightBehavior: { DisableAll: T } },\n leadingTrim: SceneNode['leadingTrim']\n): T | undefined {\n return leadingTrim === 'CAP_HEIGHT' ? ck.TextHeightBehavior.DisableAll : undefined\n}\n\n/** Which edges of the text a paragraph is: leading trim only trims the text's own edges. */\nexport interface ParagraphEdges {\n first: boolean\n last: boolean\n}\n\nfunction blockHeightBehavior(\n ck: CanvasKit,\n leadingTrim: SceneNode['leadingTrim'],\n edges: ParagraphEdges | undefined\n): TextHeightBehavior | undefined {\n if (!edges) return textHeightBehaviorValue(ck, leadingTrim)\n const { first, last } = edges\n if (leadingTrim !== 'CAP_HEIGHT') return undefined\n if (first && last) return ck.TextHeightBehavior.DisableAll\n if (first) return ck.TextHeightBehavior.DisableFirstAscent\n if (last) return ck.TextHeightBehavior.DisableLastDescent\n return ck.TextHeightBehavior.All\n}\n\n/**\n * The style a paragraph asks CanvasKit for: the face of the family that is loaded. Asked for a\n * face it lacks, CanvasKit slants and emboldens another, which neither Figma, a browser, nor a\n * native text stack draws the same, so a missing face is drawn as the face that exists and\n * reported missing, as Figma does. A family with no face loaded asks for the style as given.\n */\nfunction drawnFontStyle(\n ck: CanvasKit,\n family: string,\n weight: number,\n italic: boolean,\n style: string\n): FontStyle {\n const face = loadedFace(family, weight, italic, style) ?? { weight, italic }\n return {\n weight: { value: face.weight },\n slant: face.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright\n }\n}\n\n/** The colour a style run's text is drawn in: its first visible solid fill, or `baseColor`. */\nexport function styleRunColor(\n ck: CanvasKit,\n style: SceneNode['styleRuns'][number]['style'],\n baseColor: Float32Array,\n space: ColorProfile\n): Float32Array {\n const visibleFill = style.fills?.find((fill) => fill.visible && fill.type === 'SOLID')\n if (!visibleFill) return baseColor\n const color = toExtendedSRGB(normalizeColor(visibleFill.color), space)\n return ck.Color4f(color.r, color.g, color.b, color.a * visibleFill.opacity)\n}\n\n/**\n * A text style's color. CanvasKit keeps `color` in 8-bit sRGB, which clips a wide-gamut color, and\n * draws `foregroundColor` with float components, so both carry it; a pushed foreground paint, as a\n * gradient fill draws with, still takes their place.\n */\nfunction textColor(color: Float32Array) {\n return { color, foregroundColor: color }\n}\n\nfunction styleRunLanguage(\n style: SceneNode['styleRuns'][number]['style'],\n node: Pick<ParagraphNode, 'textLanguage'>\n): string | undefined {\n return (style.textLanguage !== undefined ? style.textLanguage : node.textLanguage) ?? undefined\n}\n\nfunction pushStyleRun(\n r: TextRenderer,\n builder: ParagraphBuilder,\n node: ParagraphNode,\n run: SceneNode['styleRuns'][number],\n baseColor: Float32Array,\n baseFontSize: number,\n fontFamilies: (primary: string, face: NamedFace) => string[],\n halfLeading: boolean,\n paintStyle?: ParagraphPaintStyle\n): void {\n const ck = r.ck\n const style = run.style\n const runFontSize = style.fontSize ?? baseFontSize\n // A percent follows the run's own font size, as in Figma.\n const runLineHeight = lineHeightPixels(\n style.lineHeight !== undefined ? style.lineHeight : node.lineHeight,\n runFontSize\n )\n const runFamily = style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)\n const runWeight = style.fontWeight ?? node.fontWeight\n const runItalic = style.italic ?? node.italic\n const runFace = {\n fontWeight: runWeight,\n italic: runItalic,\n fontStyle: rangeFontStyle(node, style)\n }\n const runKey = faceStyleKey(runFace)\n\n const textStyle = new ck.TextStyle({\n ...textColor(styleRunColor(ck, style, baseColor, r.documentColorSpace ?? 'srgb')),\n fontFamilies: fontFamilies(runFamily, runFace),\n fontSize: runFontSize,\n locale: styleRunLanguage(style, node),\n fontStyle: drawnFontStyle(ck, runFamily, runWeight, runItalic, runKey),\n fontVariations: textFontVariations(\n drawnFontVariations({\n family: runFamily,\n weight: runWeight,\n italic: runItalic,\n style: runKey,\n fontSize: runFontSize,\n variations: style.fontVariations ?? node.fontVariations,\n opticalSizeFromFontSize: style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize\n })\n ),\n fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),\n letterSpacing: textLengthPixels(style.letterSpacing ?? node.letterSpacing, runFontSize),\n heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,\n halfLeading\n })\n pushParagraphStyle(builder, textStyle, paintStyle)\n}\n\n/** `text[start, end)` in the case each of its characters has. */\nfunction addParagraphText(\n builder: ParagraphBuilder,\n node: ParagraphNode,\n start: number,\n end: number\n): void {\n builder.addText(laidOutText(shownTextSlice(node, start, end)))\n}\n\nfunction addStyledRuns(\n r: TextRenderer,\n builder: ParagraphBuilder,\n node: ParagraphNode,\n baseColor: Float32Array,\n baseFontSize: number,\n fontFamilies: (primary: string, face: NamedFace) => string[],\n halfLeading: boolean,\n paintStyle?: ParagraphPaintStyle\n): void {\n const text = node.text\n let pos = 0\n\n for (const run of node.styleRuns) {\n if (pos < run.start) addParagraphText(builder, node, pos, run.start)\n pushStyleRun(\n r,\n builder,\n node,\n run,\n baseColor,\n baseFontSize,\n fontFamilies,\n halfLeading,\n paintStyle\n )\n addParagraphText(builder, node, run.start, run.start + run.length)\n builder.pop()\n pos = run.start + run.length\n }\n\n if (pos < text.length) addParagraphText(builder, node, pos, text.length)\n}\n\n/** What a paragraph that is one block of a longer text needs beyond its node's own style. */\nexport interface ParagraphBlockOptions {\n /** Room before the first line, as a plain paragraph's first-line indent. */\n firstLineIndent?: number\n /** Truncation for this block in place of the node's. */\n truncation?: { maxLines?: number; ellipsis?: string }\n edges?: ParagraphEdges\n}\n\n/** Room before a paragraph's first line, as an empty placeholder on its baseline. */\nfunction addFirstLineIndent(ck: CanvasKit, builder: ParagraphBuilder, width: number): void {\n builder.addPlaceholder(width, 0, ck.PlaceholderAlignment.Baseline, ck.TextBaseline.Alphabetic, 0)\n}\n\n/**\n * A native paragraph for `node`'s text in its style runs, not yet laid out. A first-line\n * indent is a placeholder before the text, which takes the first character index.\n */\nexport function buildSkParagraph(\n r: TextRenderer,\n node: ParagraphNode,\n color?: Float32Array,\n { halfLeading = false, foregroundPaint }: ParagraphBuildOptions = {},\n block: ParagraphBlockOptions = {}\n): Paragraph {\n const ck = r.ck\n const baseColor = color ?? ck.BLACK\n const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE\n const baseLineHeight = lineHeightPixels(node.lineHeight, baseFontSize)\n const cjkFallbacks = fontManager.getCJKFallbackFamilies()\n const letterFallbacks = fontManager.getLetterFallbackFamilies()\n const textDirection = resolveNodeTextDirection(node)\n\n const truncateOpts = block.truncation ?? buildTruncateOpts(node)\n\n const fontFamilies = (primary: string, face: NamedFace) =>\n resolveParagraphFontFamilies(\n primary,\n { weight: face.fontWeight, italic: face.italic, style: faceStyleKey(face) },\n letterFallbacks,\n cjkFallbacks\n )\n const nodeKey = faceStyleKey(node)\n\n const baseTextStyle = {\n ...textColor(baseColor),\n fontFamilies: fontFamilies(node.fontFamily || DEFAULT_FONT_FAMILY, node),\n fontSize: baseFontSize,\n locale: node.textLanguage ?? undefined,\n fontStyle: drawnFontStyle(\n ck,\n node.fontFamily || DEFAULT_FONT_FAMILY,\n node.fontWeight,\n node.italic,\n nodeKey\n ),\n fontVariations: textFontVariations(\n drawnFontVariations({\n family: node.fontFamily || DEFAULT_FONT_FAMILY,\n weight: node.fontWeight,\n italic: node.italic,\n style: nodeKey,\n fontSize: baseFontSize,\n variations: node.fontVariations,\n opticalSizeFromFontSize: node.opticalSizeFromFontSize\n })\n ),\n fontFeatures: textFontFeatures(node.fontFeatures),\n letterSpacing: textLengthPixels(node.letterSpacing, baseFontSize),\n heightMultiplier: baseLineHeight ? baseLineHeight / baseFontSize : undefined,\n halfLeading\n }\n const paraStyle = new ck.ParagraphStyle({\n textAlign: getParagraphTextAlign(ck, node),\n textDirection: textDirection === 'RTL' ? ck.TextDirection.RTL : ck.TextDirection.LTR,\n textHeightBehavior: blockHeightBehavior(ck, node.leadingTrim, block.edges),\n ...truncateOpts,\n textStyle: baseTextStyle\n })\n\n if (!r.fontProvider) throw new Error('Font provider not initialized')\n const builder = makeParagraphBuilder(ck, paraStyle, r.fontProvider)\n\n let background: Paint | undefined\n try {\n let paintStyle: ParagraphPaintStyle | undefined\n if (foregroundPaint) {\n background = new ck.Paint()\n background.setColor(ck.TRANSPARENT)\n paintStyle = { foreground: foregroundPaint, background }\n builder.pushPaintStyle(new ck.TextStyle(baseTextStyle), foregroundPaint, background)\n }\n if (block.firstLineIndent) addFirstLineIndent(ck, builder, block.firstLineIndent)\n if (node.styleRuns.length === 0) {\n addParagraphText(builder, node, 0, node.text.length)\n } else {\n addStyledRuns(\n r,\n builder,\n node,\n baseColor,\n baseFontSize,\n fontFamilies,\n halfLeading,\n paintStyle\n )\n }\n\n return builder.build()\n } finally {\n builder.delete()\n background?.delete()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuCA,SAAgB,4BAA4B,MAAqB,UAA2B;CAC1F,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,IAAI,KAAK,mBAAmB,oBAC1B,OAAO,mBAAmB,IAAI,KAAK;CAErC,OAAO,KAAK,SAAS;AACvB;;;;;;AAOA,SAAgB,kBAAkB,MAA+D;CAC/F,IAAI,KAAK,mBAAmB,YAAY,KAAK,mBAAmB,YAAY,OAAO,CAAC;CAGpF,IAAI,KAAK,YAAY,QAAQ,KAAK,YAAY,GAC5C,OAAO,KAAK,mBAAmB,aAAa,CAAC,IAAI,EAAE,UAAA,IAAmB;CAExE,OAAO;EAAE,UAAU,KAAK;EAAU,UAAA;CAAmB;AACvD;AAEA,SAAS,sBACP,IACA,MACA;CACA,MAAM,YAAY,yBAAyB,IAAI;CAC/C,QAAQ,KAAK,qBAAb;EACE,KAAK,UACH,OAAO,GAAG,UAAU;EACtB,KAAK,SACH,OAAO,cAAc,QAAQ,GAAG,UAAU,OAAO,GAAG,UAAU;EAChE,KAAK,aACH,OAAO,GAAG,UAAU;EACtB,SACE,OAAO,cAAc,QAAQ,GAAG,UAAU,QAAQ,GAAG,UAAU;CACnE;AACF;;AAGA,SAAgB,mBACd,YACA,WAA+C,MACb;CAClC,MAAM,eAAe,IAAI,IAAI,YAAY,KAAK,cAAc,UAAU,IAAI,CAAC;CAC3E,MAAM,SAAS,CACb,IAAI,YAAY,CAAC,EAAA,CAAG,QAAQ,cAAc,CAAC,aAAa,IAAI,UAAU,IAAI,CAAC,GAC3E,GAAI,cAAc,CAAC,CACrB;CACA,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,OAAO,OAAO,K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
@@ -1,7 +1,7 @@
1
1
  import { FontResolutionSettled } from "../../text/resolver/types.js";
2
2
  import { TextPreparationCache } from "./preparation/cache.js";
3
3
  import { CanvasKit, TypefaceFontProvider } from "canvaskit-wasm";
4
- import { SceneNode } from "@pairdraw/scene-graph";
4
+ import { ColorProfile, SceneNode } from "@pairdraw/scene-graph";
5
5
  //#region src/canvas/text/renderer.d.ts
6
6
  interface FontReadinessRenderer {
7
7
  textPreparationCache?: TextPreparationCache;
@@ -15,6 +15,7 @@ interface FontReadinessRenderer {
15
15
  }
16
16
  interface TextRenderer extends FontReadinessRenderer {
17
17
  ck: CanvasKit;
18
+ documentColorSpace?: ColorProfile;
18
19
  fontProvider: TypefaceFontProvider | null;
19
20
  fontsLoaded: boolean;
20
21
  }
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.d.ts","names":[],"sources":["../../../src/canvas/text/renderer.ts"],"mappings":";;;;;UAQiB;EACf,uBAAuB;EACvB,KAAK;EACL,eAAe;EACf;;EAEA;EACA,0BAA0B;EAC1B,mBAAmB,MAAM,WAAW;;UAGrB,qBAAqB;EACpC,IAAI;EACJ,cAAc;EACd"}
1
+ {"version":3,"file":"renderer.d.ts","names":[],"sources":["../../../src/canvas/text/renderer.ts"],"mappings":";;;;;UAQiB;EACf,uBAAuB;EACvB,KAAK;EACL,eAAe;EACf;;EAEA;EACA,0BAA0B;EAC1B,mBAAmB,MAAM,WAAW;;UAGrB,qBAAqB;EACpC,IAAI;EACJ,qBAAqB;EACrB,cAAc;EACd"}
@@ -1,13 +1,13 @@
1
1
  import { getCanvasKit } from "../../canvaskit.js";
2
2
  import "../../text/emoji.js";
3
3
  import { shownText } from "../../text/case.js";
4
- import { fontManager } from "../../text/font/manager.js";
5
4
  import { outlineInk, savedGlyphInk } from "./ink.js";
6
5
  import { keycapFrame } from "./keycap.js";
7
6
  import { characterFamily, laidOutGlyphs } from "./placed.js";
8
7
  import { textDecorationRects } from "./decorations.js";
9
8
  import { buildParagraph } from "./layout/build.js";
10
9
  import { faceStyleName } from "../../text/font/names.js";
10
+ import { leaseFontProvider } from "../../text/font/provider.js";
11
11
  import { nextGraphemeBoundary } from "../../text/graphemes.js";
12
12
  import { EMPTY_EXPORT_RUNTIME } from "@pairdraw/fig/node-change";
13
13
  import { textVerticalOffset } from "@pairdraw/scene-graph/text";
@@ -191,11 +191,11 @@ function needsShaping(graph) {
191
191
  * last to finish releases it; a provider with no share left is deleted.
192
192
  */
193
193
  async function withTextShaper(canvasKit, use) {
194
- const provider = fontManager.acquireProvider(canvasKit);
194
+ const lease = leaseFontProvider(canvasKit);
195
195
  try {
196
- return await use((node) => shapeText(canvasKit, provider, node));
196
+ return await use((node) => shapeText(canvasKit, lease.provider, node));
197
197
  } finally {
198
- fontManager.releaseProvider(provider);
198
+ lease.release();
199
199
  }
200
200
  }
201
201
  /** Run a `.fig` or Figma clipboard write with text shaping. */
@@ -1 +1 @@
1
- {"version":3,"file":"shape.js","names":[],"sources":["../../../src/canvas/text/shape.ts"],"sourcesContent":["import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'\n\nimport {\n EMPTY_EXPORT_RUNTIME,\n type FigNodeChangeExportRuntime,\n type PlacedTextGlyph,\n type ShapedText,\n type ShapedTextGlyph,\n type TextDecorationRecord\n} from '@pairdraw/fig/node-change'\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { textVerticalOffset } from '@pairdraw/scene-graph/text'\n\nimport { buildParagraph } from '#core/canvas/text'\nimport { textDecorationRects, type DecoratedGlyph } from '#core/canvas/text/decorations'\nimport { outlineInk, savedGlyphInk } from '#core/canvas/text/ink'\nimport { COMBINING_KEYCAP, keycapFrame } from '#core/canvas/text/keycap'\nimport { characterFamily, laidOutGlyphs, type LaidOutGlyph } from '#core/canvas/text/placed'\nimport { getCanvasKit } from '#core/canvaskit'\nimport { shownText } from '#core/text/case'\nimport { EMOJI_METRICS_FAMILY } from '#core/text/emoji'\nimport type { OutlineCommand } from '#core/text/font/glyphs'\nimport { fontManager } from '#core/text/font/manager'\nimport { faceStyleName } from '#core/text/font/names'\nimport { nextGraphemeBoundary } from '#core/text/graphemes'\n\n/**\n * Whether saved glyphs could stand for this text: case changes that alter its length move\n * glyphs off the characters they came from, and path text is placed along its path. Truncated\n * text saves the characters it shows and the ellipsis after them.\n */\nfunction canShape(node: SceneNode, text: string): boolean {\n return node.text.length > 0 && text.length === node.text.length && !node.textPathData\n}\n\n/** Characters inside a glyph cluster or without a glyph take the offset of the one before. */\nfunction completeCharacterOffsets(offsets: Array<number | undefined>): number[] {\n let previous = 0\n return offsets.map((offset) => {\n previous = offset ?? previous\n return previous\n })\n}\n\n/**\n * The square Figma saves for an emoji, in pixels at `size` with y down: 1 em wide, from 0.07 em\n * below the baseline, closed with a line back to its start as Figma writes it.\n */\nfunction emojiPlaceholder(size: number): OutlineCommand[] {\n const bottom = 0.07 * size\n const top = -0.93 * size\n return [\n { type: 'M', x: 0, y: bottom },\n { type: 'L', x: size, y: bottom },\n { type: 'L', x: size, y: top },\n { type: 'L', x: 0, y: top },\n { type: 'L', x: 0, y: bottom },\n { type: 'Z' }\n ]\n}\n\ninterface SavedEmoji {\n codePoints: number[]\n /** Where the emoji's characters end in the text. */\n end: number\n}\n\n/**\n * The emoji a glyph starts, as Figma saves it, when the layout gave it to the emoji metrics font:\n * its code points, an emoji that shows as text by default with the selector that asks for its\n * emoji form, as Figma saves ☺ as ☺️.\n */\nfunction savedEmoji(node: SceneNode, text: string, glyph: LaidOutGlyph): SavedEmoji | undefined {\n const start = glyph.firstCharacter\n if (start === undefined || characterFamily(node, text, start) !== EMOJI_METRICS_FAMILY)\n return undefined\n const end = nextGraphemeBoundary(text, start)\n const emoji = text.slice(start, end)\n const codePoints = Array.from(emoji, (character) => character.codePointAt(0) ?? 0)\n if (codePoints.length === 1 && !/\\p{Emoji_Presentation}/u.test(emoji)) codePoints.push(0xfe0f)\n return { codePoints, end }\n}\n\n/**\n * A glyph's saved outline: an emoji's placeholder, nothing inside one, a keycap's frame, or its\n * font's outline.\n */\nfunction savedOutline(\n glyph: LaidOutGlyph,\n text: string,\n emoji: SavedEmoji | undefined,\n insideEmoji: boolean\n): OutlineCommand[] | null {\n if (insideEmoji) return []\n if (emoji) return emojiPlaceholder(glyph.fontSize)\n const character = glyph.firstCharacter\n if (character !== undefined && text[character] === COMBINING_KEYCAP)\n return keycapFrame(glyph.fontSize)\n return glyph.source?.outline(glyph.id, glyph.fontSize) ?? null\n}\n\n/**\n * Lay a text node out as the renderer draws it and pair each shaped glyph with the outline of\n * the glyph ID CanvasKit chose, so ligatures and contextual forms keep their shapes. An emoji the\n * layout gives the emoji metrics font is saved as Figma saves one: a placeholder square with its\n * code points. When a run's font cannot be told, no glyph gets an outline: the layout still\n * stands and Pairdraw lays the text out again on reading, but Figma draws it blank.\n * Returns `null` for text saved glyphs cannot represent at all.\n */\nexport function shapeText(\n ck: CanvasKit,\n fontProvider: TypefaceFontProvider,\n node: SceneNode\n): ShapedText | null {\n const text = shownText(node)\n if (!canShape(node, text)) return null\n\n const paragraph = buildParagraph({ ck, fontProvider, fontsLoaded: true }, node, undefined, {\n halfLeading: true\n })\n try {\n const offsetY = textVerticalOffset(node, paragraph.getHeight())\n const placed = laidOutGlyphs(node, paragraph, text, offsetY)\n if (!placed) return null\n const metrics = paragraph.getLineMetrics()\n const characterOffsets: Array<number | undefined> = Array.from({ length: text.length })\n // A sequence the font does not join is several glyphs: the first stands for the emoji, and\n // the rest keep their place and draw nothing. Glyphs come in visual order, so in\n // right-to-left text a character before the emoji can follow it: the whole range counts.\n let emojiRange = { start: 0, end: 0 }\n const glyphs: ShapedTextGlyph[] = placed.map((glyph) => {\n const start = glyph.firstCharacter\n if (start !== undefined) characterOffsets[start] ??= glyph.x - glyph.lineLeft\n const insideEmoji = start !== undefined && start > emojiRange.start && start < emojiRange.end\n const emoji = insideEmoji ? undefined : savedEmoji(node, text, glyph)\n if (emoji && start !== undefined) emojiRange = { start, end: emoji.end }\n return {\n commands: savedOutline(glyph, text, emoji, insideEmoji),\n x: glyph.x,\n y: glyph.y,\n fontSize: glyph.fontSize,\n firstCharacter: start,\n advance: glyph.advance,\n emojiCodePoints: emoji?.codePoints\n }\n })\n // Outlines from some runs only would draw the text with characters missing.\n const outlined = glyphs.every((glyph) => glyph.commands)\n return {\n glyphs: outlined ? glyphs : glyphs.map((glyph) => ({ ...glyph, commands: null })),\n // Figma saves no baseline for the empty line after a closing line break.\n baselines: metrics\n .filter((line, index) => index === 0 || line.startIndex < text.length)\n .map((line) => ({\n firstCharacter: line.startIndex,\n endCharacter: Math.min(line.endIncludingNewline, text.length),\n position: { x: line.left, y: line.baseline + offsetY },\n width: line.width,\n lineY: line.baseline - line.ascent + offsetY,\n lineHeight: line.height,\n lineAscent: line.ascent\n })),\n logicalIndexToCharacterOffsetMap: completeCharacterOffsets(characterOffsets)\n }\n } finally {\n paragraph.delete()\n }\n}\n\nfunction decoratedGlyph(glyph: PlacedTextGlyph): DecoratedGlyph {\n const { commandsBlob, commands } = glyph\n return {\n ...glyph,\n ink: (top, bottom) => {\n if (commandsBlob) return savedGlyphInk(commandsBlob, glyph, top, bottom)\n return commands ? outlineInk(commands, glyph.x, glyph.y, top, bottom) : null\n }\n }\n}\n\n/** Decorations as Figma saves them, over glyphs saved or just shaped. */\nfunction textDecorations(\n node: SceneNode,\n glyphs: readonly PlacedTextGlyph[]\n): TextDecorationRecord[] {\n return textDecorationRects(node, glyphs.map(decoratedGlyph)).map(\n ({ firstCharacter, x, y, width, height }) => ({ firstCharacter, x, y, width, height })\n )\n}\n\nfunction needsShaping(graph: SceneGraph): boolean {\n for (const node of graph.nodes.values()) {\n if (node.type === 'TEXT' && node.text && !node.derivedTextGlyphs?.length) return true\n }\n return false\n}\n\n/**\n * Run `use` with text shaped as the canvas lays it out, from the font provider the canvas of\n * `canvasKit` draws from, or one a caller attached and registered faces on for layout alone.\n * Each call holds a share of that provider, so overlapping calls shape from the same one and the\n * last to finish releases it; a provider with no share left is deleted.\n */\nexport async function withTextShaper<T>(\n canvasKit: CanvasKit,\n use: (shape: (node: SceneNode) => ShapedText | null) => Promise<T>\n): Promise<T> {\n const provider = fontManager.acquireProvider(canvasKit)\n try {\n return await use((node) => shapeText(canvasKit, provider, node))\n } finally {\n fontManager.releaseProvider(provider)\n }\n}\n\n/** Run a `.fig` or Figma clipboard write with text shaping. */\nexport async function withFigExportRuntime<T>(\n graph: SceneGraph,\n ck: CanvasKit | undefined,\n write: (runtime: FigNodeChangeExportRuntime) => Promise<T>\n): Promise<T> {\n const named = { textDecorations, fontStyleName: faceStyleName }\n if (!needsShaping(graph)) return write({ ...EMPTY_EXPORT_RUNTIME, ...named })\n return withTextShaper(ck ?? (await getCanvasKit()), (shapeText) => write({ shapeText, ...named }))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,SAAS,SAAS,MAAiB,MAAuB;CACxD,OAAO,KAAK,KAAK,SAAS,KAAK,KAAK,WAAW,KAAK,KAAK,UAAU,CAAC,KAAK;AAC3E;;AAGA,SAAS,yBAAyB,SAA8C;CAC9E,IAAI,WAAW;CACf,OAAO,QAAQ,KAAK,WAAW;EAC7B,WAAW,UAAU;EACrB,OAAO;CACT,CAAC;AACH;;;;;AAMA,SAAS,iBAAiB,MAAgC;CACxD,MAAM,SAAS,MAAO;CACtB,MAAM,MAAM,OAAQ;CACpB,OAAO;EACL;GAAE,MAAM;GAAK,GAAG;GAAG,GAAG;EAAO;EAC7B;GAAE,MAAM;GAAK,GAAG;GAAM,GAAG;EAAO;EAChC;GAAE,MAAM;GAAK,GAAG;GAAM,GAAG;EAAI;EAC7B;GAAE,MAAM;GAAK,GAAG;GAAG,GAAG;EAAI;EAC1B;GAAE,MAAM;GAAK,GAAG;GAAG,GAAG;EAAO;EAC7B,EAAE,MAAM,IAAI;CACd;AACF;;;;;;AAaA,SAAS,WAAW,MAAiB,MAAc,OAA6C;CAC9F,MAAM,QAAQ,MAAM;CACpB,IAAI,UAAU,KAAA,KAAa,gBAAgB,MAAM,MAA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AC,CAAC,KAC1D,EAAE,gBAAgB,GAAG,GAAG,OAAO,cAAc;EAAE;EAAgB;EAAG;EAAG;EAAO;CAAO,EACtF;AACF;AAEA,SAAS,aAAa,OAA4B;CAChD,KAAK,MAAM,QAAQ,MAAM,MAAM,OAAO,GACpC,IAAI,KAAK,SAAS,UAAU,KAAK,QAAQ,CAAC,KAAK,mBAAmB,QAAQ,OAAO;CAEnF,OAAO;AACT;;;;;;;AAQA,eAAsB,eACpB,WACA,KACY;CACZ,MAAM,WAAW,YAAY,gBAAgB,SAAS;CACtD,IAAI;EACF,OAAO,MAAM,KAAK,SAAS,UAAU,WAAW,UAAU,IAAI,CAAC;CACjE,UAAU;EACR,YAAY,gBAAgB,QAAQ;CACtC;AACF;;AAGA,eAAsB,qBACpB,OACA,IACA,OACY;CACZ,MAAM,QAAQ;EAAE;EAAiB,eAAe;CAAc;CAC9D,IAAI,CAAC,aAAa,KAAK,GAAG,OAAO,MAAM;EAAE,GAAG;EAAsB,GAAG;CAAM,CAAC;CAC5E,OAAO,eAAe,MAAO,MAAM,aAAa,IAAK,cAAc,MAAM;EAAE;EAAW,GAAG;CAAM,CAAC,CAAC;AACnG"}
1
+ {"version":3,"file":"shape.js","names":[],"sources":["../../../src/canvas/text/shape.ts"],"sourcesContent":["import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'\n\nimport {\n EMPTY_EXPORT_RUNTIME,\n type FigNodeChangeExportRuntime,\n type PlacedTextGlyph,\n type ShapedText,\n type ShapedTextGlyph,\n type TextDecorationRecord\n} from '@pairdraw/fig/node-change'\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { textVerticalOffset } from '@pairdraw/scene-graph/text'\n\nimport { buildParagraph } from '#core/canvas/text'\nimport { textDecorationRects, type DecoratedGlyph } from '#core/canvas/text/decorations'\nimport { outlineInk, savedGlyphInk } from '#core/canvas/text/ink'\nimport { COMBINING_KEYCAP, keycapFrame } from '#core/canvas/text/keycap'\nimport { characterFamily, laidOutGlyphs, type LaidOutGlyph } from '#core/canvas/text/placed'\nimport { getCanvasKit } from '#core/canvaskit'\nimport { shownText } from '#core/text/case'\nimport { EMOJI_METRICS_FAMILY } from '#core/text/emoji'\nimport type { OutlineCommand } from '#core/text/font/glyphs'\nimport { faceStyleName } from '#core/text/font/names'\nimport { leaseFontProvider } from '#core/text/font/provider'\nimport { nextGraphemeBoundary } from '#core/text/graphemes'\n\n/**\n * Whether saved glyphs could stand for this text: case changes that alter its length move\n * glyphs off the characters they came from, and path text is placed along its path. Truncated\n * text saves the characters it shows and the ellipsis after them.\n */\nfunction canShape(node: SceneNode, text: string): boolean {\n return node.text.length > 0 && text.length === node.text.length && !node.textPathData\n}\n\n/** Characters inside a glyph cluster or without a glyph take the offset of the one before. */\nfunction completeCharacterOffsets(offsets: Array<number | undefined>): number[] {\n let previous = 0\n return offsets.map((offset) => {\n previous = offset ?? previous\n return previous\n })\n}\n\n/**\n * The square Figma saves for an emoji, in pixels at `size` with y down: 1 em wide, from 0.07 em\n * below the baseline, closed with a line back to its start as Figma writes it.\n */\nfunction emojiPlaceholder(size: number): OutlineCommand[] {\n const bottom = 0.07 * size\n const top = -0.93 * size\n return [\n { type: 'M', x: 0, y: bottom },\n { type: 'L', x: size, y: bottom },\n { type: 'L', x: size, y: top },\n { type: 'L', x: 0, y: top },\n { type: 'L', x: 0, y: bottom },\n { type: 'Z' }\n ]\n}\n\ninterface SavedEmoji {\n codePoints: number[]\n /** Where the emoji's characters end in the text. */\n end: number\n}\n\n/**\n * The emoji a glyph starts, as Figma saves it, when the layout gave it to the emoji metrics font:\n * its code points, an emoji that shows as text by default with the selector that asks for its\n * emoji form, as Figma saves ☺ as ☺️.\n */\nfunction savedEmoji(node: SceneNode, text: string, glyph: LaidOutGlyph): SavedEmoji | undefined {\n const start = glyph.firstCharacter\n if (start === undefined || characterFamily(node, text, start) !== EMOJI_METRICS_FAMILY)\n return undefined\n const end = nextGraphemeBoundary(text, start)\n const emoji = text.slice(start, end)\n const codePoints = Array.from(emoji, (character) => character.codePointAt(0) ?? 0)\n if (codePoints.length === 1 && !/\\p{Emoji_Presentation}/u.test(emoji)) codePoints.push(0xfe0f)\n return { codePoints, end }\n}\n\n/**\n * A glyph's saved outline: an emoji's placeholder, nothing inside one, a keycap's frame, or its\n * font's outline.\n */\nfunction savedOutline(\n glyph: LaidOutGlyph,\n text: string,\n emoji: SavedEmoji | undefined,\n insideEmoji: boolean\n): OutlineCommand[] | null {\n if (insideEmoji) return []\n if (emoji) return emojiPlaceholder(glyph.fontSize)\n const character = glyph.firstCharacter\n if (character !== undefined && text[character] === COMBINING_KEYCAP)\n return keycapFrame(glyph.fontSize)\n return glyph.source?.outline(glyph.id, glyph.fontSize) ?? null\n}\n\n/**\n * Lay a text node out as the renderer draws it and pair each shaped glyph with the outline of\n * the glyph ID CanvasKit chose, so ligatures and contextual forms keep their shapes. An emoji the\n * layout gives the emoji metrics font is saved as Figma saves one: a placeholder square with its\n * code points. When a run's font cannot be told, no glyph gets an outline: the layout still\n * stands and Pairdraw lays the text out again on reading, but Figma draws it blank.\n * Returns `null` for text saved glyphs cannot represent at all.\n */\nexport function shapeText(\n ck: CanvasKit,\n fontProvider: TypefaceFontProvider,\n node: SceneNode\n): ShapedText | null {\n const text = shownText(node)\n if (!canShape(node, text)) return null\n\n const paragraph = buildParagraph({ ck, fontProvider, fontsLoaded: true }, node, undefined, {\n halfLeading: true\n })\n try {\n const offsetY = textVerticalOffset(node, paragraph.getHeight())\n const placed = laidOutGlyphs(node, paragraph, text, offsetY)\n if (!placed) return null\n const metrics = paragraph.getLineMetrics()\n const characterOffsets: Array<number | undefined> = Array.from({ length: text.length })\n // A sequence the font does not join is several glyphs: the first stands for the emoji, and\n // the rest keep their place and draw nothing. Glyphs come in visual order, so in\n // right-to-left text a character before the emoji can follow it: the whole range counts.\n let emojiRange = { start: 0, end: 0 }\n const glyphs: ShapedTextGlyph[] = placed.map((glyph) => {\n const start = glyph.firstCharacter\n if (start !== undefined) characterOffsets[start] ??= glyph.x - glyph.lineLeft\n const insideEmoji = start !== undefined && start > emojiRange.start && start < emojiRange.end\n const emoji = insideEmoji ? undefined : savedEmoji(node, text, glyph)\n if (emoji && start !== undefined) emojiRange = { start, end: emoji.end }\n return {\n commands: savedOutline(glyph, text, emoji, insideEmoji),\n x: glyph.x,\n y: glyph.y,\n fontSize: glyph.fontSize,\n firstCharacter: start,\n advance: glyph.advance,\n emojiCodePoints: emoji?.codePoints\n }\n })\n // Outlines from some runs only would draw the text with characters missing.\n const outlined = glyphs.every((glyph) => glyph.commands)\n return {\n glyphs: outlined ? glyphs : glyphs.map((glyph) => ({ ...glyph, commands: null })),\n // Figma saves no baseline for the empty line after a closing line break.\n baselines: metrics\n .filter((line, index) => index === 0 || line.startIndex < text.length)\n .map((line) => ({\n firstCharacter: line.startIndex,\n endCharacter: Math.min(line.endIncludingNewline, text.length),\n position: { x: line.left, y: line.baseline + offsetY },\n width: line.width,\n lineY: line.baseline - line.ascent + offsetY,\n lineHeight: line.height,\n lineAscent: line.ascent\n })),\n logicalIndexToCharacterOffsetMap: completeCharacterOffsets(characterOffsets)\n }\n } finally {\n paragraph.delete()\n }\n}\n\nfunction decoratedGlyph(glyph: PlacedTextGlyph): DecoratedGlyph {\n const { commandsBlob, commands } = glyph\n return {\n ...glyph,\n ink: (top, bottom) => {\n if (commandsBlob) return savedGlyphInk(commandsBlob, glyph, top, bottom)\n return commands ? outlineInk(commands, glyph.x, glyph.y, top, bottom) : null\n }\n }\n}\n\n/** Decorations as Figma saves them, over glyphs saved or just shaped. */\nfunction textDecorations(\n node: SceneNode,\n glyphs: readonly PlacedTextGlyph[]\n): TextDecorationRecord[] {\n return textDecorationRects(node, glyphs.map(decoratedGlyph)).map(\n ({ firstCharacter, x, y, width, height }) => ({ firstCharacter, x, y, width, height })\n )\n}\n\nfunction needsShaping(graph: SceneGraph): boolean {\n for (const node of graph.nodes.values()) {\n if (node.type === 'TEXT' && node.text && !node.derivedTextGlyphs?.length) return true\n }\n return false\n}\n\n/**\n * Run `use` with text shaped as the canvas lays it out, from the font provider the canvas of\n * `canvasKit` draws from, or one a caller attached and registered faces on for layout alone.\n * Each call holds a share of that provider, so overlapping calls shape from the same one and the\n * last to finish releases it; a provider with no share left is deleted.\n */\nexport async function withTextShaper<T>(\n canvasKit: CanvasKit,\n use: (shape: (node: SceneNode) => ShapedText | null) => Promise<T>\n): Promise<T> {\n const lease = leaseFontProvider(canvasKit)\n try {\n return await use((node) => shapeText(canvasKit, lease.provider, node))\n } finally {\n lease.release()\n }\n}\n\n/** Run a `.fig` or Figma clipboard write with text shaping. */\nexport async function withFigExportRuntime<T>(\n graph: SceneGraph,\n ck: CanvasKit | undefined,\n write: (runtime: FigNodeChangeExportRuntime) => Promise<T>\n): Promise<T> {\n const named = { textDecorations, fontStyleName: faceStyleName }\n if (!needsShaping(graph)) return write({ ...EMPTY_EXPORT_RUNTIME, ...named })\n return withTextShaper(ck ?? (await getCanvasKit()), (shapeText) => write({ shapeText, ...named }))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,SAAS,SAAS,MAAiB,MAAuB;CACxD,OAAO,KAAK,KAAK,SAAS,KAAK,KAAK,WAAW,KAAK,KAAK,UAAU,CAAC,KAAK;AAC3E;;AAGA,SAAS,yBAAyB,SAA8C;CAC9E,IAAI,WAAW;CACf,OAAO,QAAQ,KAAK,WAAW;EAC7B,WAAW,UAAU;EACrB,OAAO;CACT,CAAC;AACH;;;;;AAMA,SAAS,iBAAiB,MAAgC;CACxD,MAAM,SAAS,MAAO;CACtB,MAAM,MAAM,OAAQ;CACpB,OAAO;EACL;GAAE,MAAM;GAAK,GAAG;GAAG,GAAG;EAAO;EAC7B;GAAE,MAAM;GAAK,GAAG;GAAM,GAAG;EAAO;EAChC;GAAE,MAAM;GAAK,GAAG;GAAM,GAAG;EAAI;EAC7B;GAAE,MAAM;GAAK,GAAG;GAAG,GAAG;EAAI;EAC1B;GAAE,MAAM;GAAK,GAAG;GAAG,GAAG;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WAAW,WAAW,UAAU,MAAM,GAAG,MAAM,GAAG,KAAK,MAAM,IAAI;EAC1E;CACF;AACF;;AAGA,SAAS,gBACP,MACA,QACwB;CACxB,OAAO,oBAAoB,MAAM,OAAO,IAAI,cAAc,CAAC,CAAC,CAAC,KAC1D,EAAE,gBAAgB,GAAG,GAAG,OAAO,cAAc;EAAE;EAAgB;EAAG;EAAG;EAAO;CAAO,EACtF;AACF;AAEA,SAAS,aAAa,OAA4B;CAChD,KAAK,MAAM,QAAQ,MAAM,MAAM,OAAO,GACpC,IAAI,KAAK,SAAS,UAAU,KAAK,QAAQ,CAAC,KAAK,mBAAmB,QAAQ,OAAO;CAEnF,OAAO;AACT;;;;;;;AAQA,eAAsB,eACpB,WACA,KACY;CACZ,MAAM,QAAQ,kBAAkB,SAAS;CACzC,IAAI;EACF,OAAO,MAAM,KAAK,SAAS,UAAU,WAAW,MAAM,UAAU,IAAI,CAAC;CACvE,UAAU;EACR,MAAM,QAAQ;CAChB;AACF;;AAGA,eAAsB,qBACpB,OACA,IACA,OACY;CACZ,MAAM,QAAQ;EAAE;EAAiB,eAAe;CAAc;CAC9D,IAAI,CAAC,aAAa,KAAK,GAAG,OAAO,MAAM;EAAE,GAAG;EAAsB,GAAG;CAAM,CAAC;CAC5E,OAAO,eAAe,MAAO,MAAM,aAAa,IAAK,cAAc,MAAM;EAAE;EAAW,GAAG;CAAM,CAAC,CAAC;AACnG"}
@@ -1 +1 @@
1
- {"version":3,"file":"texture.d.ts","names":[],"sources":["../../src/canvas/texture.ts"],"mappings":";;;;;;;;iBA0CgB,wBACd,GAAG,cACH,SAAS,eACT,eACC;;iBAkCa,gBAAgB,MAAM,YAAY;;;;;;iBAYlC,kBACd,GAAG,cACH,QAAQ,QACR,MAAM,WACN"}
1
+ {"version":3,"file":"texture.d.ts","names":[],"sources":["../../src/canvas/texture.ts"],"mappings":";;;;;;;;iBA2CgB,wBACd,GAAG,cACH,SAAS,eACT,eACC;;iBAkCa,gBAAgB,MAAM,YAAY;;;;;;iBAYlC,kBACd,GAAG,cACH,QAAQ,QACR,MAAM,WACN"}
@@ -1,3 +1,4 @@
1
+ import { skColorSpace } from "./renderer/colors.js";
1
2
  import { cellValue } from "./noise/tile.js";
2
3
  //#region src/canvas/texture.ts
3
4
  /** Cells on each side of a texture's displacement tile; it repeats beyond them. */
@@ -50,7 +51,7 @@ function textureDisplacementTile(r, texture, seed) {
50
51
  height: TEXTURE_TILE_CELLS,
51
52
  alphaType: r.ck.AlphaType.Unpremul,
52
53
  colorType: r.ck.ColorType.RGBA_8888,
53
- colorSpace: r.ck.ColorSpace.SRGB
54
+ colorSpace: skColorSpace(r.ck, r.documentColorSpace)
54
55
  }, pixels, TEXTURE_TILE_CELLS * 4);
55
56
  if (!image) return null;
56
57
  r.textureNoiseCache.set(key, image);
@@ -1 +1 @@
1
- {"version":3,"file":"texture.js","names":[],"sources":["../../src/canvas/texture.ts"],"sourcesContent":["import type { Canvas, Image, ImageFilter, Shader } from 'canvaskit-wasm'\n\nimport type { SceneNode, TextureEffect } from '@pairdraw/scene-graph'\n\nimport { cellValue } from './noise/tile'\nimport type { SkiaRenderer } from './renderer'\n\n/** Cells on each side of a texture's displacement tile; it repeats beyond them. */\nconst TEXTURE_TILE_CELLS = 256\n\nfunction smooth(t: number): number {\n return t * t * (3 - 2 * t)\n}\n\n/**\n * A cell's red or green displacement as smooth noise over `frequency` cells, sampled where the\n * layer's pixels are: one cycle per grain, and tileable because the corners wrap.\n */\nfunction displacement(x: number, y: number, frequency: number, seed: number, salt: number): number {\n const gx = x * frequency\n const gy = y * frequency\n const x0 = Math.floor(gx)\n const y0 = Math.floor(gy)\n const x1 = (x0 + 1) % TEXTURE_TILE_CELLS\n const y1 = (y0 + 1) % TEXTURE_TILE_CELLS\n const tx = smooth(gx - x0)\n const ty = smooth(gy - y0)\n const wrap = (value: number) =>\n ((value % TEXTURE_TILE_CELLS) + TEXTURE_TILE_CELLS) % TEXTURE_TILE_CELLS\n const v00 = cellValue(wrap(x0), wrap(y0), seed, salt)\n const v10 = cellValue(x1, wrap(y0), seed, salt)\n const v01 = cellValue(wrap(x0), y1, seed, salt)\n const v11 = cellValue(x1, y1, seed, salt)\n const top = v00 + (v10 - v00) * tx\n const bottom = v01 + (v11 - v01) * tx\n return top + (bottom - top) * ty\n}\n\n/**\n * The displacement tile for a texture: red and green as independent smooth noise one grain to a\n * cycle, as `feTurbulence` writes them, cached by grain size and seed.\n */\nexport function textureDisplacementTile(\n r: SkiaRenderer,\n texture: TextureEffect,\n seed: number\n): Image | null {\n const frequency = (size: number) => (size > 0 ? 1 / size : 0)\n const fx = frequency(texture.texture.noiseSize.x)\n const fy = frequency(texture.texture.noiseSize.y)\n const key = `texture:${fx}:${fy}:${seed}`\n const kept = r.textureNoiseCache.get(key)\n if (kept) return kept\n const pixels = new Uint8Array(TEXTURE_TILE_CELLS * TEXTURE_TILE_CELLS * 4)\n for (let y = 0; y < TEXTURE_TILE_CELLS; y++) {\n for (let x = 0; x < TEXTURE_TILE_CELLS; x++) {\n const at = (y * TEXTURE_TILE_CELLS + x) * 4\n pixels[at] = Math.floor(displacement(x, y, fx, seed, 1) * 256)\n pixels[at + 1] = Math.floor(displacement(x, y, fy, seed, 2) * 256)\n pixels[at + 2] = 0\n pixels[at + 3] = 255\n }\n }\n const image = r.ck.MakeImage(\n {\n width: TEXTURE_TILE_CELLS,\n height: TEXTURE_TILE_CELLS,\n alphaType: r.ck.AlphaType.Unpremul,\n colorType: r.ck.ColorType.RGBA_8888,\n colorSpace: r.ck.ColorSpace.SRGB\n },\n pixels,\n TEXTURE_TILE_CELLS * 4\n )\n if (!image) return null\n r.textureNoiseCache.set(key, image)\n return image\n}\n\n/** The first visible texture effect on a layer, which roughens its edges. */\nexport function textureEffectOf(node: SceneNode): TextureEffect | null {\n for (const effect of node.effects) {\n if (effect.visible && effect.type === 'TEXTURE' && effect.radius > 0) return effect\n }\n return null\n}\n\n/**\n * Draws a layer's content through the displacement of its texture effect: the noise moves each\n * pixel by up to `radius`, as Figma's filter does, and `clipToShape` keeps the moved pixels inside\n * the layer's box. Returns false when there is no texture to draw, so a caller draws as usual.\n */\nexport function withTextureEffect(\n r: SkiaRenderer,\n canvas: Canvas,\n node: SceneNode,\n draw: () => void\n): boolean {\n const texture = textureEffectOf(node)\n if (!texture) return false\n const tile = textureDisplacementTile(r, texture, texture.texture.seed ?? 0)\n if (!tile) return false\n const repeat = r.ck.TileMode.Repeat\n const shader: Shader = tile.makeShaderOptions(\n repeat,\n repeat,\n r.ck.FilterMode.Linear,\n r.ck.MipmapMode.None\n )\n const displacement: ImageFilter = r.ck.ImageFilter.MakeShader(shader)\n const filter: ImageFilter = r.ck.ImageFilter.MakeDisplacementMap(\n r.ck.ColorChannel.Red,\n r.ck.ColorChannel.Green,\n texture.radius * 2,\n displacement,\n null\n )\n const paint = new r.ck.Paint()\n try {\n paint.setImageFilter(filter)\n const rect = r.ck.LTRBRect(0, 0, node.width, node.height)\n if (texture.texture.clipToShape) r.clipNodeShape(canvas, node)\n canvas.saveLayer(paint, rect)\n try {\n draw()\n } finally {\n canvas.restore()\n }\n } finally {\n paint.delete()\n filter.delete()\n displacement.delete()\n shader.delete()\n }\n return true\n}\n"],"mappings":";;;AAQA,MAAM,qBAAqB;AAE3B,SAAS,OAAO,GAAmB;CACjC,OAAO,IAAI,KAAK,IAAI,IAAI;AAC1B;;;;;AAMA,SAAS,aAAa,GAAW,GAAW,WAAmB,MAAc,MAAsB;CACjG,MAAM,KAAK,IAAI;CACf,MAAM,KAAK,IAAI;CACf,MAAM,KAAK,KAAK,MAAM,EAAE;CACxB,MAAM,KAAK,KAAK,MAAM,EAAE;CACxB,MAAM,MAAM,KAAK,KAAK;CACtB,MAAM,MAAM,KAAK,KAAK;CACtB,MAAM,KAAK,OAAO,KAAK,EAAE;CACzB,MAAM,KAAK,OAAO,KAAK,EAAE;CACzB,MAAM,QAAQ,WACV,QAAQ,qBAAsB,sBAAsB;CACxD,MAAM,MAAM,UAAU,KAAK,EAAE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AE,kBAAkB,IAAI,KAAK,KAAK;CAClC,OAAO;AACT;;AAGA,SAAgB,gBAAgB,MAAuC;CACrE,KAAK,MAAM,UAAU,KAAK,SACxB,IAAI,OAAO,WAAW,OAAO,SAAS,aAAa,OAAO,SAAS,GAAG,OAAO;CAE/E,OAAO;AACT;;;;;;AAOA,SAAgB,kBACd,GACA,QACA,MACA,MACS;CACT,MAAM,UAAU,gBAAgB,IAAI;CACpC,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,OAAO,wBAAwB,GAAG,SAAS,QAAQ,QAAQ,QAAQ,CAAC;CAC1E,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,SAAS,EAAE,GAAG,SAAS;CAC7B,MAAM,SAAiB,KAAK,kBAC1B,QACA,QACA,EAAE,GAAG,WAAW,QAChB,EAAE,GAAG,WAAW,IAClB;CACA,MAAM,eAA4B,EAAE,GAAG,YAAY,WAAW,MAAM;CACpE,MAAM,SAAsB,EAAE,GAAG,YAAY,oBAC3C,EAAE,GAAG,aAAa,KAClB,EAAE,GAAG,aAAa,OAClB,QAAQ,SAAS,GACjB,cACA,IACF;CACA,MAAM,QAAQ,IAAI,EAAE,GAAG,MAAM;CAC7B,IAAI;EACF,MAAM,eAAe,MAAM;EAC3B,MAAM,OAAO,EAAE,GAAG,SAAS,GAAG,GAAG,KAAK,OAAO,KAAK,MAAM;EACxD,IAAI,QAAQ,QAAQ,aAAa,EAAE,cAAc,QAAQ,IAAI;EAC7D,OAAO,UAAU,OAAO,IAAI;EAC5B,IAAI;GACF,KAAK;EACP,UAAU;GACR,OAAO,QAAQ;EACjB;CACF,UAAU;EACR,MAAM,OAAO;EACb,OAAO,OAAO;EACd,aAAa,OAAO;EACpB,OAAO,OAAO;CAChB;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"texture.js","names":[],"sources":["../../src/canvas/texture.ts"],"sourcesContent":["import type { Canvas, Image, ImageFilter, Shader } from 'canvaskit-wasm'\n\nimport type { SceneNode, TextureEffect } from '@pairdraw/scene-graph'\n\nimport { cellValue } from './noise/tile'\nimport type { SkiaRenderer } from './renderer'\nimport { skColorSpace } from './renderer/colors'\n\n/** Cells on each side of a texture's displacement tile; it repeats beyond them. */\nconst TEXTURE_TILE_CELLS = 256\n\nfunction smooth(t: number): number {\n return t * t * (3 - 2 * t)\n}\n\n/**\n * A cell's red or green displacement as smooth noise over `frequency` cells, sampled where the\n * layer's pixels are: one cycle per grain, and tileable because the corners wrap.\n */\nfunction displacement(x: number, y: number, frequency: number, seed: number, salt: number): number {\n const gx = x * frequency\n const gy = y * frequency\n const x0 = Math.floor(gx)\n const y0 = Math.floor(gy)\n const x1 = (x0 + 1) % TEXTURE_TILE_CELLS\n const y1 = (y0 + 1) % TEXTURE_TILE_CELLS\n const tx = smooth(gx - x0)\n const ty = smooth(gy - y0)\n const wrap = (value: number) =>\n ((value % TEXTURE_TILE_CELLS) + TEXTURE_TILE_CELLS) % TEXTURE_TILE_CELLS\n const v00 = cellValue(wrap(x0), wrap(y0), seed, salt)\n const v10 = cellValue(x1, wrap(y0), seed, salt)\n const v01 = cellValue(wrap(x0), y1, seed, salt)\n const v11 = cellValue(x1, y1, seed, salt)\n const top = v00 + (v10 - v00) * tx\n const bottom = v01 + (v11 - v01) * tx\n return top + (bottom - top) * ty\n}\n\n/**\n * The displacement tile for a texture: red and green as independent smooth noise one grain to a\n * cycle, as `feTurbulence` writes them, cached by grain size and seed.\n */\nexport function textureDisplacementTile(\n r: SkiaRenderer,\n texture: TextureEffect,\n seed: number\n): Image | null {\n const frequency = (size: number) => (size > 0 ? 1 / size : 0)\n const fx = frequency(texture.texture.noiseSize.x)\n const fy = frequency(texture.texture.noiseSize.y)\n const key = `texture:${fx}:${fy}:${seed}`\n const kept = r.textureNoiseCache.get(key)\n if (kept) return kept\n const pixels = new Uint8Array(TEXTURE_TILE_CELLS * TEXTURE_TILE_CELLS * 4)\n for (let y = 0; y < TEXTURE_TILE_CELLS; y++) {\n for (let x = 0; x < TEXTURE_TILE_CELLS; x++) {\n const at = (y * TEXTURE_TILE_CELLS + x) * 4\n pixels[at] = Math.floor(displacement(x, y, fx, seed, 1) * 256)\n pixels[at + 1] = Math.floor(displacement(x, y, fy, seed, 2) * 256)\n pixels[at + 2] = 0\n pixels[at + 3] = 255\n }\n }\n const image = r.ck.MakeImage(\n {\n width: TEXTURE_TILE_CELLS,\n height: TEXTURE_TILE_CELLS,\n alphaType: r.ck.AlphaType.Unpremul,\n colorType: r.ck.ColorType.RGBA_8888,\n colorSpace: skColorSpace(r.ck, r.documentColorSpace)\n },\n pixels,\n TEXTURE_TILE_CELLS * 4\n )\n if (!image) return null\n r.textureNoiseCache.set(key, image)\n return image\n}\n\n/** The first visible texture effect on a layer, which roughens its edges. */\nexport function textureEffectOf(node: SceneNode): TextureEffect | null {\n for (const effect of node.effects) {\n if (effect.visible && effect.type === 'TEXTURE' && effect.radius > 0) return effect\n }\n return null\n}\n\n/**\n * Draws a layer's content through the displacement of its texture effect: the noise moves each\n * pixel by up to `radius`, as Figma's filter does, and `clipToShape` keeps the moved pixels inside\n * the layer's box. Returns false when there is no texture to draw, so a caller draws as usual.\n */\nexport function withTextureEffect(\n r: SkiaRenderer,\n canvas: Canvas,\n node: SceneNode,\n draw: () => void\n): boolean {\n const texture = textureEffectOf(node)\n if (!texture) return false\n const tile = textureDisplacementTile(r, texture, texture.texture.seed ?? 0)\n if (!tile) return false\n const repeat = r.ck.TileMode.Repeat\n const shader: Shader = tile.makeShaderOptions(\n repeat,\n repeat,\n r.ck.FilterMode.Linear,\n r.ck.MipmapMode.None\n )\n const displacement: ImageFilter = r.ck.ImageFilter.MakeShader(shader)\n const filter: ImageFilter = r.ck.ImageFilter.MakeDisplacementMap(\n r.ck.ColorChannel.Red,\n r.ck.ColorChannel.Green,\n texture.radius * 2,\n displacement,\n null\n )\n const paint = new r.ck.Paint()\n try {\n paint.setImageFilter(filter)\n const rect = r.ck.LTRBRect(0, 0, node.width, node.height)\n if (texture.texture.clipToShape) r.clipNodeShape(canvas, node)\n canvas.saveLayer(paint, rect)\n try {\n draw()\n } finally {\n canvas.restore()\n }\n } finally {\n paint.delete()\n filter.delete()\n displacement.delete()\n shader.delete()\n }\n return true\n}\n"],"mappings":";;;;AASA,MAAM,qBAAqB;AAE3B,SAAS,OAAO,GAAmB;CACjC,OAAO,IAAI,KAAK,IAAI,IAAI;AAC1B;;;;;AAMA,SAAS,aAAa,GAAW,GAAW,WAAmB,MAAc,MAAsB;CACjG,MAAM,KAAK,IAAI;CACf,MAAM,KAAK,IAAI;CACf,MAAM,KAAK,KAAK,MAAM,EAAE;CACxB,MAAM,KAAK,KAAK,MAAM,EAAE;CACxB,MAAM,MAAM,KAAK,KAAK;CACtB,MAAM,MAAM,KAAK,KAAK;CACtB,MAAM,KAAK,OAAO,KAAK,EAAE;CACzB,MAAM,KAAK,OAAO,KAAK,EAAE;CACzB,MAAM,QAAQ,WACV,QAAQ,qBAAsB,sBAAsB;CACxD,MAAM,MAAM,UAAU,KAAK,EAAE,GAAG,KAAK,EAAE,GAAG,MAAM,IAAI;CACpD,MAAM,MAAM,UAAU,IAAI,KAAK,EAAE,GAAG,MAAM,IAAI;CAC9C,MAAM,MAAM,UAAU,KAAK,EAAE,GAAG,IAAI,MAAM,IAAI;CAC9C,MAAM,MAAM,UAAU,IAAI,IAAI,MAAM,IAAI;CACxC,MAAM,MAAM,OAAO,MAAM,OAAO;CAEhC,OAAO,OADQ,OAAO,MAAM,OAAO,KACZ,OAAO;AAChC;;;;;AAMA,SAAgB,wBACd,GACA,SACA,MACc;CACd,MAAM,aAAa,SAAkB,OAAO,IAAI,IAAI,OAAO;CAC3D,MAAM,KAAK,UAAU,QAAQ,QAAQ,UAAU,CAAC;CAChD,MAAM,KAAK,UAAU,QAAQ,QAAQ,UAAU,CAAC;CAChD,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG;CACnC,MAAM,OAAO,EAAE,kBAAkB,IAAI,GAAG;CACxC,IAAI,MAAM,OAAO;CACjB,MAAM,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AAY,oBAC3C,EAAE,GAAG,aAAa,KAClB,EAAE,GAAG,aAAa,OAClB,QAAQ,SAAS,GACjB,cACA,IACF;CACA,MAAM,QAAQ,IAAI,EAAE,GAAG,MAAM;CAC7B,IAAI;EACF,MAAM,eAAe,MAAM;EAC3B,MAAM,OAAO,EAAE,GAAG,SAAS,GAAG,GAAG,KAAK,OAAO,KAAK,MAAM;EACxD,IAAI,QAAQ,QAAQ,aAAa,EAAE,cAAc,QAAQ,IAAI;EAC7D,OAAO,UAAU,OAAO,IAAI;EAC5B,IAAI;GACF,KAAK;EACP,UAAU;GACR,OAAO,QAAQ;EACjB;CACF,UAAU;EACR,MAAM,OAAO;EACb,OAAO,OAAO;EACd,aAAa,OAAO;EACpB,OAAO,OAAO;CAChB;CACA,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
1
  import { resolveVariable } from "@pairdraw/scene-graph/variables";
2
- import { uniqBy } from "es-toolkit/array";
3
2
  import { colorToHex } from "@pairdraw/scene-graph/color";
3
+ import { uniqBy } from "es-toolkit/array";
4
4
  import { DESIGN_MEMORY_GROUPS } from "@pairdraw/scene-graph/design-memory";
5
5
  import { converter } from "culori";
6
6
  //#region src/design-memory/rules.ts
@@ -1 +1 @@
1
- {"version":3,"file":"assets.d.ts","names":[],"sources":["../../../src/editor/clipboard/assets.ts"],"mappings":";;KA0CK,wBACH,mBACA,mBAAmB,aACnB;iBAGc,4BACd,KAAK,eACL,sBAAsB;EAEK,aAAA,OAAA;EAyHM,aAAA,OAAA,QAAM,YAAY,eAAY;EAsC/B,kBAAA,OAAA,QAAM,YAAY,eAAY;EA7B9B,WAAA,gBAAM,YAAY,eAAe;EAY/B,eAAA,cAAM,YAAY,eAAe"}
1
+ {"version":3,"file":"assets.d.ts","names":[],"sources":["../../../src/editor/clipboard/assets.ts"],"mappings":";;KA0CK,wBACH,mBACA,mBAAmB,aACnB;iBAGc,4BACd,KAAK,eACL,sBAAsB;EAEK,aAAA,OAAA;EA2HM,aAAA,OAAA,QAAM,YAAY,eAAY;EAwC/B,kBAAA,OAAA,QAAM,YAAY,eAAY;EA/B9B,WAAA,gBAAM,YAAY,eAAe;EAc/B,eAAA,cAAM,YAAY,eAAe"}
@@ -38,7 +38,7 @@ function createClipboardAssetActions(ctx, pushCreatedNodesUndo) {
38
38
  }
39
39
  async function prepareAsset(file) {
40
40
  if (isSVGFile(file)) {
41
- const data = prepareSVGImport(await file.text());
41
+ const data = prepareSVGImport(await file.text(), { profile: ctx.graph.documentColorSpace });
42
42
  return data ? {
43
43
  kind: "svg",
44
44
  data,
@@ -133,7 +133,7 @@ function createClipboardAssetActions(ctx, pushCreatedNodesUndo) {
133
133
  }
134
134
  /** Paste SVG markup as layers, as Figma does; false when the text is not SVG. */
135
135
  async function pasteSVG(markup, cx, cy) {
136
- const data = isSVGMarkup(markup) ? prepareSVGImport(markup) : null;
136
+ const data = isSVGMarkup(markup) ? prepareSVGImport(markup, { profile: ctx.graph.documentColorSpace }) : null;
137
137
  if (!data) return false;
138
138
  const asset = {
139
139
  kind: "svg",
@@ -1 +1 @@
1
- {"version":3,"file":"assets.js","names":[],"sources":["../../../src/editor/clipboard/assets.ts"],"sourcesContent":["import { sumBy } from 'es-toolkit'\nimport { filename } from 'pathe/utils'\n\nimport type { Fill } from '@pairdraw/scene-graph'\nimport { getWorldMatrix } from '@pairdraw/scene-graph/coordinate'\nimport { computeImageHash, IMPORTABLE_RASTER_TYPES, isSVGFile } from '@pairdraw/scene-graph/images'\nimport Matrix from '@pairdraw/scene-graph/matrix'\n\nimport { TRANSPARENT } from '#core/constants'\nimport { resolvePasteTarget } from '#core/editor/clipboard/paste/target'\nimport type { EditorContext } from '#core/editor/types'\nimport {\n createSVGNodesFromImport,\n isSVGMarkup,\n prepareSVGImport,\n svgImportFonts,\n type SVGImportData\n} from '#core/io/formats/svg'\nimport { computeAllLayouts } from '#core/layout'\n\nconst IMAGE_MAX_DIMENSION = 4096\nconst ASSET_GAP = 20\n\ninterface PreparedRasterAsset {\n kind: 'raster'\n bytes: Uint8Array\n name: string\n width: number\n height: number\n}\n\ninterface PreparedSVGAsset {\n kind: 'svg'\n data: SVGImportData\n /** A dropped file's name; pasted markup is named as Figma names it. */\n name?: string\n width: number\n height: number\n}\n\ntype PreparedAsset = PreparedRasterAsset | PreparedSVGAsset\n\ntype PushCreatedNodesUndo = (\n created: string[],\n previousSelection: Set<string>,\n label?: string\n) => void\n\nexport function createClipboardAssetActions(\n ctx: EditorContext,\n pushCreatedNodesUndo: PushCreatedNodesUndo\n) {\n function storeImage(bytes: Uint8Array): string {\n const hash = computeImageHash(bytes)\n ctx.graph.images.set(hash, bytes)\n return hash\n }\n\n function decodeImageDimensions(bytes: Uint8Array): { width: number; height: number } | null {\n const ck = ctx.getCk()\n if (!ck) return null\n const skImg = ck.MakeImageFromEncoded(bytes)\n if (!skImg) return null\n let width = skImg.width()\n let height = skImg.height()\n skImg.delete()\n if (width > IMAGE_MAX_DIMENSION || height > IMAGE_MAX_DIMENSION) {\n const ratio = Math.min(IMAGE_MAX_DIMENSION / width, IMAGE_MAX_DIMENSION / height)\n width = Math.round(width * ratio)\n height = Math.round(height * ratio)\n }\n return { width, height }\n }\n\n async function prepareAsset(file: File): Promise<PreparedAsset | null> {\n if (isSVGFile(file)) {\n const data = prepareSVGImport(await file.text())\n return data\n ? {\n kind: 'svg',\n data,\n name: filename(file.name) || undefined,\n width: data.width,\n height: data.height\n }\n : null\n }\n if (!IMPORTABLE_RASTER_TYPES.has(file.type)) return null\n const bytes = new Uint8Array(await file.arrayBuffer())\n const dimensions = decodeImageDimensions(bytes)\n return dimensions ? { kind: 'raster', bytes, name: file.name, ...dimensions } : null\n }\n\n function parentLocalPoint(parentId: string, x: number, y: number) {\n const parent = ctx.graph.getNode(parentId)\n if (!parent) return { x, y }\n const inverse = Matrix.invert(getWorldMatrix(parent, ctx.graph))\n return inverse ? Matrix.mapPoint(inverse, { x, y }) : { x, y }\n }\n\n function createRasterNode(\n asset: PreparedRasterAsset,\n parentId: string,\n x: number,\n y: number\n ): string {\n const hash = storeImage(asset.bytes)\n const fill: Fill = {\n type: 'IMAGE',\n imageHash: hash,\n imageScaleMode: 'FILL',\n color: TRANSPARENT,\n opacity: 1,\n visible: true\n }\n return ctx.graph.createNode('RECTANGLE', parentId, {\n name: filename(asset.name) ?? asset.name,\n x,\n y,\n width: asset.width,\n height: asset.height,\n fills: [fill]\n }).id\n }\n\n function placeAssets(prepared: PreparedAsset[], cx: number, cy: number, label: string): boolean {\n if (prepared.length === 0) return false\n\n const previousSelection = new Set(ctx.state.selectedIds)\n const parentId = resolvePasteTarget(ctx)\n const center = parentLocalPoint(parentId, cx, cy)\n const totalWidth = sumBy(prepared, (asset) => asset.width) + ASSET_GAP * (prepared.length - 1)\n const maxHeight = Math.max(...prepared.map((asset) => asset.height))\n let x = center.x - totalWidth / 2\n const y = center.y - maxHeight / 2\n const created: string[] = []\n\n try {\n for (const asset of prepared) {\n const id =\n asset.kind === 'raster'\n ? createRasterNode(asset, parentId, x, y)\n : createSVGNodesFromImport(ctx.graph, parentId, asset.data, {\n name: asset.name,\n x,\n y\n })?.id\n if (id) created.push(id)\n x += asset.width + ASSET_GAP\n }\n } catch (error) {\n for (const id of created.reverse()) ctx.graph.deleteNode(id)\n throw error\n }\n\n if (created.length === 0) return false\n computeAllLayouts(ctx.graph, ctx.state.currentPageId)\n ctx.setSelectedIds(new Set(created))\n pushCreatedNodesUndo(created, previousSelection, label)\n ctx.requestRender()\n return true\n }\n\n /** Load the fonts of imported SVG text, so it is measured and placed with them. */\n async function loadSVGFonts(assets: PreparedAsset[]) {\n const fonts = assets.flatMap((asset) =>\n asset.kind === 'svg' ? svgImportFonts(asset.data) : []\n )\n await Promise.all(\n fonts.map((font) => ctx.loadFont(font.family, font.style, font.characters).catch(() => null))\n )\n }\n\n async function placeFiles(files: File[], cx: number, cy: number) {\n const prepared = (await Promise.all(files.map(prepareAsset))).filter(\n (asset): asset is PreparedAsset => asset !== null\n )\n await loadSVGFonts(prepared)\n placeAssets(prepared, cx, cy, 'Place files')\n }\n\n /** Paste SVG markup as layers, as Figma does; false when the text is not SVG. */\n async function pasteSVG(markup: string, cx: number, cy: number): Promise<boolean> {\n const data = isSVGMarkup(markup) ? prepareSVGImport(markup) : null\n if (!data) return false\n const asset: PreparedAsset = { kind: 'svg', data, width: data.width, height: data.height }\n await loadSVGFonts([asset])\n return placeAssets([asset], cx, cy, 'Paste SVG')\n }\n\n /**\n * Paste a Mermaid flowchart as FigJam shapes, sections, and connectors, laid out and centred on\n * the point; false when the text is not one.\n */\n async function pasteMermaid(text: string, cx: number, cy: number): Promise<boolean> {\n const { detectMermaidDiagram, parseFlowchart } = await import('@pairdraw/mermaid')\n if (!detectMermaidDiagram(text)) return false\n const chart = parseFlowchart(text)\n const { addFlowchart } = await import('#core/io/formats/mermaid')\n const previousSelection = new Set(ctx.state.selectedIds)\n const parentId = resolvePasteTarget(ctx)\n const { ids: created } = await addFlowchart(ctx.graph, parentId, chart, {\n center: parentLocalPoint(parentId, cx, cy)\n })\n if (created.length === 0) return false\n ctx.setSelectedIds(new Set(created))\n pushCreatedNodesUndo(created, previousSelection, 'Paste Mermaid')\n ctx.requestRender()\n return true\n }\n\n function placeImageFiles(files: File[], cx: number, cy: number) {\n return placeFiles(\n files.filter((file) => IMPORTABLE_RASTER_TYPES.has(file.type)),\n cx,\n cy\n )\n }\n\n return { storeImage, placeFiles, placeImageFiles, pasteSVG, pasteMermaid }\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAM,sBAAsB;AAC5B,MAAM,YAAY;AA2BlB,SAAgB,4BACd,KACA,sBACA;CACA,SAAS,WAAW,OAA2B;EAC7C,MAAM,OAAO,iBAAiB,KAAK;EACnC,IAAI,MAAM,OAAO,IAAI,MAAM,KAAK;EAChC,OAAO;CACT;CAEA,SAAS,sBAAsB,OAA6D;EAC1F,MAAM,KAAK,IAAI,MAAM;EACrB,IAAI,CAAC,IAAI,OAAO;EAChB,MAAM,QAAQ,GAAG,qBAAqB,KAA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B,SAAS,mBAAmB,eAAe;EAChE,IAAI,cAAc;EAClB,OAAO;CACT;CAEA,SAAS,gBAAgB,OAAe,IAAY,IAAY;EAC9D,OAAO,WACL,MAAM,QAAQ,SAAS,wBAAwB,IAAI,KAAK,IAAI,CAAC,GAC7D,IACA,EACF;CACF;CAEA,OAAO;EAAE;EAAY;EAAY;EAAiB;EAAU;CAAa;AAC3E"}
1
+ {"version":3,"file":"assets.js","names":[],"sources":["../../../src/editor/clipboard/assets.ts"],"sourcesContent":["import { sumBy } from 'es-toolkit'\nimport { filename } from 'pathe/utils'\n\nimport type { Fill } from '@pairdraw/scene-graph'\nimport { getWorldMatrix } from '@pairdraw/scene-graph/coordinate'\nimport { computeImageHash, IMPORTABLE_RASTER_TYPES, isSVGFile } from '@pairdraw/scene-graph/images'\nimport Matrix from '@pairdraw/scene-graph/matrix'\n\nimport { TRANSPARENT } from '#core/constants'\nimport { resolvePasteTarget } from '#core/editor/clipboard/paste/target'\nimport type { EditorContext } from '#core/editor/types'\nimport {\n createSVGNodesFromImport,\n isSVGMarkup,\n prepareSVGImport,\n svgImportFonts,\n type SVGImportData\n} from '#core/io/formats/svg'\nimport { computeAllLayouts } from '#core/layout'\n\nconst IMAGE_MAX_DIMENSION = 4096\nconst ASSET_GAP = 20\n\ninterface PreparedRasterAsset {\n kind: 'raster'\n bytes: Uint8Array\n name: string\n width: number\n height: number\n}\n\ninterface PreparedSVGAsset {\n kind: 'svg'\n data: SVGImportData\n /** A dropped file's name; pasted markup is named as Figma names it. */\n name?: string\n width: number\n height: number\n}\n\ntype PreparedAsset = PreparedRasterAsset | PreparedSVGAsset\n\ntype PushCreatedNodesUndo = (\n created: string[],\n previousSelection: Set<string>,\n label?: string\n) => void\n\nexport function createClipboardAssetActions(\n ctx: EditorContext,\n pushCreatedNodesUndo: PushCreatedNodesUndo\n) {\n function storeImage(bytes: Uint8Array): string {\n const hash = computeImageHash(bytes)\n ctx.graph.images.set(hash, bytes)\n return hash\n }\n\n function decodeImageDimensions(bytes: Uint8Array): { width: number; height: number } | null {\n const ck = ctx.getCk()\n if (!ck) return null\n const skImg = ck.MakeImageFromEncoded(bytes)\n if (!skImg) return null\n let width = skImg.width()\n let height = skImg.height()\n skImg.delete()\n if (width > IMAGE_MAX_DIMENSION || height > IMAGE_MAX_DIMENSION) {\n const ratio = Math.min(IMAGE_MAX_DIMENSION / width, IMAGE_MAX_DIMENSION / height)\n width = Math.round(width * ratio)\n height = Math.round(height * ratio)\n }\n return { width, height }\n }\n\n async function prepareAsset(file: File): Promise<PreparedAsset | null> {\n if (isSVGFile(file)) {\n const data = prepareSVGImport(await file.text(), {\n profile: ctx.graph.documentColorSpace\n })\n return data\n ? {\n kind: 'svg',\n data,\n name: filename(file.name) || undefined,\n width: data.width,\n height: data.height\n }\n : null\n }\n if (!IMPORTABLE_RASTER_TYPES.has(file.type)) return null\n const bytes = new Uint8Array(await file.arrayBuffer())\n const dimensions = decodeImageDimensions(bytes)\n return dimensions ? { kind: 'raster', bytes, name: file.name, ...dimensions } : null\n }\n\n function parentLocalPoint(parentId: string, x: number, y: number) {\n const parent = ctx.graph.getNode(parentId)\n if (!parent) return { x, y }\n const inverse = Matrix.invert(getWorldMatrix(parent, ctx.graph))\n return inverse ? Matrix.mapPoint(inverse, { x, y }) : { x, y }\n }\n\n function createRasterNode(\n asset: PreparedRasterAsset,\n parentId: string,\n x: number,\n y: number\n ): string {\n const hash = storeImage(asset.bytes)\n const fill: Fill = {\n type: 'IMAGE',\n imageHash: hash,\n imageScaleMode: 'FILL',\n color: TRANSPARENT,\n opacity: 1,\n visible: true\n }\n return ctx.graph.createNode('RECTANGLE', parentId, {\n name: filename(asset.name) ?? asset.name,\n x,\n y,\n width: asset.width,\n height: asset.height,\n fills: [fill]\n }).id\n }\n\n function placeAssets(prepared: PreparedAsset[], cx: number, cy: number, label: string): boolean {\n if (prepared.length === 0) return false\n\n const previousSelection = new Set(ctx.state.selectedIds)\n const parentId = resolvePasteTarget(ctx)\n const center = parentLocalPoint(parentId, cx, cy)\n const totalWidth = sumBy(prepared, (asset) => asset.width) + ASSET_GAP * (prepared.length - 1)\n const maxHeight = Math.max(...prepared.map((asset) => asset.height))\n let x = center.x - totalWidth / 2\n const y = center.y - maxHeight / 2\n const created: string[] = []\n\n try {\n for (const asset of prepared) {\n const id =\n asset.kind === 'raster'\n ? createRasterNode(asset, parentId, x, y)\n : createSVGNodesFromImport(ctx.graph, parentId, asset.data, {\n name: asset.name,\n x,\n y\n })?.id\n if (id) created.push(id)\n x += asset.width + ASSET_GAP\n }\n } catch (error) {\n for (const id of created.reverse()) ctx.graph.deleteNode(id)\n throw error\n }\n\n if (created.length === 0) return false\n computeAllLayouts(ctx.graph, ctx.state.currentPageId)\n ctx.setSelectedIds(new Set(created))\n pushCreatedNodesUndo(created, previousSelection, label)\n ctx.requestRender()\n return true\n }\n\n /** Load the fonts of imported SVG text, so it is measured and placed with them. */\n async function loadSVGFonts(assets: PreparedAsset[]) {\n const fonts = assets.flatMap((asset) =>\n asset.kind === 'svg' ? svgImportFonts(asset.data) : []\n )\n await Promise.all(\n fonts.map((font) => ctx.loadFont(font.family, font.style, font.characters).catch(() => null))\n )\n }\n\n async function placeFiles(files: File[], cx: number, cy: number) {\n const prepared = (await Promise.all(files.map(prepareAsset))).filter(\n (asset): asset is PreparedAsset => asset !== null\n )\n await loadSVGFonts(prepared)\n placeAssets(prepared, cx, cy, 'Place files')\n }\n\n /** Paste SVG markup as layers, as Figma does; false when the text is not SVG. */\n async function pasteSVG(markup: string, cx: number, cy: number): Promise<boolean> {\n const data = isSVGMarkup(markup)\n ? prepareSVGImport(markup, { profile: ctx.graph.documentColorSpace })\n : null\n if (!data) return false\n const asset: PreparedAsset = { kind: 'svg', data, width: data.width, height: data.height }\n await loadSVGFonts([asset])\n return placeAssets([asset], cx, cy, 'Paste SVG')\n }\n\n /**\n * Paste a Mermaid flowchart as FigJam shapes, sections, and connectors, laid out and centred on\n * the point; false when the text is not one.\n */\n async function pasteMermaid(text: string, cx: number, cy: number): Promise<boolean> {\n const { detectMermaidDiagram, parseFlowchart } = await import('@pairdraw/mermaid')\n if (!detectMermaidDiagram(text)) return false\n const chart = parseFlowchart(text)\n const { addFlowchart } = await import('#core/io/formats/mermaid')\n const previousSelection = new Set(ctx.state.selectedIds)\n const parentId = resolvePasteTarget(ctx)\n const { ids: created } = await addFlowchart(ctx.graph, parentId, chart, {\n center: parentLocalPoint(parentId, cx, cy)\n })\n if (created.length === 0) return false\n ctx.setSelectedIds(new Set(created))\n pushCreatedNodesUndo(created, previousSelection, 'Paste Mermaid')\n ctx.requestRender()\n return true\n }\n\n function placeImageFiles(files: File[], cx: number, cy: number) {\n return placeFiles(\n files.filter((file) => IMPORTABLE_RASTER_TYPES.has(file.type)),\n cx,\n cy\n )\n }\n\n return { storeImage, placeFiles, placeImageFiles, pasteSVG, pasteMermaid }\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAM,sBAAsB;AAC5B,MAAM,YAAY;AA2BlB,SAAgB,4BACd,KACA,sBACA;CACA,SAAS,WAAW,OAA2B;EAC7C,MAAM,OAAO,iBAAiB,KAAK;EACnC,IAAI,MAAM,OAAO,IAAI,MAAM,KAAK;EAChC,OAAO;CACT;CAEA,SAAS,sBAAsB,OAA6D;EAC1F,MAAM,KAAK,IAAI,MAAM;EACrB,IAAI,CAAC,IAAI,OAAO;EAChB,MAAM,QAAQ,GAAG,qBAAqB,KAAK;EAC3C,IAAI,CAAC,OAAO,OAAO;EACnB,IAAI,QAAQ,MAAM,MAAM;EACxB,IAAI,SAAS,MAAM,OAAO;EAC1B,MAAM,OAAO;EACb,IAAI,QAAQ,uBAAuB,SAAS,qBAAqB;GAC/D,MAAM,QAAQ,KAAK,IAAI,sBAAsB,OAAO,sBAAsB,MAAM;GAChF,QAAQ,KAAK,MAAM,QAAQ,KAAK;GAChC,SAAS,KAAK,MAAM,SAAS,KAAK;EACpC;EACA,OAAO;GAAE;GAAO;EAAO;CACzB;CAEA,eAAe,aAAa,MAA2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NodeTree } from "./snapshot.js";
2
+ import { SceneGraph } from "@pairdraw/scene-graph";
3
+ //#region src/editor/clipboard/component-matches.d.ts
4
+ /**
5
+ * The component or set already in this document that a snapshot's dependency becomes, when the
6
+ * dependency came from here before. A node a paste created carries its clipboard origin, and a
7
+ * component read from a `.fig` carries the source identity Figma stores; names are never compared,
8
+ * so an unrelated same-named component is never reused.
9
+ */
10
+ declare function matchClipboardComponents(graph: SceneGraph, sourceRootId: string, dependencies: ClipboardNodeTree[]): Map<string, string>;
11
+ //#endregion
12
+ export { matchClipboardComponents };
13
+ //# sourceMappingURL=component-matches.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"component-matches.d.ts","names":[],"sources":["../../../src/editor/clipboard/component-matches.ts"],"mappings":";;;;;;;;;iBAagB,yBACd,OAAO,YACP,sBACA,cAAc,sBACb"}
@@ -0,0 +1,50 @@
1
+ import { collectSubtrees } from "../history/subtree.js";
2
+ import { PAIRDRAW_PLUGIN_DATA, readPluginData } from "@pairdraw/scene-graph/plugin-data";
3
+ //#region src/editor/clipboard/component-matches.ts
4
+ /**
5
+ * The component or set already in this document that a snapshot's dependency becomes, when the
6
+ * dependency came from here before. A node a paste created carries its clipboard origin, and a
7
+ * component read from a `.fig` carries the source identity Figma stores; names are never compared,
8
+ * so an unrelated same-named component is never reused.
9
+ */
10
+ function matchClipboardComponents(graph, sourceRootId, dependencies) {
11
+ const roots = [...graph.getAllNodes()].filter((node) => node.type === "COMPONENT" || node.type === "COMPONENT_SET");
12
+ const byOrigin = /* @__PURE__ */ new Map();
13
+ const bySource = /* @__PURE__ */ new Map();
14
+ const byKey = /* @__PURE__ */ new Map();
15
+ for (const root of roots) {
16
+ const origin = readPluginData(root.pluginData, PAIRDRAW_PLUGIN_DATA.clipboardOrigin);
17
+ if (origin?.documentId === sourceRootId) byOrigin.set(origin.nodeId, root.id);
18
+ if (root.source.id) bySource.set(root.source.id, root.id);
19
+ for (const key of [root.sourceLibraryKey, root.componentKey]) if (key && !byKey.has(key)) byKey.set(key, root.id);
20
+ }
21
+ const matches = /* @__PURE__ */ new Map();
22
+ const matchedRoots = /* @__PURE__ */ new Set();
23
+ const mapExistingChildren = (dependency, existingRootId) => {
24
+ const byChildOrigin = /* @__PURE__ */ new Map();
25
+ const byChildSource = /* @__PURE__ */ new Map();
26
+ for (const node of collectSubtrees(graph, [existingRootId])) {
27
+ const origin = readPluginData(node.pluginData, PAIRDRAW_PLUGIN_DATA.clipboardOrigin);
28
+ if (origin?.documentId === sourceRootId) byChildOrigin.set(origin.nodeId, node.id);
29
+ if (node.source.id) byChildSource.set(node.source.id, node.id);
30
+ }
31
+ const visit = (node) => {
32
+ const existing = byChildOrigin.get(node.id) ?? (node.source.id ? byChildSource.get(node.source.id) : void 0);
33
+ if (existing) matches.set(node.id, existing);
34
+ for (const child of node.children ?? []) visit(child);
35
+ };
36
+ for (const child of dependency.children ?? []) visit(child);
37
+ };
38
+ for (const dependency of dependencies) {
39
+ const existing = byOrigin.get(dependency.id) ?? (dependency.sourceLibraryKey ? byKey.get(dependency.sourceLibraryKey) : void 0) ?? (dependency.componentKey ? byKey.get(dependency.componentKey) : void 0) ?? (dependency.source.id ? bySource.get(dependency.source.id) : void 0);
40
+ if (!existing || matchedRoots.has(existing)) continue;
41
+ matchedRoots.add(existing);
42
+ matches.set(dependency.id, existing);
43
+ mapExistingChildren(dependency, existing);
44
+ }
45
+ return matches;
46
+ }
47
+ //#endregion
48
+ export { matchClipboardComponents };
49
+
50
+ //# sourceMappingURL=component-matches.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"component-matches.js","names":[],"sources":["../../../src/editor/clipboard/component-matches.ts"],"sourcesContent":["import type { SceneGraph } from '@pairdraw/scene-graph'\nimport { PAIRDRAW_PLUGIN_DATA, readPluginData } from '@pairdraw/scene-graph/plugin-data'\n\nimport { collectSubtrees } from '#core/editor/history/subtree'\n\nimport type { ClipboardNodeTree } from './snapshot'\n\n/**\n * The component or set already in this document that a snapshot's dependency becomes, when the\n * dependency came from here before. A node a paste created carries its clipboard origin, and a\n * component read from a `.fig` carries the source identity Figma stores; names are never compared,\n * so an unrelated same-named component is never reused.\n */\nexport function matchClipboardComponents(\n graph: SceneGraph,\n sourceRootId: string,\n dependencies: ClipboardNodeTree[]\n): Map<string, string> {\n const roots = [...graph.getAllNodes()].filter(\n (node) => node.type === 'COMPONENT' || node.type === 'COMPONENT_SET'\n )\n const byOrigin = new Map<string, string>()\n const bySource = new Map<string, string>()\n const byKey = new Map<string, string>()\n for (const root of roots) {\n const origin = readPluginData(root.pluginData, PAIRDRAW_PLUGIN_DATA.clipboardOrigin)\n if (origin?.documentId === sourceRootId) byOrigin.set(origin.nodeId, root.id)\n if (root.source.id) bySource.set(root.source.id, root.id)\n for (const key of [root.sourceLibraryKey, root.componentKey])\n if (key && !byKey.has(key)) byKey.set(key, root.id)\n }\n const matches = new Map<string, string>()\n const matchedRoots = new Set<string>()\n\n const mapExistingChildren = (dependency: ClipboardNodeTree, existingRootId: string) => {\n const byChildOrigin = new Map<string, string>()\n const byChildSource = new Map<string, string>()\n for (const node of collectSubtrees(graph, [existingRootId])) {\n const origin = readPluginData(node.pluginData, PAIRDRAW_PLUGIN_DATA.clipboardOrigin)\n if (origin?.documentId === sourceRootId) byChildOrigin.set(origin.nodeId, node.id)\n if (node.source.id) byChildSource.set(node.source.id, node.id)\n }\n const visit = (node: ClipboardNodeTree) => {\n const existing =\n byChildOrigin.get(node.id) ??\n (node.source.id ? byChildSource.get(node.source.id) : undefined)\n if (existing) matches.set(node.id, existing)\n for (const child of node.children ?? []) visit(child)\n }\n for (const child of dependency.children ?? []) visit(child)\n }\n\n for (const dependency of dependencies) {\n const existing =\n byOrigin.get(dependency.id) ??\n (dependency.sourceLibraryKey ? byKey.get(dependency.sourceLibraryKey) : undefined) ??\n (dependency.componentKey ? byKey.get(dependency.componentKey) : undefined) ??\n (dependency.source.id ? bySource.get(dependency.source.id) : undefined)\n if (!existing || matchedRoots.has(existing)) continue\n matchedR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OAAO,EAAE,IAAI,KAAA;GACxD,IAAI,UAAU,QAAQ,IAAI,KAAK,IAAI,QAAQ;GAC3C,KAAK,MAAM,SAAS,KAAK,YAAY,CAAC,GAAG,MAAM,KAAK;EACtD;EACA,KAAK,MAAM,SAAS,WAAW,YAAY,CAAC,GAAG,MAAM,KAAK;CAC5D;CAEA,KAAK,MAAM,cAAc,cAAc;EACrC,MAAM,WACJ,SAAS,IAAI,WAAW,EAAE,MACzB,WAAW,mBAAmB,MAAM,IAAI,WAAW,gBAAgB,IAAI,KAAA,OACvE,WAAW,eAAe,MAAM,IAAI,WAAW,YAAY,IAAI,KAAA,OAC/D,WAAW,OAAO,KAAK,SAAS,IAAI,WAAW,OAAO,EAAE,IAAI,KAAA;EAC/D,IAAI,CAAC,YAAY,aAAa,IAAI,QAAQ,GAAG;EAC7C,aAAa,IAAI,QAAQ;EACzB,QAAQ,IAAI,WAAW,IAAI,QAAQ;EACnC,oBAAoB,YAAY,QAAQ;CAC1C;CACA,OAAO;AACT"}
@@ -6,6 +6,13 @@ import { SceneNode } from "@pairdraw/scene-graph";
6
6
  interface ClipboardDependencyImport {
7
7
  nodes: ClipboardSnapshot['nodes'];
8
8
  componentDependencies: ClipboardSnapshot['componentDependencies'];
9
+ /**
10
+ * By a dependency's id here, the component or set already in this document it becomes, when the
11
+ * same snapshot was pasted before. A reuse keeps the local main, as in Figma.
12
+ */
13
+ componentMatches: Map<string, string>;
14
+ /** The copying document's root id, for a foreign paste that creates dependencies here. */
15
+ clipboardOrigin?: string;
9
16
  styleSnapshots: SceneNode[];
10
17
  /**
11
18
  * Whether the layers bind variables of this document now, whose values may differ from the
@@ -1 +1 @@
1
- {"version":3,"file":"dependencies.d.ts","names":[],"sources":["../../../src/editor/clipboard/dependencies.ts"],"mappings":";;;;;UAiBiB;EACf,OAAO;EACP,uBAAuB;EACvB,gBAAgB;;;;;EAKhB;EACA;EACA;;;iBAIc,oCACd,KAAK,eACL,UAAU,mBACV,SAAS,wBACR;;;;;;;iBAiCa,4BACd,KAAK,eACL,UAAU,mBACV,SAAS,wBACR"}
1
+ {"version":3,"file":"dependencies.d.ts","names":[],"sources":["../../../src/editor/clipboard/dependencies.ts"],"mappings":";;;;;UAkBiB;EACf,OAAO;EACP,uBAAuB;;;;;EAKvB,kBAAkB;;EAElB;EACA,gBAAgB;;;;;EAKhB;EACA;EACA;;;iBAIc,oCACd,KAAK,eACL,UAAU,mBACV,SAAS,wBACR;;;;;;;iBAiCa,4BACd,KAAK,eACL,UAAU,mBACV,SAAS,wBACR"}
@@ -1,5 +1,6 @@
1
1
  import { detachClipboardNode } from "./detach.js";
2
2
  import { importClipboardVariables, remapClipboardVariableBindings } from "./variables.js";
3
+ import { matchClipboardComponents } from "./component-matches.js";
3
4
  import { addsRenamed, matchClipboardCollections, matchClipboardStyles } from "./conflicts.js";
4
5
  import { applyExistingStyles } from "./existing-styles.js";
5
6
  import { numberedName } from "@pairdraw/scene-graph/naming";
@@ -35,6 +36,7 @@ function importClipboardDependencies(ctx, snapshot, choice) {
35
36
  if (snapshot.sourceRootId === ctx.graph.rootId) return {
36
37
  nodes,
37
38
  componentDependencies: componentDependencies.filter((node) => !ctx.graph.getNode(node.id)),
39
+ componentMatches: /* @__PURE__ */ new Map(),
38
40
  styleSnapshots: [],
39
41
  resolveBindings: false
40
42
  };
@@ -47,6 +49,7 @@ function importClipboardDependencies(ctx, snapshot, choice) {
47
49
  return {
48
50
  nodes,
49
51
  componentDependencies,
52
+ componentMatches: /* @__PURE__ */ new Map(),
50
53
  styleSnapshots: [],
51
54
  resolveBindings: false
52
55
  };
@@ -102,6 +105,8 @@ function importClipboardDependencies(ctx, snapshot, choice) {
102
105
  return {
103
106
  nodes,
104
107
  componentDependencies,
108
+ componentMatches: matchClipboardComponents(ctx.graph, snapshot.sourceRootId, componentDependencies),
109
+ clipboardOrigin: snapshot.sourceRootId,
105
110
  styleSnapshots,
106
111
  resolveBindings: snapshot.variableDependencies.variables.length > 0,
107
112
  applyVariables: variables.apply,
@@ -1 +1 @@
1
- {"version":3,"file":"dependencies.js","names":[],"sources":["../../../src/editor/clipboard/dependencies.ts"],"sourcesContent":["import type { SceneNode } from '@pairdraw/scene-graph'\nimport { numberedName } from '@pairdraw/scene-graph/naming'\n\nimport type { EditorContext } from '#core/editor/types'\n\nimport {\n addsRenamed,\n matchClipboardCollections,\n matchClipboardStyles,\n type ClipboardCollectionMerge,\n type ClipboardImportChoice\n} from './conflicts'\nimport { detachClipboardNode } from './detach'\nimport { applyExistingStyles } from './existing-styles'\nimport type { ClipboardNodeTree, ClipboardSnapshot } from './snapshot'\nimport { importClipboardVariables, remapClipboardVariableBindings } from './variables'\n\nexport interface ClipboardDependencyImport {\n nodes: ClipboardSnapshot['nodes']\n componentDependencies: ClipboardSnapshot['componentDependencies']\n styleSnapshots: SceneNode[]\n /**\n * Whether the layers bind variables of this document now, whose values may differ from the\n * copied ones, so the paste resolves their bindings once they are placed.\n */\n resolveBindings: boolean\n applyVariables?: () => void\n revertVariables?: () => void\n}\n\n/** Imports a snapshot's styles and variables as undo steps of the running batch. */\nexport function importClipboardDependenciesWithUndo(\n ctx: EditorContext,\n snapshot: ClipboardSnapshot,\n choice?: ClipboardImportChoice\n): ClipboardDependencyImport {\n const dependencies = importClipboardDependencies(ctx, snapshot, choice)\n if (dependencies.styleSnapshots.length > 0) {\n ctx.undo.push({\n label: 'Import clipboard styles',\n forward: () => {\n for (const style of dependencies.styleSnapshots) {\n ctx.graph.preserveSourceMetadataDuring(() =>\n ctx.graph.createNode(style.type, ctx.state.currentPageId, style)\n )\n }\n },\n inverse: () => {\n for (const style of dependencies.styleSnapshots) ctx.graph.deleteNode(style.id)\n }\n })\n }\n if (dependencies.applyVariables && dependencies.revertVariables) {\n ctx.undo.push({\n label: 'Import clipboard variables',\n forward: dependencies.applyVariables,\n inverse: dependencies.revertVariables\n })\n }\n return dependencies\n}\n\n/**\n * The snapshot's layers ready to paste here. A copy from another document brings its styles and\n * variables, or with an `as-is` choice keeps only the values its layers showed. Without a choice\n * every collection and style is added; with one, a same-named collection or style is used\n * unless the choice adds it renamed.\n */\nexport function importClipboardDependencies(\n ctx: EditorContext,\n snapshot: ClipboardSnapshot,\n choice?: ClipboardImportChoice\n): ClipboardDependencyImport {\n const nodes = structuredClone(snapshot.nodes)\n const componentDependencies = structuredClone(snapshot.componentDependencies)\n if (snapshot.sourceRootId === ctx.graph.rootId) {\n return {\n nodes,\n componentDependencies: componentDependencies.filter((node) => !ctx.graph.getNode(node.id)),\n styleSnapshots: [],\n resolveBindings: false\n }\n }\n if (choice?.mode === 'as-is') {\n const detach = (node: ClipboardNodeTree) => {\n detachClipboardNode(node, snapshot.resolvedBindings?.get(node.id))\n for (const child of node.children ?? []) detach(child)\n }\n for (const node of [...nodes, ...componentDependencies]) detach(node)\n return { nodes, componentDependencies, styleSnapshots: [], resolveBindings: false }\n }\n const styleIds = new Map<string, string>()\n /** This document's styles the layers use in place of copied ones, by id. */\n const existingStyles = new Map<string, SceneNode>()\n const styleSnapshots: SceneNode[] = []\n const styleMatches = choice ? matchClipboardStyles(ctx.graph, snapshot.styleDefinitions) : null\n const takenStyleNames = [...ctx.graph.getAllNodes()].flatMap((node) =>\n node.sharedStyleType ? [node.name] : []\n )\n for (const definition of snapshot.styleDefinitions) {\n const sourceStyleId = definition.source.id\n if (!sourceStyleId) continue\n const match = styleMatches?.get(sourceStyleId)\n const renamed = addsRenamed(choice, sourceStyleId)\n if (match?.source.id && !renamed) {\n styleIds.set(sourceStyleId, match.source.id)\n existingStyles.set(match.source.id, match)\n continue\n }\n const pastedStyleId = crypto.randomUUID()\n const name = renamed ? numberedName(definition.name, takenStyleNames) : definition.name\n takenStyleNames.push(name)\n let pasted: SceneNode | undefined\n ctx.graph.preserveSourceMetadataDuring(() => {\n pasted = ctx.graph.createNode(definition.type, ctx.state.currentPageId, {\n ...structuredClone(definition),\n id: undefined,\n name,\n parentId: ctx.state.currentPageId,\n childIds: [],\n source: { ...definition.source, id: pastedStyleId }\n })\n })\n if (!pasted) continue\n styleIds.set(sourceStyleId, pastedStyleId)\n styleSnapshots.push(structuredClone(pasted))\n }\n const collections = snapshot.variableDependencies.collections\n const merges = choice\n ? matchClipboardCollections(ctx.graph, collections)\n : new Map<string, ClipboardCollectionMerge>()\n for (const collection of collections)\n if (addsRenamed(choice, collection.id)) merges.delete(collection.id)\n const variables = importClipboardVariables(\n ctx.graph,\n snapshot.variableDependencies,\n merges,\n new Set(collections.flatMap(({ id }) => (addsRenamed(choice, id) ? [id] : [])))\n )\n function remap(node: ClipboardSnapshot['nodes'][number]) {\n remapClipboardVariableBindings(\n node,\n variables.variableIds,\n variables.collectionIds,\n variables.modeIds,\n styleIds,\n variables.droppedModes\n )\n applyExistingStyles(ctx.graph, node, existingStyles)\n for (const child of node.children ?? []) remap(child)\n }\n for (const node of [...nodes, ...componentDependencies]) remap(node)\n variables.apply()\n return {\n nodes,\n componentDependencies,\n styleSnapshots,\n resolveBindings: snapshot.variableDependencies.variables.length > 0,\n applyVariables: variables.apply,\n revertVariables: variables.revert\n }\n}\n"],"mappings":";;;;;;;AA+BA,SAAgB,oCACd,KACA,UACA,QAC2B;CAC3B,MAAM,eAAe,4BAA4B,KAAK,UAAU,MAAM;CACtE,IAAI,aAAa,eAAe,SAAS,GACvC,IAAI,KAAK,KAAK;EACZ,OAAO;EACP,eAAe;GACb,KAAK,MAAM,SAAS,aAAa,gBAC/B,IAAI,MAAM,mCACR,IAAI,MAAM,WAAW,MAAM,MAAM,IAAI,MAAM,eAAe,KAAK,CACjE;EAEJ;EACA,eAAe;GACb,KAAK,MAAM,SAAS,aAAa,gBAAgB,IAAI,MAAM,WAAW,MAAM,EAAE;EAChF;CACF,CAAC;CAEH,IAAI,aAAa,kBAAkB,aAAa,iBAC9C,IAAI,KAAK,KAAK;EACZ,OAAO;EACP,SAAS,aAAa;EACtB,SAAS,aAAa;CACxB,CAAC;CAEH,OAAO;AACT;;;;;;;AAQA,SAAgB,4BACd,KACA,UACA,QAC2B;CAC3B,MA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src/editor/clipboard/dependencies.ts"],"sourcesContent":["import type { SceneNode } from '@pairdraw/scene-graph'\nimport { numberedName } from '@pairdraw/scene-graph/naming'\n\nimport type { EditorContext } from '#core/editor/types'\n\nimport { matchClipboardComponents } from './component-matches'\nimport {\n addsRenamed,\n matchClipboardCollections,\n matchClipboardStyles,\n type ClipboardCollectionMerge,\n type ClipboardImportChoice\n} from './conflicts'\nimport { detachClipboardNode } from './detach'\nimport { applyExistingStyles } from './existing-styles'\nimport type { ClipboardNodeTree, ClipboardSnapshot } from './snapshot'\nimport { importClipboardVariables, remapClipboardVariableBindings } from './variables'\n\nexport interface ClipboardDependencyImport {\n nodes: ClipboardSnapshot['nodes']\n componentDependencies: ClipboardSnapshot['componentDependencies']\n /**\n * By a dependency's id here, the component or set already in this document it becomes, when the\n * same snapshot was pasted before. A reuse keeps the local main, as in Figma.\n */\n componentMatches: Map<string, string>\n /** The copying document's root id, for a foreign paste that creates dependencies here. */\n clipboardOrigin?: string\n styleSnapshots: SceneNode[]\n /**\n * Whether the layers bind variables of this document now, whose values may differ from the\n * copied ones, so the paste resolves their bindings once they are placed.\n */\n resolveBindings: boolean\n applyVariables?: () => void\n revertVariables?: () => void\n}\n\n/** Imports a snapshot's styles and variables as undo steps of the running batch. */\nexport function importClipboardDependenciesWithUndo(\n ctx: EditorContext,\n snapshot: ClipboardSnapshot,\n choice?: ClipboardImportChoice\n): ClipboardDependencyImport {\n const dependencies = importClipboardDependencies(ctx, snapshot, choice)\n if (dependencies.styleSnapshots.length > 0) {\n ctx.undo.push({\n label: 'Import clipboard styles',\n forward: () => {\n for (const style of dependencies.styleSnapshots) {\n ctx.graph.preserveSourceMetadataDuring(() =>\n ctx.graph.createNode(style.type, ctx.state.currentPageId, style)\n )\n }\n },\n inverse: () => {\n for (const style of dependencies.styleSnapshots) ctx.graph.deleteNode(style.id)\n }\n })\n }\n if (dependencies.applyVariables && dependencies.revertVariables) {\n ctx.undo.push({\n label: 'Import clipboard variables',\n forward: dependencies.applyVariables,\n inverse: dependencies.revertVariables\n })\n }\n return dependencies\n}\n\n/**\n * The snapshot's layers ready to paste here. A copy from another document brings its styles and\n * variables, or with an `as-is` choice keeps only the values its layers showed. Without a choice\n * every collection and style is added; with one, a same-named collection or style is used\n * unless the choice adds it renamed.\n */\nexport function importClipboardDependencies(\n ctx: EditorContext,\n snapshot: ClipboardSnapshot,\n choice?: ClipboardImportChoice\n): ClipboardDependencyImport {\n const nodes = structuredClone(snapshot.nodes)\n const componentDependencies = structuredClone(snapshot.componentDependencies)\n if (snapshot.sourceRootId === ctx.graph.rootId) {\n return {\n nodes,\n componentDependencies: componentDependencies.filter((node) => !ctx.graph.getNode(node.id)),\n componentMatches: new Map(),\n styleSnapshots: [],\n resolveBindings: false\n }\n }\n if (choice?.mode === 'as-is') {\n const detach = (node: ClipboardNodeTree) => {\n detachClipboardNode(node, snapshot.resolvedBindings?.get(node.id))\n for (const child of node.children ?? []) detach(child)\n }\n for (const node of [...nodes, ...componentDependencies]) detach(node)\n return {\n nodes,\n componentDependencies,\n componentMatches: new Map(),\n styleSnapshots: [],\n resolveBindings: false\n }\n }\n const styleIds = new Map<string, string>()\n /** This document's styles the layers use in place of copied ones, by id. */\n const existingStyles = new Map<string, SceneNode>()\n const styleSnapshots: SceneNode[] = []\n const styleMatches = choice ? matchClipboardStyles(ctx.graph, snapshot.styleDefinitions) : null\n const takenStyleNames = [...ctx.graph.getAllNodes()].flatMap((node) =>\n node.sharedStyleType ? [node.name] : []\n )\n for (const definition of snapshot.styleDefinitions) {\n const sourceStyleId = definition.source.id\n if (!sourceStyleId) continue\n const match = styleMatches?.get(sourceStyleId)\n const renamed = addsRenamed(choice, sourceStyleId)\n if (match?.source.id && !renamed) {\n styleIds.set(sourceStyleId, match.source.id)\n existingStyles.set(match.source.id, match)\n continue\n }\n const pastedStyleId = crypto.randomUUID()\n const name = renamed ? numberedName(definition.name, takenStyleNames) : definition.name\n takenStyleNames.push(name)\n let pasted: SceneNode | undefined\n ctx.graph.preserveSourceMetadataDuring(() => {\n pasted = ctx.graph.createNode(definition.type, ctx.state.currentPageId, {\n ...structuredClone(definition),\n id: undefined,\n name,\n parentId: ctx.state.currentPageId,\n childIds: [],\n source: { ...definition.source, id: pastedStyleId }\n })\n })\n if (!pasted) continue\n styleIds.set(sourceStyleId, pastedStyleId)\n styleSnapshots.push(structuredClone(pasted))\n }\n const collections = snapshot.variableDependencies.collections\n const merges = choice\n ? matchClipboardCollections(ctx.graph, collections)\n : new Map<string, ClipboardCollectionMerge>()\n for (const collection of collections)\n if (addsRenamed(choice, collection.id)) merges.delete(collection.id)\n const variables = importClipboardVariables(\n ctx.graph,\n snapshot.variableDependencies,\n merges,\n new Set(collections.flatMap(({ id }) => (addsRenamed(choice, id) ? [id] : [])))\n )\n function remap(node: ClipboardSnapshot['nodes'][number]) {\n remapClipboardVariableBindings(\n node,\n variables.variableIds,\n variables.collectionIds,\n variables.modeIds,\n styleIds,\n variables.droppedModes\n )\n applyExistingStyles(ctx.graph, node, existingStyles)\n for (const child of node.children ?? []) remap(child)\n }\n for (const node of [...nodes, ...componentDependencies]) remap(node)\n variables.apply()\n return {\n nodes,\n componentDependencies,\n componentMatches: matchClipboardComponents(\n ctx.graph,\n snapshot.sourceRootId,\n componentDependencies\n ),\n clipboardOrigin: snapshot.sourceRootId,\n styleSnapshots,\n resolveBindings: snapshot.variableDependencies.variables.length > 0,\n applyVariables: variables.apply,\n revertVariables: variables.revert\n }\n}\n"],"mappings":";;;;;;;;AAuCA,SAAgB,oCACd,KACA,UACA,QAC2B;CAC3B,MAAM,eAAe,4BAA4B,KAAK,UAAU,MAAM;CACtE,IAAI,aAAa,eAAe,SAAS,GACvC,IAAI,KAAK,KAAK;EACZ,OAAO;EACP,eAAe;GACb,KAAK,MAAM,SAAS,aAAa,gBAC/B,IAAI,MAAM,mCACR,IAAI,MAAM,WAAW,MAAM,MAAM,IAAI,MAAM,eAAe,KAAK,CACjE;EAEJ;EACA,eAAe;GACb,KAAK,MAAM,SA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AAS,KAAK,YAAY,CAAC,GAAG,MAAM,KAAK;CACtD;CACA,KAAK,MAAM,QAAQ,CAAC,GAAG,OAAO,GAAG,qBAAqB,GAAG,MAAM,IAAI;CACnE,UAAU,MAAM;CAChB,OAAO;EACL;EACA;EACA,kBAAkB,yBAChB,IAAI,OACJ,SAAS,cACT,qBACF;EACA,iBAAiB,SAAS;EAC1B;EACA,iBAAiB,SAAS,qBAAqB,UAAU,SAAS;EAClE,gBAAgB,UAAU;EAC1B,iBAAiB,UAAU;CAC7B;AACF"}
@@ -31,7 +31,7 @@ function createClipboardExportActions(ctx) {
31
31
  async function copySelectionAsHTML(ids) {
32
32
  if (ids.length === 0) return null;
33
33
  const { renderNodesToHTML } = await import("../../io/formats/html/index.js");
34
- const { html } = await renderNodesToHTML(ctx.graph, ids, {
34
+ const { html, draws } = await renderNodesToHTML(ctx.graph, ids, {
35
35
  html: "fragment",
36
36
  style: "inline",
37
37
  assets: "inline"
@@ -39,7 +39,7 @@ function createClipboardExportActions(ctx) {
39
39
  canvasKit: ctx.getCk() ?? void 0,
40
40
  renderer: ctx.getRenderer() ?? void 0
41
41
  });
42
- return html || null;
42
+ return draws ? html || null : null;
43
43
  }
44
44
  return {
45
45
  copySelectionAsText,
@@ -1 +1 @@
1
- {"version":3,"file":"export.js","names":[],"sources":["../../../src/editor/clipboard/export.ts"],"sourcesContent":["import { selectionToJSX } from '@pairdraw/design-jsx'\n\nimport type { EditorContext } from '#core/editor/types'\nimport type { BooleanPathResolver } from '#core/io/formats/boolean-path'\nimport { renderNodesToLaidOutSVG } from '#core/io/formats/svg/text/layout'\n\nexport function createClipboardExportActions(ctx: EditorContext) {\n /**\n * The copies compute an authored boolean's result with the app's own renderer, as an export\n * does, so copying never loads a second CanvasKit; a headless editor falls back to one. The\n * module is imported on copy rather than statically because it carries the raster renderer,\n * which the editor would otherwise load for a feature most copies never use.\n */\n async function booleanPath(): Promise<BooleanPathResolver | undefined> {\n const { booleanPathResolver, needsBooleanPaths } = await import('#core/io/formats/boolean-path')\n if (!needsBooleanPaths(ctx.graph)) return undefined\n return booleanPathResolver(ctx.getCk() ?? undefined, ctx.getRenderer() ?? undefined)\n }\n\n function copySelectionAsText(ids: string[]): string {\n return ids.map((id) => ctx.graph.getNode(id)?.name ?? id).join('\\n')\n }\n\n async function copySelectionAsSVG(ids: string[]): Promise<string | null> {\n const nodeIds =\n ids.length > 0 ? ids : ctx.graph.getChildren(ctx.state.currentPageId).map((n) => n.id)\n return renderNodesToLaidOutSVG(ctx.graph, ctx.state.currentPageId, nodeIds, {\n booleanPath: await booleanPath()\n })\n }\n\n function copySelectionAsJSX(ids: string[]): string | null {\n return ids.length > 0 ? selectionToJSX(ids, ctx.graph) : null\n }\n\n /**\n * The layers as one self-contained HTML fragment, as the HTML export writes them: inline\n * styles, and images inlined as data URLs so the markup works wherever it is pasted. Null for\n * no layers or none that draw.\n */\n async function copySelectionAsHTML(ids: string[]): Promise<string | null> {\n if (ids.length === 0) return null\n const { renderNodesToHTML } = await import('#core/io/formats/html')\n const { html } = await renderNodesToHTML(\n ctx.graph,\n ids,\n { html: 'fragment', style: 'inline', assets: 'inline' },\n undefined,\n { canvasKit: ctx.getCk() ?? undefined, renderer: ctx.getRenderer() ?? undefined }\n )\n return html || null\n }\n\n return { copySelectionAsText, copySelectionAsSVG, copySelectionAsJSX, copySelectionAsHTML }\n}\n"],"mappings":";;;AAMA,SAAgB,6BAA6B,KAAoB;;;;;;;CAO/D,eAAe,cAAwD;EACrE,MAAM,EAAE,qBAAqB,sBAAsB,MAAM,OAAO;EAChE,IAAI,CAAC,kBAAkB,IAAI,KAAK,GAAG,OAAO,KAAA;EAC1C,OAAO,oBAAoB,IAAI,MAAM,KAAK,KAAA,GAAW,IAAI,YAAY,KAAK,KAAA,CAAS;CACrF;CAEA,SAAS,oBAAoB,KAAuB;EAClD,OAAO,IAAI,KAAK,OAAO,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,KAAK,IAAI;CACrE;CAEA,eAAe,mBAAmB,KAAuC;EACvE,MAAM,UACJ,IAAI,SAAS,IAAI,MAAM,IAAI,MAAM,YAAY,IAAI,MAAM,aAAa,CAAC,CAAC,KAAK,MAAM,EAAE,EAAE;EACvF,OAAO,wBAAwB,IAAI,OAAO,IAAI,MAAM,eAAe,SAAS,EAC1E,aAAa,MAAM,YAAY,EACjC,CAAC;CACH;CAEA,SAAS,mBAAmB,KAA8B;EACxD,OAAO,IAAI,SAAS,IAAI,eAAe,KAAK,IAAI,KAAK,IAAI;CAC3D;;;;;;CAOA,eAAe,oBAAoB,KAAuC;EACxE,IAAI,IAAI,WAAW,GAAG,OAAO;EAC7B,MAAM,EAAE,sBAAsB,MAAM,OAAO;EAC3C,MAAM,EAAE,SAAS,MAAM,kBACrB,IAAI,OACJ,KACA;GAAE,MAAM;GAAY,OAAO;GAAU,QAAQ;EAAS,GACtD,KAAA,GACA;GAAE,WAAW,IAAI,MAAM,KAAK,KAAA;GAAW,UAAU,IAAI,YAAY,KAAK,KAAA;EAAU,CAClF;EACA,OAAO,QAAQ;CACjB;CAEA,OAAO;EAAE;EAAqB;EAAoB;EAAoB;CAAoB;AAC5F"}
1
+ {"version":3,"file":"export.js","names":[],"sources":["../../../src/editor/clipboard/export.ts"],"sourcesContent":["import { selectionToJSX } from '@pairdraw/design-jsx'\n\nimport type { EditorContext } from '#core/editor/types'\nimport type { BooleanPathResolver } from '#core/io/formats/boolean-path'\nimport { renderNodesToLaidOutSVG } from '#core/io/formats/svg/text/layout'\n\nexport function createClipboardExportActions(ctx: EditorContext) {\n /**\n * The copies compute an authored boolean's result with the app's own renderer, as an export\n * does, so copying never loads a second CanvasKit; a headless editor falls back to one. The\n * module is imported on copy rather than statically because it carries the raster renderer,\n * which the editor would otherwise load for a feature most copies never use.\n */\n async function booleanPath(): Promise<BooleanPathResolver | undefined> {\n const { booleanPathResolver, needsBooleanPaths } = await import('#core/io/formats/boolean-path')\n if (!needsBooleanPaths(ctx.graph)) return undefined\n return booleanPathResolver(ctx.getCk() ?? undefined, ctx.getRenderer() ?? undefined)\n }\n\n function copySelectionAsText(ids: string[]): string {\n return ids.map((id) => ctx.graph.getNode(id)?.name ?? id).join('\\n')\n }\n\n async function copySelectionAsSVG(ids: string[]): Promise<string | null> {\n const nodeIds =\n ids.length > 0 ? ids : ctx.graph.getChildren(ctx.state.currentPageId).map((n) => n.id)\n return renderNodesToLaidOutSVG(ctx.graph, ctx.state.currentPageId, nodeIds, {\n booleanPath: await booleanPath()\n })\n }\n\n function copySelectionAsJSX(ids: string[]): string | null {\n return ids.length > 0 ? selectionToJSX(ids, ctx.graph) : null\n }\n\n /**\n * The layers as one self-contained HTML fragment, as the HTML export writes them: inline\n * styles, and images inlined as data URLs so the markup works wherever it is pasted. Null for\n * no layers or none that draw.\n */\n async function copySelectionAsHTML(ids: string[]): Promise<string | null> {\n if (ids.length === 0) return null\n const { renderNodesToHTML } = await import('#core/io/formats/html')\n const { html, draws } = await renderNodesToHTML(\n ctx.graph,\n ids,\n { html: 'fragment', style: 'inline', assets: 'inline' },\n undefined,\n { canvasKit: ctx.getCk() ?? undefined, renderer: ctx.getRenderer() ?? undefined }\n )\n return draws ? html || null : null\n }\n\n return { copySelectionAsText, copySelectionAsSVG, copySelectionAsJSX, copySelectionAsHTML }\n}\n"],"mappings":";;;AAMA,SAAgB,6BAA6B,KAAoB;;;;;;;CAO/D,eAAe,cAAwD;EACrE,MAAM,EAAE,qBAAqB,sBAAsB,MAAM,OAAO;EAChE,IAAI,CAAC,kBAAkB,IAAI,KAAK,GAAG,OAAO,KAAA;EAC1C,OAAO,oBAAoB,IAAI,MAAM,KAAK,KAAA,GAAW,IAAI,YAAY,KAAK,KAAA,CAAS;CACrF;CAEA,SAAS,oBAAoB,KAAuB;EAClD,OAAO,IAAI,KAAK,OAAO,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,KAAK,IAAI;CACrE;CAEA,eAAe,mBAAmB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d.ts","names":[],"sources":["../../src/editor/clipboard.ts"],"mappings":";;;;;;;;;;;KA+CK;EACH;;;;;EAKA;;EAEA,eAAe;;;;;;iBAgBD,cACd,KAAK,KAAK,yBACV,MAAM,WACN,kBACA,UAAU,SACT;iBAQa,uBAAuB,KAAK;;;;;;;;;;;EAoH9B,gBAAA,UAAA,mBAAiB,YACf,QAAM,UACT,iBAAY;EA0BY,gBAAA,cAAM,YAAc,QAAM,UAAW,iBAAY;EAgFhD,iBAAA,cAAM,aAAa,gBAAgB;EA4MnC,oBAAA;EASN,cAAA,SAAA,kBAAgB,gBAAkB;;;EApbtB,oBAAA,eAAA;EAijBlB,gBAAA,MAAA,WAAS,kBAAkB,UAAY,WAAM"}