@pairdraw/core 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (517) 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/effect.d.ts.map +1 -1
  43. package/dist/canvas/shaders/effect.js +2 -1
  44. package/dist/canvas/shaders/effect.js.map +1 -1
  45. package/dist/canvas/shadows/shape.d.ts.map +1 -1
  46. package/dist/canvas/shadows/shape.js +4 -2
  47. package/dist/canvas/shadows/shape.js.map +1 -1
  48. package/dist/canvas/shadows.d.ts.map +1 -1
  49. package/dist/canvas/shadows.js +4 -2
  50. package/dist/canvas/shadows.js.map +1 -1
  51. package/dist/canvas/text/decorations.d.ts +2 -2
  52. package/dist/canvas/text/decorations.d.ts.map +1 -1
  53. package/dist/canvas/text/decorations.js +5 -5
  54. package/dist/canvas/text/decorations.js.map +1 -1
  55. package/dist/canvas/text/index.js +1 -1
  56. package/dist/canvas/text/index.js.map +1 -1
  57. package/dist/canvas/text/paragraph/index.d.ts +2 -2
  58. package/dist/canvas/text/paragraph/index.d.ts.map +1 -1
  59. package/dist/canvas/text/paragraph/index.js +16 -5
  60. package/dist/canvas/text/paragraph/index.js.map +1 -1
  61. package/dist/canvas/text/renderer.d.ts +2 -1
  62. package/dist/canvas/text/renderer.d.ts.map +1 -1
  63. package/dist/canvas/text/shape.js +4 -4
  64. package/dist/canvas/text/shape.js.map +1 -1
  65. package/dist/canvas/texture.d.ts.map +1 -1
  66. package/dist/canvas/texture.js +2 -1
  67. package/dist/canvas/texture.js.map +1 -1
  68. package/dist/design-memory/rules.js +1 -1
  69. package/dist/editor/bridges/undo.d.ts +1 -1
  70. package/dist/editor/clipboard/assets.d.ts.map +1 -1
  71. package/dist/editor/clipboard/assets.js +2 -2
  72. package/dist/editor/clipboard/assets.js.map +1 -1
  73. package/dist/editor/clipboard/component-matches.d.ts +13 -0
  74. package/dist/editor/clipboard/component-matches.d.ts.map +1 -0
  75. package/dist/editor/clipboard/component-matches.js +50 -0
  76. package/dist/editor/clipboard/component-matches.js.map +1 -0
  77. package/dist/editor/clipboard/dependencies.d.ts +7 -0
  78. package/dist/editor/clipboard/dependencies.d.ts.map +1 -1
  79. package/dist/editor/clipboard/dependencies.js +5 -0
  80. package/dist/editor/clipboard/dependencies.js.map +1 -1
  81. package/dist/editor/clipboard.d.ts.map +1 -1
  82. package/dist/editor/clipboard.js +48 -19
  83. package/dist/editor/clipboard.js.map +1 -1
  84. package/dist/editor/components/properties.d.ts.map +1 -1
  85. package/dist/editor/components/properties.js +3 -3
  86. package/dist/editor/components/properties.js.map +1 -1
  87. package/dist/editor/create.d.ts +1 -1
  88. package/dist/editor/eyedropper.d.ts +1 -1
  89. package/dist/editor/eyedropper.d.ts.map +1 -1
  90. package/dist/editor/eyedropper.js +6 -3
  91. package/dist/editor/eyedropper.js.map +1 -1
  92. package/dist/editor/history/atomic-tool.d.ts.map +1 -1
  93. package/dist/editor/history/atomic-tool.js +3 -2
  94. package/dist/editor/history/atomic-tool.js.map +1 -1
  95. package/dist/editor/shapes/pencil.js +1 -1
  96. package/dist/editor/structure/state.d.ts.map +1 -1
  97. package/dist/editor/structure/state.js +2 -2
  98. package/dist/editor/structure/state.js.map +1 -1
  99. package/dist/editor/text.d.ts.map +1 -1
  100. package/dist/editor/text.js +2 -2
  101. package/dist/editor/text.js.map +1 -1
  102. package/dist/editor/variables.js +3 -3
  103. package/dist/editor/variables.js.map +1 -1
  104. package/dist/figma-api/fresh-read.d.ts +15 -0
  105. package/dist/figma-api/fresh-read.d.ts.map +1 -0
  106. package/dist/figma-api/fresh-read.js +54 -0
  107. package/dist/figma-api/fresh-read.js.map +1 -0
  108. package/dist/figma-api/graph-ref.d.ts +9 -0
  109. package/dist/figma-api/graph-ref.d.ts.map +1 -0
  110. package/dist/figma-api/graph-ref.js +14 -0
  111. package/dist/figma-api/graph-ref.js.map +1 -0
  112. package/dist/figma-api/index.d.ts +6 -1
  113. package/dist/figma-api/index.d.ts.map +1 -1
  114. package/dist/figma-api/index.js +12 -5
  115. package/dist/figma-api/index.js.map +1 -1
  116. package/dist/figma-api/pending-layout.d.ts +3 -3
  117. package/dist/figma-api/pending-layout.d.ts.map +1 -1
  118. package/dist/figma-api/pending-layout.js +7 -3
  119. package/dist/figma-api/pending-layout.js.map +1 -1
  120. package/dist/figma-api/pending-sync.d.ts +1 -1
  121. package/dist/figma-api/pending-sync.d.ts.map +1 -1
  122. package/dist/figma-api/pending-sync.js +3 -1
  123. package/dist/figma-api/pending-sync.js.map +1 -1
  124. package/dist/figma-api/proxy.d.ts.map +1 -1
  125. package/dist/figma-api/proxy.js +3 -2
  126. package/dist/figma-api/proxy.js.map +1 -1
  127. package/dist/figma-api/reactions.d.ts +20 -4
  128. package/dist/figma-api/reactions.d.ts.map +1 -1
  129. package/dist/figma-api/reactions.js +49 -3
  130. package/dist/figma-api/reactions.js.map +1 -1
  131. package/dist/figma-api/variables/index.d.ts.map +1 -1
  132. package/dist/figma-api/variables/index.js +2 -2
  133. package/dist/figma-api/variables/index.js.map +1 -1
  134. package/dist/io/formats/design-tokens/css/known.js +1 -1
  135. package/dist/io/formats/design-tokens/css/known.js.map +1 -1
  136. package/dist/io/formats/design-tokens/css/read.d.ts +3 -1
  137. package/dist/io/formats/design-tokens/css/read.d.ts.map +1 -1
  138. package/dist/io/formats/design-tokens/css/read.js +11 -5
  139. package/dist/io/formats/design-tokens/css/read.js.map +1 -1
  140. package/dist/io/formats/design-tokens/css/sync.d.ts.map +1 -1
  141. package/dist/io/formats/design-tokens/css/sync.js +17 -4
  142. package/dist/io/formats/design-tokens/css/sync.js.map +1 -1
  143. package/dist/io/formats/design-tokens/css/values.d.ts +6 -5
  144. package/dist/io/formats/design-tokens/css/values.d.ts.map +1 -1
  145. package/dist/io/formats/design-tokens/css/values.js +24 -8
  146. package/dist/io/formats/design-tokens/css/values.js.map +1 -1
  147. package/dist/io/formats/design-tokens/decode.d.ts +7 -6
  148. package/dist/io/formats/design-tokens/decode.d.ts.map +1 -1
  149. package/dist/io/formats/design-tokens/decode.js +13 -12
  150. package/dist/io/formats/design-tokens/decode.js.map +1 -1
  151. package/dist/io/formats/design-tokens/export.js +3 -3
  152. package/dist/io/formats/design-tokens/export.js.map +1 -1
  153. package/dist/io/formats/design-tokens/plan/index.d.ts.map +1 -1
  154. package/dist/io/formats/design-tokens/plan/index.js +4 -3
  155. package/dist/io/formats/design-tokens/plan/index.js.map +1 -1
  156. package/dist/io/formats/design-tokens/plan/styles.d.ts.map +1 -1
  157. package/dist/io/formats/design-tokens/plan/styles.js +9 -9
  158. package/dist/io/formats/design-tokens/plan/styles.js.map +1 -1
  159. package/dist/io/formats/design-tokens/styles.d.ts +4 -4
  160. package/dist/io/formats/design-tokens/styles.d.ts.map +1 -1
  161. package/dist/io/formats/design-tokens/styles.js +7 -7
  162. package/dist/io/formats/design-tokens/styles.js.map +1 -1
  163. package/dist/io/formats/design-tokens/sync/drift.js +2 -2
  164. package/dist/io/formats/design-tokens/sync/drift.js.map +1 -1
  165. package/dist/io/formats/design-tokens/values.d.ts +10 -5
  166. package/dist/io/formats/design-tokens/values.d.ts.map +1 -1
  167. package/dist/io/formats/design-tokens/values.js +13 -7
  168. package/dist/io/formats/design-tokens/values.js.map +1 -1
  169. package/dist/io/formats/drawio/label.js +1 -1
  170. package/dist/io/formats/drawio/paint.js +1 -1
  171. package/dist/io/formats/drawio/warnings.js +2 -2
  172. package/dist/io/formats/drawio/warnings.js.map +1 -1
  173. package/dist/io/formats/fig/export/index.d.ts.map +1 -1
  174. package/dist/io/formats/fig/export/index.js +15 -3
  175. package/dist/io/formats/fig/export/index.js.map +1 -1
  176. package/dist/io/formats/fig/export/patch/index.d.ts.map +1 -1
  177. package/dist/io/formats/fig/export/patch/index.js +2 -1
  178. package/dist/io/formats/fig/export/patch/index.js.map +1 -1
  179. package/dist/io/formats/fig/export/setup.d.ts +7 -2
  180. package/dist/io/formats/fig/export/setup.d.ts.map +1 -1
  181. package/dist/io/formats/fig/export/setup.js +12 -13
  182. package/dist/io/formats/fig/export/setup.js.map +1 -1
  183. package/dist/io/formats/fig/export/variables.d.ts.map +1 -1
  184. package/dist/io/formats/fig/export/variables.js +9 -7
  185. package/dist/io/formats/fig/export/variables.js.map +1 -1
  186. package/dist/io/formats/html/vectors.js +1 -0
  187. package/dist/io/formats/html/vectors.js.map +1 -1
  188. package/dist/io/formats/mermaid/layers.js +2 -2
  189. package/dist/io/formats/mermaid/layers.js.map +1 -1
  190. package/dist/io/formats/mermaid/styles.js +1 -1
  191. package/dist/io/formats/pdf/export.d.ts.map +1 -1
  192. package/dist/io/formats/pdf/export.js +1 -0
  193. package/dist/io/formats/pdf/export.js.map +1 -1
  194. package/dist/io/formats/pdf/prepare.d.ts +4 -4
  195. package/dist/io/formats/pdf/prepare.d.ts.map +1 -1
  196. package/dist/io/formats/pdf/prepare.js +2 -2
  197. package/dist/io/formats/pdf/prepare.js.map +1 -1
  198. package/dist/io/formats/pen/index.js +4 -2
  199. package/dist/io/formats/pen/index.js.map +1 -1
  200. package/dist/io/formats/pptx/style.js +1 -1
  201. package/dist/io/formats/raster/render.d.ts +1 -1
  202. package/dist/io/formats/raster/render.d.ts.map +1 -1
  203. package/dist/io/formats/raster/render.js +9 -4
  204. package/dist/io/formats/raster/render.js.map +1 -1
  205. package/dist/io/formats/svg/defs.d.ts +6 -3
  206. package/dist/io/formats/svg/defs.d.ts.map +1 -1
  207. package/dist/io/formats/svg/defs.js +12 -11
  208. package/dist/io/formats/svg/defs.js.map +1 -1
  209. package/dist/io/formats/svg/effects.js +2 -2
  210. package/dist/io/formats/svg/effects.js.map +1 -1
  211. package/dist/io/formats/svg/export.d.ts +5 -2
  212. package/dist/io/formats/svg/export.d.ts.map +1 -1
  213. package/dist/io/formats/svg/export.js +4 -2
  214. package/dist/io/formats/svg/export.js.map +1 -1
  215. package/dist/io/formats/svg/filter.d.ts +4 -1
  216. package/dist/io/formats/svg/filter.d.ts.map +1 -1
  217. package/dist/io/formats/svg/filter.js +6 -2
  218. package/dist/io/formats/svg/filter.js.map +1 -1
  219. package/dist/io/formats/svg/grain.js +1 -1
  220. package/dist/io/formats/svg/grain.js.map +1 -1
  221. package/dist/io/formats/svg/import.d.ts +4 -2
  222. package/dist/io/formats/svg/import.d.ts.map +1 -1
  223. package/dist/io/formats/svg/import.js +2 -1
  224. package/dist/io/formats/svg/import.js.map +1 -1
  225. package/dist/io/formats/svg/text/export.d.ts.map +1 -1
  226. package/dist/io/formats/svg/text/export.js +8 -8
  227. package/dist/io/formats/svg/text/export.js.map +1 -1
  228. package/dist/io/formats/svg/text/layout.js +2 -2
  229. package/dist/io/formats/svg/text/layout.js.map +1 -1
  230. package/dist/io/formats.d.ts.map +1 -1
  231. package/dist/io/formats.js +1 -0
  232. package/dist/io/formats.js.map +1 -1
  233. package/dist/io/subgraph.d.ts.map +1 -1
  234. package/dist/io/subgraph.js +1 -1
  235. package/dist/io/subgraph.js.map +1 -1
  236. package/dist/io/types.d.ts +1 -1
  237. package/dist/kiwi/fig/session/options.d.ts +3 -0
  238. package/dist/kiwi/fig/session/options.d.ts.map +1 -1
  239. package/dist/kiwi/fig/session/options.js +4 -0
  240. package/dist/kiwi/fig/session/options.js.map +1 -1
  241. package/dist/layout/yoga-helpers.d.ts +2 -1
  242. package/dist/layout/yoga-helpers.d.ts.map +1 -1
  243. package/dist/layout/yoga-helpers.js +7 -1
  244. package/dist/layout/yoga-helpers.js.map +1 -1
  245. package/dist/layout.js +24 -1
  246. package/dist/layout.js.map +1 -1
  247. package/dist/lint/fixes.js +1 -1
  248. package/dist/lint/linter.js +2 -2
  249. package/dist/lint/linter.js.map +1 -1
  250. package/dist/pairdraw-api/comments.d.ts +4 -1
  251. package/dist/pairdraw-api/comments.d.ts.map +1 -1
  252. package/dist/pairdraw-api/comments.js +5 -0
  253. package/dist/pairdraw-api/comments.js.map +1 -1
  254. package/dist/pairdraw-api/index.d.ts +3 -3
  255. package/dist/pairdraw-api/index.d.ts.map +1 -1
  256. package/dist/pairdraw-api/index.js +5 -5
  257. package/dist/pairdraw-api/index.js.map +1 -1
  258. package/dist/pairdraw-api/nodes.d.ts +1 -1
  259. package/dist/prototype/scene.js +1 -1
  260. package/dist/rpc/analyze-commands.js +1 -1
  261. package/dist/rpc/read-commands.d.ts +2 -2
  262. package/dist/rpc/read-commands.js +3 -3
  263. package/dist/rpc/read-commands.js.map +1 -1
  264. package/dist/rpc/variables-command.js +2 -2
  265. package/dist/rpc/variables-command.js.map +1 -1
  266. package/dist/text/font/provider.d.ts +15 -0
  267. package/dist/text/font/provider.d.ts.map +1 -0
  268. package/dist/text/font/provider.js +18 -0
  269. package/dist/text/font/provider.js.map +1 -0
  270. package/dist/text/font/readiness.d.ts +32 -0
  271. package/dist/text/font/readiness.d.ts.map +1 -0
  272. package/dist/text/font/{status.js → readiness.js} +8 -4
  273. package/dist/text/font/readiness.js.map +1 -0
  274. package/dist/text/index.d.ts +4 -3
  275. package/dist/text/index.js +4 -3
  276. package/dist/text/prepare.d.ts +9 -4
  277. package/dist/text/prepare.d.ts.map +1 -1
  278. package/dist/text/prepare.js +9 -4
  279. package/dist/text/prepare.js.map +1 -1
  280. package/dist/tools/analyze/colors.js +1 -1
  281. package/dist/tools/analyze/responsive/index.js +7 -18
  282. package/dist/tools/analyze/responsive/index.js.map +1 -1
  283. package/dist/tools/analyze/responsive/widths.d.ts +27 -0
  284. package/dist/tools/analyze/responsive/widths.d.ts.map +1 -0
  285. package/dist/tools/analyze/responsive/widths.js +49 -0
  286. package/dist/tools/analyze/responsive/widths.js.map +1 -0
  287. package/dist/tools/analyze.d.ts +2 -1
  288. package/dist/tools/analyze.js +2 -1
  289. package/dist/tools/codegen/tokens.d.ts.map +1 -1
  290. package/dist/tools/codegen/tokens.js +2 -2
  291. package/dist/tools/codegen/tokens.js.map +1 -1
  292. package/dist/tools/comments.d.ts.map +1 -1
  293. package/dist/tools/comments.js +2 -2
  294. package/dist/tools/comments.js.map +1 -1
  295. package/dist/tools/component-catalog.d.ts.map +1 -1
  296. package/dist/tools/component-catalog.js +5 -3
  297. package/dist/tools/component-catalog.js.map +1 -1
  298. package/dist/tools/create/basic.js +1 -1
  299. package/dist/tools/create/behaviours.js +1 -1
  300. package/dist/tools/create/html.d.ts.map +1 -1
  301. package/dist/tools/create/html.js +1 -3
  302. package/dist/tools/create/html.js.map +1 -1
  303. package/dist/tools/create/icons.js +2 -2
  304. package/dist/tools/create/icons.js.map +1 -1
  305. package/dist/tools/create/mermaid.js +1 -1
  306. package/dist/tools/create/render.js +1 -1
  307. package/dist/tools/create/svg.js +5 -2
  308. package/dist/tools/create/svg.js.map +1 -1
  309. package/dist/tools/create/vector.js +3 -3
  310. package/dist/tools/create/vector.js.map +1 -1
  311. package/dist/tools/css/shorthand.d.ts +20 -0
  312. package/dist/tools/css/shorthand.d.ts.map +1 -0
  313. package/dist/tools/css/shorthand.js +54 -0
  314. package/dist/tools/css/shorthand.js.map +1 -0
  315. package/dist/tools/describe/index.js +2 -2
  316. package/dist/tools/describe/index.js.map +1 -1
  317. package/dist/tools/describe/issues.js +1 -1
  318. package/dist/tools/html-host.d.ts.map +1 -1
  319. package/dist/tools/html-host.js +5 -3
  320. package/dist/tools/html-host.js.map +1 -1
  321. package/dist/tools/image-ai/apply.d.ts.map +1 -1
  322. package/dist/tools/image-ai/apply.js +1 -3
  323. package/dist/tools/image-ai/apply.js.map +1 -1
  324. package/dist/tools/image-ai/generate.js +1 -1
  325. package/dist/tools/image-ai/service.d.ts.map +1 -1
  326. package/dist/tools/image-ai/service.js +5 -3
  327. package/dist/tools/image-ai/service.js.map +1 -1
  328. package/dist/tools/index.d.ts +2 -1
  329. package/dist/tools/index.js +2 -1
  330. package/dist/tools/modify/effects.js +1 -1
  331. package/dist/tools/modify/effects.js.map +1 -1
  332. package/dist/tools/modify/geometry.d.ts.map +1 -1
  333. package/dist/tools/modify/geometry.js +14 -3
  334. package/dist/tools/modify/geometry.js.map +1 -1
  335. package/dist/tools/modify/layout.d.ts.map +1 -1
  336. package/dist/tools/modify/layout.js +35 -8
  337. package/dist/tools/modify/layout.js.map +1 -1
  338. package/dist/tools/modify/matching.d.ts.map +1 -1
  339. package/dist/tools/modify/matching.js +10 -10
  340. package/dist/tools/modify/matching.js.map +1 -1
  341. package/dist/tools/modify/paint.d.ts.map +1 -1
  342. package/dist/tools/modify/paint.js +57 -5
  343. package/dist/tools/modify/paint.js.map +1 -1
  344. package/dist/tools/modify/reactions.d.ts.map +1 -1
  345. package/dist/tools/modify/reactions.js +2 -2
  346. package/dist/tools/modify/reactions.js.map +1 -1
  347. package/dist/tools/modify/text.d.ts.map +1 -1
  348. package/dist/tools/modify/text.js +3 -3
  349. package/dist/tools/modify/text.js.map +1 -1
  350. package/dist/tools/prompts/codegen.js +1 -1
  351. package/dist/tools/prompts/codegen.js.map +1 -1
  352. package/dist/tools/read/css.d.ts +14 -0
  353. package/dist/tools/read/css.d.ts.map +1 -0
  354. package/dist/tools/read/css.js +306 -0
  355. package/dist/tools/read/css.js.map +1 -0
  356. package/dist/tools/read/libraries.js +1 -1
  357. package/dist/tools/read/reactions.js +1 -1
  358. package/dist/tools/read/reactions.js.map +1 -1
  359. package/dist/tools/read/space.d.ts.map +1 -1
  360. package/dist/tools/read/space.js +0 -2
  361. package/dist/tools/read/space.js.map +1 -1
  362. package/dist/tools/read.d.ts +2 -1
  363. package/dist/tools/read.js +2 -1
  364. package/dist/tools/registry/core.d.ts +1 -1
  365. package/dist/tools/registry/core.js +3 -1
  366. package/dist/tools/registry/core.js.map +1 -1
  367. package/dist/tools/schema.d.ts +6 -4
  368. package/dist/tools/schema.d.ts.map +1 -1
  369. package/dist/tools/schema.js +9 -5
  370. package/dist/tools/schema.js.map +1 -1
  371. package/dist/tools/script/host.d.ts.map +1 -1
  372. package/dist/tools/script/host.js +5 -3
  373. package/dist/tools/script/host.js.map +1 -1
  374. package/dist/tools/variables/collections.js +1 -1
  375. package/dist/tools/variables/collections.js.map +1 -1
  376. package/dist/tools/variables/values.d.ts.map +1 -1
  377. package/dist/tools/variables/values.js +4 -4
  378. package/dist/tools/variables/values.js.map +1 -1
  379. package/dist/tools/vector/vectorize.d.ts.map +1 -1
  380. package/dist/tools/vector/vectorize.js +6 -4
  381. package/dist/tools/vector/vectorize.js.map +1 -1
  382. package/dist/tools/video-host.d.ts.map +1 -1
  383. package/dist/tools/video-host.js +5 -3
  384. package/dist/tools/video-host.js.map +1 -1
  385. package/dist/vector/vectorize/svg/gradients.d.ts +2 -2
  386. package/dist/vector/vectorize/svg/gradients.d.ts.map +1 -1
  387. package/dist/vector/vectorize/svg/gradients.js +5 -5
  388. package/dist/vector/vectorize/svg/gradients.js.map +1 -1
  389. package/dist/vector/vectorize/svg/to-vectors.d.ts +3 -1
  390. package/dist/vector/vectorize/svg/to-vectors.d.ts.map +1 -1
  391. package/dist/vector/vectorize/svg/to-vectors.js +13 -12
  392. package/dist/vector/vectorize/svg/to-vectors.js.map +1 -1
  393. package/package.json +9 -9
  394. package/src/canvas/noise/render.ts +1 -1
  395. package/src/canvas/noise/shader.ts +13 -5
  396. package/src/canvas/noise/tile.ts +2 -1
  397. package/src/canvas/renderer/colors.ts +76 -50
  398. package/src/canvas/renderer/document-surface.ts +53 -0
  399. package/src/canvas/renderer/fonts.ts +6 -4
  400. package/src/canvas/renderer/lifecycle.ts +4 -4
  401. package/src/canvas/renderer/methods.ts +1 -0
  402. package/src/canvas/renderer/pipeline.ts +21 -3
  403. package/src/canvas/renderer/retained-backing.ts +2 -1
  404. package/src/canvas/renderer/tiles/surface-pool.ts +9 -7
  405. package/src/canvas/renderer.ts +36 -11
  406. package/src/canvas/scene.ts +4 -3
  407. package/src/canvas/shaders/effect.ts +2 -1
  408. package/src/canvas/shadows/shape.ts +4 -2
  409. package/src/canvas/shadows.ts +5 -2
  410. package/src/canvas/text/decorations.ts +15 -5
  411. package/src/canvas/text/index.ts +9 -1
  412. package/src/canvas/text/paragraph/index.ts +16 -6
  413. package/src/canvas/text/renderer.ts +2 -1
  414. package/src/canvas/text/shape.ts +4 -4
  415. package/src/canvas/texture.ts +2 -1
  416. package/src/editor/clipboard/assets.ts +6 -2
  417. package/src/editor/clipboard/component-matches.ts +65 -0
  418. package/src/editor/clipboard/dependencies.ts +22 -1
  419. package/src/editor/clipboard.ts +74 -20
  420. package/src/editor/components/properties.ts +3 -2
  421. package/src/editor/eyedropper.ts +14 -4
  422. package/src/editor/history/atomic-tool.ts +3 -2
  423. package/src/editor/structure/state.ts +2 -1
  424. package/src/editor/text.ts +2 -1
  425. package/src/editor/variables.ts +3 -3
  426. package/src/figma-api/fresh-read.ts +57 -0
  427. package/src/figma-api/graph-ref.ts +13 -0
  428. package/src/figma-api/index.ts +12 -4
  429. package/src/figma-api/pending-layout.ts +7 -3
  430. package/src/figma-api/pending-sync.ts +4 -1
  431. package/src/figma-api/proxy.ts +2 -1
  432. package/src/figma-api/reactions.ts +91 -10
  433. package/src/figma-api/variables/index.ts +5 -4
  434. package/src/io/formats/design-tokens/css/known.ts +1 -1
  435. package/src/io/formats/design-tokens/css/read.ts +20 -7
  436. package/src/io/formats/design-tokens/css/sync.ts +9 -4
  437. package/src/io/formats/design-tokens/css/values.ts +37 -9
  438. package/src/io/formats/design-tokens/decode.ts +17 -12
  439. package/src/io/formats/design-tokens/export.ts +3 -3
  440. package/src/io/formats/design-tokens/plan/index.ts +6 -5
  441. package/src/io/formats/design-tokens/plan/styles.ts +37 -10
  442. package/src/io/formats/design-tokens/styles.ts +10 -7
  443. package/src/io/formats/design-tokens/sync/drift.ts +6 -4
  444. package/src/io/formats/design-tokens/values.ts +15 -8
  445. package/src/io/formats/drawio/warnings.ts +2 -2
  446. package/src/io/formats/fig/export/index.ts +36 -3
  447. package/src/io/formats/fig/export/patch/index.ts +4 -1
  448. package/src/io/formats/fig/export/setup.ts +25 -15
  449. package/src/io/formats/fig/export/variables.ts +17 -6
  450. package/src/io/formats/html/vectors.ts +1 -0
  451. package/src/io/formats/mermaid/layers.ts +2 -2
  452. package/src/io/formats/pdf/export.ts +1 -0
  453. package/src/io/formats/pdf/prepare.ts +6 -6
  454. package/src/io/formats/pen/index.ts +5 -2
  455. package/src/io/formats/raster/render.ts +12 -4
  456. package/src/io/formats/svg/defs.ts +26 -14
  457. package/src/io/formats/svg/effects.ts +2 -2
  458. package/src/io/formats/svg/export.ts +17 -3
  459. package/src/io/formats/svg/filter.ts +12 -2
  460. package/src/io/formats/svg/grain.ts +1 -1
  461. package/src/io/formats/svg/import.ts +6 -3
  462. package/src/io/formats/svg/text/export.ts +10 -8
  463. package/src/io/formats/svg/text/layout.ts +2 -2
  464. package/src/io/formats.ts +8 -1
  465. package/src/io/subgraph.ts +4 -1
  466. package/src/kiwi/fig/session/options.ts +4 -1
  467. package/src/layout/yoga-helpers.ts +8 -0
  468. package/src/layout.ts +47 -1
  469. package/src/lint/linter.ts +1 -1
  470. package/src/pairdraw-api/comments.ts +6 -0
  471. package/src/pairdraw-api/index.ts +7 -9
  472. package/src/rpc/read-commands.ts +4 -4
  473. package/src/rpc/variables-command.ts +2 -2
  474. package/src/text/font/provider.ts +26 -0
  475. package/src/text/font/{status.ts → readiness.ts} +13 -9
  476. package/src/text/index.ts +2 -1
  477. package/src/text/prepare.ts +9 -4
  478. package/src/tools/analyze/responsive/index.ts +8 -15
  479. package/src/tools/analyze/responsive/widths.ts +63 -0
  480. package/src/tools/analyze.ts +2 -0
  481. package/src/tools/codegen/tokens.ts +4 -2
  482. package/src/tools/comments.ts +6 -4
  483. package/src/tools/component-catalog.ts +5 -3
  484. package/src/tools/create/html.ts +0 -3
  485. package/src/tools/create/icons.ts +1 -1
  486. package/src/tools/create/svg.ts +4 -1
  487. package/src/tools/create/vector.ts +2 -2
  488. package/src/tools/css/shorthand.ts +64 -0
  489. package/src/tools/describe/index.ts +2 -8
  490. package/src/tools/html-host.ts +5 -3
  491. package/src/tools/image-ai/apply.ts +0 -2
  492. package/src/tools/image-ai/service.ts +5 -3
  493. package/src/tools/index.ts +2 -0
  494. package/src/tools/modify/effects.ts +1 -1
  495. package/src/tools/modify/geometry.ts +16 -3
  496. package/src/tools/modify/layout.ts +47 -13
  497. package/src/tools/modify/matching.ts +14 -11
  498. package/src/tools/modify/paint.ts +85 -5
  499. package/src/tools/modify/reactions.ts +3 -2
  500. package/src/tools/modify/text.ts +15 -11
  501. package/src/tools/prompts/codegen.md +2 -1
  502. package/src/tools/read/css.ts +365 -0
  503. package/src/tools/read/reactions.ts +3 -2
  504. package/src/tools/read/space.ts +0 -2
  505. package/src/tools/read.ts +1 -0
  506. package/src/tools/registry/core.ts +3 -2
  507. package/src/tools/schema.ts +14 -5
  508. package/src/tools/script/host.ts +6 -3
  509. package/src/tools/variables/collections.ts +1 -1
  510. package/src/tools/variables/values.ts +16 -5
  511. package/src/tools/vector/vectorize.ts +10 -4
  512. package/src/tools/video-host.ts +5 -3
  513. package/src/vector/vectorize/svg/gradients.ts +8 -5
  514. package/src/vector/vectorize/svg/to-vectors.ts +48 -14
  515. package/dist/text/font/status.d.ts +0 -28
  516. package/dist/text/font/status.d.ts.map +0 -1
  517. package/dist/text/font/status.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"layout.js","names":[],"sources":["../../../src/tools/modify/layout.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { PairdrawAPI } from '#core/pairdraw-api'\nimport { toolNumber, nodeIdInputSchema, defineTool, nodeNotFound } from '#core/tools/schema'\n\nexport const setLayout = defineTool({\n name: 'set_layout',\n\n description: 'Set auto-layout (flexbox) on a frame. Direction, alignment, spacing, padding.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Frame node ID')),\n direction: v.optional(\n v.pipe(\n v.picklist(['HORIZONTAL', 'VERTICAL']),\n v.description('Layout direction (keeps current if omitted)')\n )\n ),\n spacing: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.minValue(0),\n v.description('Gap between items (only changes if provided)')\n )\n )\n ),\n padding: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.minValue(0),\n v.description('Equal padding on all sides (only changes if provided)')\n )\n )\n ),\n padding_horizontal: v.optional(\n toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Horizontal padding')))\n ),\n padding_vertical: v.optional(\n toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Vertical padding')))\n ),\n align: v.optional(\n v.pipe(\n v.picklist(['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN', 'SPACE_AROUND']),\n v.description(\n 'Primary axis alignment (only changes if provided). SPACE_AROUND gives each child an equal share of the free space, half on each side, on top of the gap'\n )\n )\n ),\n counter_align: v.optional(\n v.pipe(\n v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH']),\n v.description('Cross axis alignment (only changes if provided)')\n )\n ),\n flow_direction: v.optional(\n v.pipe(\n v.picklist(['AUTO', 'LTR', 'RTL']),\n v.description('Child flow direction for auto-layout. AUTO inherits from parent.')\n )\n )\n }),\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n\n const raw = figma.graph.getNode(args.id)\n // A page holds layers; it is not a frame, so nothing lays it out.\n if (raw?.type === 'CANVAS')\n return {\n error: `A page cannot hold auto layout. Set it on a frame inside the page (${args.id}).`\n }\n if (!args.direction && raw?.layoutMode === 'NONE') {\n return {\n error: 'Frame has no auto-layout. Pass direction (\"HORIZONTAL\" or \"VERTICAL\") to enable it.'\n }\n }\n\n const wasNone = raw?.layoutMode === 'NONE'\n if (args.direction) node.layoutMode = args.direction\n if (wasNone) {\n node.primaryAxisSizingMode = 'AUTO'\n node.counterAxisSizingMode = 'AUTO'\n }\n if (args.spacing !== undefined) node.itemSpacing = args.spacing\n if (args.align !== undefined) node.primaryAxisAlignItems = args.align\n if (args.counter_align !== undefined) node.counterAxisAlignItems = args.counter_align\n if (args.flow_direction !== undefined)\n new PairdrawAPI(figma).setLayoutDirection(node, args.flow_direction)\n\n if (args.padding !== undefined) {\n node.paddingTop = args.padding\n node.paddingRight = args.padding\n node.paddingBottom = args.padding\n node.paddingLeft = args.padding\n }\n if (args.padding_horizontal !== undefined) {\n node.paddingLeft = args.padding_horizontal\n node.paddingRight = args.padding_horizontal\n }\n if (args.padding_vertical !== undefined) {\n node.paddingTop = args.padding_vertical\n node.paddingBottom = args.padding_vertical\n }\n\n return { id: args.id, spacing: node.itemSpacing }\n }\n})\n\nexport const setConstraints = defineTool({\n name: 'set_constraints',\n\n description: 'Set resize constraints for a node within its parent.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n horizontal: v.optional(\n v.pipe(\n v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']),\n v.description('Horizontal constraint')\n )\n ),\n vertical: v.optional(\n v.pipe(\n v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']),\n v.description('Vertical constraint')\n )\n )\n }),\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n if (args.horizontal || args.vertical) {\n node.constraints = {\n horizontal: args.horizontal ?? node.constraints.horizontal,\n vertical: args.vertical ?? node.constraints.vertical\n }\n }\n return { id: args.id, constraints: node.constraints }\n }\n})\n\nexport const setLayoutChild = defineTool({\n name: 'set_layout_child',\n\n description:\n 'Configure auto-layout child: sizing (FIXED/HUG/FILL), grow, alignment, absolute positioning.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Child node ID')),\n sizing_horizontal: v.optional(\n v.pipe(v.picklist(['FIXED', 'HUG', 'FILL']), v.description('Horizontal sizing mode'))\n ),\n sizing_vertical: v.optional(\n v.pipe(v.picklist(['FIXED', 'HUG', 'FILL']), v.description('Vertical sizing mode'))\n ),\n grow: v.optional(\n toolNumber(\n v.pipe(v.number(), v.minValue(0), v.description('Flex grow factor (0 = fixed, 1 = grow)'))\n )\n ),\n align_self: v.optional(\n v.pipe(\n v.picklist(['INHERIT', 'MIN', 'CENTER', 'MAX', 'STRETCH', 'BASELINE']),\n v.description('Self alignment override (cross-axis)')\n )\n ),\n positioning: v.optional(\n v.pipe(\n v.picklist(['AUTO', 'ABSOLUTE']),\n v.description('ABSOLUTE to take node out of auto-layout flow')\n )\n )\n }),\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n const updated: string[] = []\n if (args.sizing_horizontal !== undefined) {\n node.layoutSizingHorizontal = args.sizing_horizontal\n updated.push('layoutSizingHorizontal')\n }\n if (args.sizing_vertical !== undefined) {\n node.layoutSizingVertical = args.sizing_vertical\n updated.push('layoutSizingVertical')\n }\n if (args.grow !== undefined) {\n node.layoutGrow = args.grow\n updated.push('layoutGrow')\n }\n if (args.align_self !== undefined) {\n node.layoutAlign = args.align_self\n updated.push('layoutAlign')\n }\n if (args.positioning !== undefined) {\n node.layoutPositioning = args.positioning\n updated.push('layoutPositioning')\n }\n return { id: args.id, updated }\n }\n})\n"],"mappings":";;;;AAKA,MAAa,YAAY,WAAW;CAClC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAa;CAClD,OAAO,EAAE,aAAa;EACpB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC;EACrD,WAAW,EAAE,SACX,EAAE,KACA,EAAE,SAAS,CAAC,cAAc,UAAU,CAAC,GACrC,EAAE,YAAY,6CAA6C,CAC7D,CACF;EACA,SAAS,EAAE,SACT,WACE,EAAE,KACA,EAAE,OAAO,GACT,EAAE,SAAS,CAAC,GACZ,EAAE,YAAY,8CAA8C,CAC9D,CACF,CACF;EACA,SAAS,EAAE,SACT,WACE,EAAE,KACA,EAAE,OAAO,GACT,EAAE,SAAS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;EACA,IAAI,KAAK,eAAe,KAAA,GAAW;GACjC,KAAK,cAAc,KAAK;GACxB,QAAQ,KAAK,aAAa;EAC5B;EACA,IAAI,KAAK,gBAAgB,KAAA,GAAW;GAClC,KAAK,oBAAoB,KAAK;GAC9B,QAAQ,KAAK,mBAAmB;EAClC;EACA,OAAO;GAAE,IAAI,KAAK;GAAI;EAAQ;CAChC;AACF,CAAC"}
1
+ {"version":3,"file":"layout.js","names":[],"sources":["../../../src/tools/modify/layout.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { FigmaNodeProxy } from '#core/figma-api'\nimport { PairdrawAPI } from '#core/pairdraw-api'\nimport { lengthShorthandInput, parseLengthShorthand } from '#core/tools/css/shorthand'\nimport { toolNumber, nodeIdInputSchema, defineTool, nodeNotFound } from '#core/tools/schema'\n\ntype SpacingArgs = { padding?: number | string; gap?: number | string }\n\n/** Parses the shorthand before the frame changes, so bad input leaves it as it was. */\nfunction parseSpacing(\n args: SpacingArgs\n): { padding?: number[]; gap?: number[] } | { error: string } {\n const parsed: { padding?: number[]; gap?: number[] } = {}\n if (args.padding !== undefined) {\n const padding = parseLengthShorthand(args.padding, 4, 'padding')\n if ('error' in padding) return padding\n parsed.padding = padding\n }\n if (args.gap !== undefined) {\n const gap = parseLengthShorthand(args.gap, 2, 'gap')\n if ('error' in gap) return gap\n parsed.gap = gap\n }\n return parsed\n}\n\nfunction writeSpacing(node: FigmaNodeProxy, spacing: { padding?: number[]; gap?: number[] }): void {\n if (spacing.padding) {\n const [top, right, bottom, left] = spacing.padding\n node.paddingTop = top\n node.paddingRight = right\n node.paddingBottom = bottom\n node.paddingLeft = left\n }\n if (spacing.gap) {\n node.itemSpacing = spacing.gap[0]\n node.counterAxisSpacing = spacing.gap[1]\n }\n}\n\nexport const setLayout = defineTool({\n name: 'set_layout',\n\n description:\n 'Set auto-layout (flexbox) on a frame. Direction, alignment, spacing, padding, which also take CSS shorthand: padding=\"16px 24px\", gap=\"12px 4px\".',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Frame node ID')),\n direction: v.optional(\n v.pipe(\n v.picklist(['HORIZONTAL', 'VERTICAL']),\n v.description('Layout direction (keeps current if omitted)')\n )\n ),\n spacing: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.minValue(0),\n v.description('Gap between items (only changes if provided)')\n )\n )\n ),\n padding: v.optional(\n lengthShorthandInput(\n 'Padding: one length for every side, or CSS shorthand \"16px 24px\" / \"8px 16px 4px 24px\"'\n )\n ),\n gap: v.optional(\n lengthShorthandInput('Gap: one length, or \"12px 4px\" for main-axis and cross-axis spacing')\n ),\n padding_horizontal: v.optional(\n toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Horizontal padding')))\n ),\n padding_vertical: v.optional(\n toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Vertical padding')))\n ),\n align: v.optional(\n v.pipe(\n v.picklist(['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN', 'SPACE_AROUND']),\n v.description(\n 'Primary axis alignment (only changes if provided). SPACE_AROUND gives each child an equal share of the free space, half on each side, on top of the gap'\n )\n )\n ),\n counter_align: v.optional(\n v.pipe(\n v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH']),\n v.description('Cross axis alignment (only changes if provided)')\n )\n ),\n flow_direction: v.optional(\n v.pipe(\n v.picklist(['AUTO', 'LTR', 'RTL']),\n v.description('Child flow direction for auto-layout. AUTO inherits from parent.')\n )\n )\n }),\n execute: (figma, args) => {\n const spacing = parseSpacing(args)\n if ('error' in spacing) return spacing\n\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n\n const raw = figma.graph.getNode(args.id)\n // A page holds layers; it is not a frame, so nothing lays it out.\n if (raw?.type === 'CANVAS')\n return {\n error: `A page cannot hold auto layout. Set it on a frame inside the page (${args.id}).`\n }\n if (!args.direction && raw?.layoutMode === 'NONE') {\n return {\n error: 'Frame has no auto-layout. Pass direction (\"HORIZONTAL\" or \"VERTICAL\") to enable it.'\n }\n }\n\n const wasNone = raw?.layoutMode === 'NONE'\n if (args.direction) node.layoutMode = args.direction\n if (wasNone) {\n node.primaryAxisSizingMode = 'AUTO'\n node.counterAxisSizingMode = 'AUTO'\n }\n if (args.spacing !== undefined) node.itemSpacing = args.spacing\n if (args.align !== undefined) node.primaryAxisAlignItems = args.align\n if (args.counter_align !== undefined) node.counterAxisAlignItems = args.counter_align\n if (args.flow_direction !== undefined)\n new PairdrawAPI(figma).setLayoutDirection(node, args.flow_direction)\n\n writeSpacing(node, spacing)\n if (args.padding_horizontal !== undefined) {\n node.paddingLeft = args.padding_horizontal\n node.paddingRight = args.padding_horizontal\n }\n if (args.padding_vertical !== undefined) {\n node.paddingTop = args.padding_vertical\n node.paddingBottom = args.padding_vertical\n }\n\n return { id: args.id, spacing: node.itemSpacing }\n }\n})\n\nexport const setConstraints = defineTool({\n name: 'set_constraints',\n\n description: 'Set resize constraints for a node within its parent.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n horizontal: v.optional(\n v.pipe(\n v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']),\n v.description('Horizontal constraint')\n )\n ),\n vertical: v.optional(\n v.pipe(\n v.picklist(['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']),\n v.description('Vertical constraint')\n )\n )\n }),\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n if (args.horizontal || args.vertical) {\n node.constraints = {\n horizontal: args.horizontal ?? node.constraints.horizontal,\n vertical: args.vertical ?? node.constraints.vertical\n }\n }\n return { id: args.id, constraints: node.constraints }\n }\n})\n\nexport const setLayoutChild = defineTool({\n name: 'set_layout_child',\n\n description:\n 'Configure auto-layout child: sizing (FIXED/HUG/FILL), grow, alignment, absolute positioning.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Child node ID')),\n sizing_horizontal: v.optional(\n v.pipe(v.picklist(['FIXED', 'HUG', 'FILL']), v.description('Horizontal sizing mode'))\n ),\n sizing_vertical: v.optional(\n v.pipe(v.picklist(['FIXED', 'HUG', 'FILL']), v.description('Vertical sizing mode'))\n ),\n grow: v.optional(\n toolNumber(\n v.pipe(v.number(), v.minValue(0), v.description('Flex grow factor (0 = fixed, 1 = grow)'))\n )\n ),\n align_self: v.optional(\n v.pipe(\n v.picklist(['INHERIT', 'MIN', 'CENTER', 'MAX', 'STRETCH', 'BASELINE']),\n v.description('Self alignment override (cross-axis)')\n )\n ),\n positioning: v.optional(\n v.pipe(\n v.picklist(['AUTO', 'ABSOLUTE']),\n v.description('ABSOLUTE to take node out of auto-layout flow')\n )\n )\n }),\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n const updated: string[] = []\n if (args.sizing_horizontal !== undefined) {\n node.layoutSizingHorizontal = args.sizing_horizontal\n updated.push('layoutSizingHorizontal')\n }\n if (args.sizing_vertical !== undefined) {\n node.layoutSizingVertical = args.sizing_vertical\n updated.push('layoutSizingVertical')\n }\n if (args.grow !== undefined) {\n node.layoutGrow = args.grow\n updated.push('layoutGrow')\n }\n if (args.align_self !== undefined) {\n node.layoutAlign = args.align_self\n updated.push('layoutAlign')\n }\n if (args.positioning !== undefined) {\n node.layoutPositioning = args.positioning\n updated.push('layoutPositioning')\n }\n return { id: args.id, updated }\n }\n})\n"],"mappings":";;;;;;AAUA,SAAS,aACP,MAC4D;CAC5D,MAAM,SAAiD,CAAC;CACxD,IAAI,KAAK,YAAY,KAAA,GAAW;EAC9B,MAAM,UAAU,qBAAqB,KAAK,SAAS,GAAG,SAAS;EAC/D,IAAI,WAAW,SAAS,OAAO;EAC/B,OAAO,UAAU;CACnB;CACA,IAAI,KAAK,QAAQ,KAAA,GAAW;EAC1B,MAAM,MAAM,qBAAqB,KAAK,KAAK,GAAG,KAAK;EACnD,IAAI,WAAW,KAAK,OAAO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E,YAAY,wCAAwC,CAAC,CAC3F,CACF;EACA,YAAY,EAAE,SACZ,EAAE,KACA,EAAE,SAAS;GAAC;GAAW;GAAO;GAAU;GAAO;GAAW;EAAU,CAAC,GACrE,EAAE,YAAY,sCAAsC,CACtD,CACF;EACA,aAAa,EAAE,SACb,EAAE,KACA,EAAE,SAAS,CAAC,QAAQ,UAAU,CAAC,GAC/B,EAAE,YAAY,+CAA+C,CAC/D,CACF;CACF,CAAC;CACD,UAAU,OAAO,SAAS;EACxB,MAAM,OAAO,MAAM,YAAY,KAAK,EAAE;EACtC,IAAI,CAAC,MAAM,OAAO,aAAa,KAAK,EAAE;EACtC,MAAM,UAAoB,CAAC;EAC3B,IAAI,KAAK,sBAAsB,KAAA,GAAW;GACxC,KAAK,yBAAyB,KAAK;GACnC,QAAQ,KAAK,wBAAwB;EACvC;EACA,IAAI,KAAK,oBAAoB,KAAA,GAAW;GACtC,KAAK,uBAAuB,KAAK;GACjC,QAAQ,KAAK,sBAAsB;EACrC;EACA,IAAI,KAAK,SAAS,KAAA,GAAW;GAC3B,KAAK,aAAa,KAAK;GACvB,QAAQ,KAAK,YAAY;EAC3B;EACA,IAAI,KAAK,eAAe,KAAA,GAAW;GACjC,KAAK,cAAc,KAAK;GACxB,QAAQ,KAAK,aAAa;EAC5B;EACA,IAAI,KAAK,gBAAgB,KAAA,GAAW;GAClC,KAAK,oBAAoB,KAAK;GAC9B,QAAQ,KAAK,mBAAmB;EAClC;EACA,OAAO;GAAE,IAAI,KAAK;GAAI;EAAQ;CAChC;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"matching.d.ts","names":[],"sources":["../../../src/tools/modify/matching.ts"],"mappings":";;cAoNa,2BAAA"}
1
+ {"version":3,"file":"matching.d.ts","names":[],"sources":["../../../src/tools/modify/matching.ts"],"mappings":";;cAuNa,2BAAA"}
@@ -59,15 +59,15 @@ function channels(color) {
59
59
  ].map((value) => Math.round(value * 255)).join(",");
60
60
  }
61
61
  /** A colour as a tool reads it, so a bad value fails with the message other tools give. */
62
- function colorOf(value) {
63
- const parsed = parseToolColor(value);
62
+ function colorOf(value, profile) {
63
+ const parsed = parseToolColor(value, profile);
64
64
  if ("error" in parsed) throw new Error(parsed.error);
65
65
  return parsed;
66
66
  }
67
67
  /** The swap a colour pair makes; throws on a value that is not a colour. */
68
- function colorSwap(pair) {
69
- const from = colorOf(pair.from);
70
- const to = colorOf(pair.to);
68
+ function colorSwap(pair, profile) {
69
+ const from = colorOf(pair.from, profile);
70
+ const to = colorOf(pair.to, profile);
71
71
  const key = channels(from);
72
72
  const percent = (value) => Math.round(value * 100);
73
73
  return {
@@ -158,8 +158,8 @@ function textEdits(node, replacements) {
158
158
  return getStyledTextSegments(node, ["fontName", "fontSize"]).flatMap((segment) => edit(segment.start, segment.end, segment.fontName, segment.fontSize) ?? []);
159
159
  }
160
160
  const REPLACEMENT_KINDS = Object.keys(replacementInputs);
161
- function colorSwaps(pairs) {
162
- return (pairs ?? []).map(colorSwap);
161
+ function colorSwaps(pairs, profile) {
162
+ return (pairs ?? []).map((pair) => colorSwap(pair, profile));
163
163
  }
164
164
  const replaceMatchingProperties = defineTool({
165
165
  name: "replace_matching_properties",
@@ -195,9 +195,9 @@ const replaceMatchingProperties = defineTool({
195
195
  const readOnly = [];
196
196
  try {
197
197
  const swaps = {
198
- fill: colorSwaps(args.fill_color),
199
- text: colorSwaps(args.text_color),
200
- stroke: colorSwaps(args.stroke_color)
198
+ fill: colorSwaps(args.fill_color, figma.graph.documentColorSpace),
199
+ text: colorSwaps(args.text_color, figma.graph.documentColorSpace),
200
+ stroke: colorSwaps(args.stroke_color, figma.graph.documentColorSpace)
201
201
  };
202
202
  for (const node of nodes) {
203
203
  const paint = paintAndGeometryChanges(node, args, swaps);
@@ -1 +1 @@
1
- {"version":3,"file":"matching.js","names":[],"sources":["../../../src/tools/modify/matching.ts"],"sourcesContent":["import { mapValues, pick } from 'es-toolkit'\nimport * as v from 'valibot'\n\nimport type { Fill, NodeType, SceneNode } from '@pairdraw/scene-graph'\nimport { copyStroke } from '@pairdraw/scene-graph/copy'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { getNodeEditCapability } from '#core/editor/capabilities'\nimport type { FigmaAPI } from '#core/figma-api'\nimport { editNode } from '#core/figma-api/accessor-utils'\nimport type { FigmaFontNameInput } from '#core/figma-api/fonts/names'\nimport { getStyledTextSegments } from '#core/figma-api/text/style'\nimport { collectNodeFontFaces } from '#core/text/requirements/collect'\nimport { defineTool, parseToolColor, toolFailure, toolNumber } from '#core/tools/schema'\n\nimport { textFonts } from './text'\n\nconst colorPairSchema = v.strictObject({\n from: v.pipe(v.string(), v.description('Color to find (hex); with alpha, only that opacity')),\n to: v.pipe(v.string(), v.description('Color to use instead (hex); with alpha, its opacity'))\n})\nconst numberPairSchema = v.strictObject({\n from: toolNumber(v.pipe(v.number(), v.description('Value to find'))),\n to: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Value to use instead')))\n})\nconst textPairSchema = v.strictObject({\n from: v.pipe(v.string(), v.nonEmpty(), v.description('Value to find (case-insensitive)')),\n to: v.pipe(v.string(), v.nonEmpty(), v.description('Value to use instead'))\n})\nconst fontNameSchema = v.object({ family: v.string(), style: v.string() })\n\nconst pairs = <S extends v.GenericSchema>(schema: S, description: string) =>\n v.optional(v.pipe(v.array(schema), v.minLength(1), v.description(description)))\n\nconst replacementInputs = {\n fill_color: pairs(colorPairSchema, 'Solid fill colors of layers other than text'),\n text_color: pairs(colorPairSchema, 'Text colors, including colored ranges'),\n stroke_color: pairs(colorPairSchema, 'Solid stroke colors'),\n stroke_weight: pairs(numberPairSchema, 'Stroke weights of layers that have strokes'),\n corner_radius: pairs(\n numberPairSchema,\n 'Corner radii: a layer’s radius, or each corner on its own where they are set separately'\n ),\n font_family: pairs(textPairSchema, 'Font families, keeping each range’s style'),\n font_style: pairs(textPairSchema, 'Font styles such as Regular or Bold, keeping the family'),\n font_size: pairs(numberPairSchema, 'Font sizes')\n}\n\ntype ReplacementKind = keyof typeof replacementInputs\ntype ColorPair = v.InferOutput<typeof colorPairSchema>\ntype NumberPair = v.InferOutput<typeof numberPairSchema>\ntype TextPair = v.InferOutput<typeof textPairSchema>\ntype Replacements = {\n fill_color?: ColorPair[]\n text_color?: ColorPair[]\n stroke_color?: ColorPair[]\n stroke_weight?: NumberPair[]\n corner_radius?: NumberPair[]\n font_family?: TextPair[]\n font_style?: TextPair[]\n font_size?: NumberPair[]\n}\ntype Scope = { ids?: string[]; within: 'page' | 'selection' }\n\nconst CORNERS = [\n 'topLeftRadius',\n 'topRightRadius',\n 'bottomRightRadius',\n 'bottomLeftRadius'\n] as const\n/** Layers that draw their corners rounded; a radius on any other is not shown. */\nconst ROUNDED_TYPES: ReadonlySet<NodeType> = new Set([\n 'FRAME',\n 'RECTANGLE',\n 'ROUNDED_RECTANGLE',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n\n/** Channels as 0–255 integers, so a hex written by hand matches the colour it names. */\nfunction channels(color: Color): string {\n return [color.r, color.g, color.b].map((value) => Math.round(value * 255)).join(',')\n}\n\n/** A colour as a tool reads it, so a bad value fails with the message other tools give. */\nfunction colorOf(value: string): Color {\n const parsed = parseToolColor(value)\n if ('error' in parsed) throw new Error(parsed.error)\n return parsed\n}\n\ninterface ColorSwap {\n match: (paint: Fill) => boolean\n apply: (paint: Fill) => Fill\n}\n\n/** The swap a colour pair makes; throws on a value that is not a colour. */\nfunction colorSwap(pair: ColorPair): ColorSwap {\n const from = colorOf(pair.from)\n const to = colorOf(pair.to)\n const key = channels(from)\n const percent = (value: number) => Math.round(value * 100)\n return {\n match: (paint) =>\n paint.type === 'SOLID' &&\n channels(paint.color) === key &&\n (from.a >= 1 || percent(paint.opacity * paint.color.a) === percent(from.a)),\n // A colour's alpha is the paint's opacity, as Figma takes it; without one the paint keeps its own.\n apply: (paint) => ({\n ...paint,\n color: { ...to, a: 1 },\n opacity: to.a < 1 ? to.a : paint.opacity * paint.color.a\n })\n }\n}\n\n/** `paints` with every listed colour swapped, or null when none matched. */\nfunction swapPaints<T extends Fill>(\n paints: readonly T[],\n swaps: readonly ColorSwap[],\n bound: (index: number) => boolean\n): T[] | null {\n const next = paints.map((paint, index) => {\n if (bound(index)) return paint\n const swap = swaps.find((candidate) => candidate.match(paint))\n return swap ? { ...paint, ...swap.apply(paint) } : paint\n })\n return next.some((paint, index) => paint !== paints[index]) ? next : null\n}\n\nfunction swapNumber(value: number, swaps: readonly NumberPair[] | undefined): number | null {\n const swap = swaps?.find((pair) => pair.from === value)\n return swap && swap.to !== value ? swap.to : null\n}\n\nfunction swapText(value: string, swaps: readonly TextPair[] | undefined): string | null {\n const swap = swaps?.find((pair) => pair.from.toLowerCase() === value.toLowerCase())\n return swap && swap.to !== value ? swap.to : null\n}\n\n/** The layers a call searches: the given ones, the selection, or the page's, with descendants. */\nfunction searchedNodes(figma: FigmaAPI, scope: Scope): SceneNode[] | string {\n const graph = figma.graph\n let roots: string[]\n if (scope.ids && scope.ids.length > 0) {\n const missing = scope.ids.find((id) => !graph.getNode(id))\n if (missing) return `Node \"${missing}\" not found`\n roots = scope.ids\n } else if (scope.within === 'selection') {\n roots = figma.currentPage.selection.map((node) => node.id)\n if (roots.length === 0) return 'Nothing is selected'\n } else {\n roots = graph.getNode(figma.currentPage.id)?.childIds ?? []\n }\n const nodes: SceneNode[] = []\n const seen = new Set<string>()\n const walk = (id: string) => {\n const node = seen.has(id) ? undefined : graph.getNode(id)\n if (!node) return\n seen.add(id)\n nodes.push(node)\n for (const childId of node.childIds) walk(childId)\n }\n for (const id of roots) walk(id)\n return nodes\n}\n\ninterface TextEdit {\n start: number\n end: number\n fontName?: { family: string; style: string }\n fontSize?: number\n family: boolean\n style: boolean\n}\n\n/** The font and size changes one text layer takes, range by range. */\nfunction textEdits(node: SceneNode, replacements: Replacements): TextEdit[] {\n if (node.type !== 'TEXT') return []\n const { font_family, font_style, font_size } = replacements\n if (!font_family && !font_style && !font_size) return []\n const edit = (start: number, end: number, font: unknown, size: unknown): TextEdit | null => {\n if (!v.is(fontNameSchema, font)) return null\n const family = swapText(font.family, font_family)\n const style = swapText(font.style, font_style)\n const fontSize = typeof size === 'number' ? swapNumber(size, font_size) : null\n if (!family && !style && fontSize === null) return null\n const textEdit: TextEdit = { start, end, family: family !== null, style: style !== null }\n if (family || style) {\n textEdit.fontName = { family: family ?? font.family, style: style ?? font.style }\n }\n if (fontSize !== null) textEdit.fontSize = fontSize\n return textEdit\n }\n if (node.text.length === 0) {\n // An empty text has no ranges to read; its own face is the first one it lists.\n const face = collectNodeFontFaces(node).at(0)\n const whole = face && edit(0, 0, face, node.fontSize)\n return whole ? [whole] : []\n }\n return getStyledTextSegments(node, ['fontName', 'fontSize']).flatMap(\n (segment) => edit(segment.start, segment.end, segment.fontName, segment.fontSize) ?? []\n )\n}\n\nconst REPLACEMENT_KINDS = Object.keys(replacementInputs) as ReplacementKind[]\n\nfunction colorSwaps(pairs: readonly ColorPair[] | undefined): ColorSwap[] {\n return (pairs ?? []).map(colorSwap)\n}\n\nexport const replaceMatchingProperties = defineTool({\n name: 'replace_matching_properties',\n description:\n 'Swap one value for another on every layer that uses it, across the current page (default), the selection, or the given layers with their descendants: fill, text, and stroke colors, stroke weights, corner radii, font families, font styles, and font sizes. Each property takes a list of { from, to } pairs; colors match by hex, ignoring opacity unless from has alpha, and colors bound to variables are left alone. Layers of read-only library components are not changed and come back in read_only. Returns how many values changed per property and the layers changed.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n ids: v.optional(\n v.pipe(\n v.array(v.string()),\n v.description('Layers to search with their descendants (default: see within)')\n )\n ),\n within: v.optional(\n v.pipe(\n v.picklist(['page', 'selection']),\n v.description('Without ids: the current page (default) or the selection')\n ),\n 'page'\n ),\n ...replacementInputs\n }),\n fonts: (figma, args) => {\n const nodes = searchedNodes(figma, args)\n if (typeof nodes === 'string') return []\n const fonts: FigmaFontNameInput[] = []\n for (const node of nodes) {\n const edits = textEdits(node, args)\n if (edits.length === 0) continue\n fonts.push(...textFonts(figma, node.id))\n for (const edit of edits) if (edit.fontName) fonts.push(edit.fontName)\n }\n return fonts\n },\n execute: (figma, args) => {\n const kinds = REPLACEMENT_KINDS.filter((kind) => args[kind] !== undefined)\n if (kinds.length === 0) return { error: 'Name at least one property to replace' }\n const nodes = searchedNodes(figma, args)\n if (typeof nodes === 'string') return { error: nodes }\n const counts = mapValues(replacementInputs, () => 0)\n const changed = new Set<string>()\n const readOnly: string[] = []\n try {\n const swaps = {\n fill: colorSwaps(args.fill_color),\n text: colorSwaps(args.text_color),\n stroke: colorSwaps(args.stroke_color)\n }\n for (const node of nodes) {\n const paint = paintAndGeometryChanges(node, args, swaps)\n const edits = textEdits(node, args)\n if (!paint && edits.length === 0) continue\n // A library's components change in that library, so their layers are reported instead.\n if (!getNodeEditCapability(figma.graph, node.id).editable) {\n readOnly.push(node.id)\n continue\n }\n if (paint) {\n // As the node setters write, so styles detach and instances keep the change.\n editNode(figma.graph, node.id, paint.changes, figma.groupFitOptions)\n for (const kind of REPLACEMENT_KINDS) counts[kind] += paint.counts[kind] ?? 0\n }\n if (edits.length > 0) changeText(figma, node, edits, counts)\n changed.add(node.id)\n }\n } catch (error) {\n return toolFailure(error)\n }\n return {\n replaced: pick(counts, kinds),\n changed: changed.size,\n ids: [...changed],\n ...(readOnly.length > 0 ? { read_only: readOnly } : {})\n }\n }\n})\n\ntype Counts = Record<ReplacementKind, number>\n\n/** What one layer's paints, stroke weight, and corners change to, with the values it changes. */\nfunction paintAndGeometryChanges(\n node: SceneNode,\n replacements: Replacements,\n swaps: { fill: ColorSwap[]; text: ColorSwap[]; stroke: ColorSwap[] }\n): { changes: Partial<SceneNode>; counts: Partial<Counts> } | null {\n const changes: Partial<SceneNode> = {}\n const counts: Partial<Counts> = {}\n const count = (kind: ReplacementKind, amount = 1) => {\n counts[kind] = (counts[kind] ?? 0) + amount\n }\n const isText = node.type === 'TEXT'\n const fillSwaps = isText ? swaps.text : swaps.fill\n const fillKind = isText ? 'text_color' : 'fill_color'\n const bound = (kind: 'fills' | 'strokes') => (index: number) =>\n !!node.boundVariables[`${kind}/${index}/color`]\n if (fillSwaps.length > 0) {\n const fills = swapPaints(node.fills, fillSwaps, bound('fills'))\n if (fills) {\n changes.fills = fills\n count(fillKind, fills.filter((paint, index) => paint !== node.fills[index]).length)\n }\n if (isText) {\n let runs = 0\n const styleRuns = node.styleRuns.map((run) => {\n const runFills = run.style.fills && swapPaints(run.style.fills, fillSwaps, () => false)\n if (!runFills) return run\n runs++\n return { ...run, style: { ...run.style, fills: runFills } }\n })\n if (runs > 0) {\n changes.styleRuns = styleRuns\n count('text_color', runs)\n }\n }\n }\n if (swaps.stroke.length > 0) {\n const strokes = swapPaints(node.strokes, swaps.stroke, bound('strokes'))\n if (strokes) {\n changes.strokes = strokes\n count('stroke_color', strokes.filter((paint, index) => paint !== node.strokes[index]).length)\n }\n }\n const weight =\n node.strokes.length > 0 ? swapNumber(node.strokeWeight, replacements.stroke_weight) : null\n if (weight !== null) {\n // Each stroke draws at its own weight, so they all take it, as the strokeWeight setter does.\n changes.strokeWeight = weight\n changes.strokes = (changes.strokes ?? node.strokes).map((stroke) => ({\n ...copyStroke(stroke),\n weight\n }))\n count('stroke_weight')\n }\n if (replacements.corner_radius && ROUNDED_TYPES.has(node.type)) {\n Object.assign(changes, cornerChanges(node, replacements.corner_radius, count))\n }\n return Object.keys(changes).length > 0 ? { changes, counts } : null\n}\n\n/**\n * The corner radii `swaps` give a layer. Corners set together draw `cornerRadius`, whatever the\n * corner fields hold, so only corners set one by one are matched each on its own.\n */\nfunction cornerChanges(\n node: SceneNode,\n swaps: readonly NumberPair[],\n count: (kind: ReplacementKind) => void\n): Partial<SceneNode> {\n if (!node.independentCorners) {\n const radius = swapNumber(node.cornerRadius, swaps)\n if (radius === null) return {}\n count('corner_radius')\n return {\n cornerRadius: radius,\n ...Object.fromEntries(CORNERS.map((corner) => [corner, radius])),\n independentCorners: false\n }\n }\n const changes: Partial<SceneNode> = {}\n for (const corner of CORNERS) {\n const radius = swapNumber(node[corner], swaps)\n if (radius === null) continue\n changes[corner] = radius\n count('corner_radius')\n }\n const radii = CORNERS.map((corner) => changes[corner] ?? node[corner])\n if (radii.every((radius, index) => radius === node[CORNERS[index]])) return {}\n const uniform = radii.every((radius) => radius === radii[0])\n changes.cornerRadius = uniform ? radii[0] : node.cornerRadius\n changes.independentCorners = !uniform\n return changes\n}\n\nfunction changeText(\n figma: FigmaAPI,\n node: SceneNode,\n edits: readonly TextEdit[],\n counts: Record<ReplacementKind, number>\n): void {\n const text = figma.getNodeById(node.id)\n if (!text) return\n for (const edit of edits) {\n // A range over all of the text sets the text's own font, as set_font does, not a style run.\n const ranged = edit.start > 0 || edit.end < node.text.length\n if (edit.fontName) {\n if (ranged) text.setRangeFontName(edit.start, edit.end, edit.fontName)\n else text.fontName = edit.fontName\n }\n // The size comes after the font, so it lays the text out in the font it ends up in.\n if (edit.fontSize !== undefined) {\n if (ranged) text.setRangeFontSize(edit.start, edit.end, edit.fontSize)\n else text.fontSize = edit.fontSize\n counts.font_size++\n }\n if (edit.family) counts.font_family++\n if (edit.style) counts.font_style++\n }\n}\n"],"mappings":";;;;;;;;;;AAiBA,MAAM,kBAAkB,EAAE,aAAa;CACrC,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,oDAAoD,CAAC;CAC5F,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,qDAAqD,CAAC;AAC7F,CAAC;AACD,MAAM,mBAAmB,EAAE,aAAa;CACtC,MAAM,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,CAAC;CACnE,IAAI,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,YAAY,sBAAsB,CAAC,CAAC;AACzF,CAAC;AACD,MAAM,iBAAiB,EAAE,aAAa;CACpC,MAAM,EAAE,KAAK,EAAE,OAAO,GAA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O;EAExB,MAAM,SAAS,KAAK,QAAQ,KAAK,KAAK,MAAM,KAAK,KAAK;EACtD,IAAI,KAAK,UAAU;GACjB,IAAI,QAAQ,KAAK,iBAAiB,KAAK,OAAO,KAAK,KAAK,KAAK,QAAQ;QAChE,KAAK,WAAW,KAAK;EAC5B;EAEA,IAAI,KAAK,aAAa,KAAA,GAAW;GAC/B,IAAI,QAAQ,KAAK,iBAAiB,KAAK,OAAO,KAAK,KAAK,KAAK,QAAQ;QAChE,KAAK,WAAW,KAAK;GAC1B,OAAO;EACT;EACA,IAAI,KAAK,QAAQ,OAAO;EACxB,IAAI,KAAK,OAAO,OAAO;CACzB;AACF"}
1
+ {"version":3,"file":"matching.js","names":[],"sources":["../../../src/tools/modify/matching.ts"],"sourcesContent":["import { mapValues, pick } from 'es-toolkit'\nimport * as v from 'valibot'\n\nimport type { DocumentColorSpace, Fill, NodeType, SceneNode } from '@pairdraw/scene-graph'\nimport { copyStroke } from '@pairdraw/scene-graph/copy'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { getNodeEditCapability } from '#core/editor/capabilities'\nimport type { FigmaAPI } from '#core/figma-api'\nimport { editNode } from '#core/figma-api/accessor-utils'\nimport type { FigmaFontNameInput } from '#core/figma-api/fonts/names'\nimport { getStyledTextSegments } from '#core/figma-api/text/style'\nimport { collectNodeFontFaces } from '#core/text/requirements/collect'\nimport { defineTool, parseToolColor, toolFailure, toolNumber } from '#core/tools/schema'\n\nimport { textFonts } from './text'\n\nconst colorPairSchema = v.strictObject({\n from: v.pipe(v.string(), v.description('Color to find (hex); with alpha, only that opacity')),\n to: v.pipe(v.string(), v.description('Color to use instead (hex); with alpha, its opacity'))\n})\nconst numberPairSchema = v.strictObject({\n from: toolNumber(v.pipe(v.number(), v.description('Value to find'))),\n to: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Value to use instead')))\n})\nconst textPairSchema = v.strictObject({\n from: v.pipe(v.string(), v.nonEmpty(), v.description('Value to find (case-insensitive)')),\n to: v.pipe(v.string(), v.nonEmpty(), v.description('Value to use instead'))\n})\nconst fontNameSchema = v.object({ family: v.string(), style: v.string() })\n\nconst pairs = <S extends v.GenericSchema>(schema: S, description: string) =>\n v.optional(v.pipe(v.array(schema), v.minLength(1), v.description(description)))\n\nconst replacementInputs = {\n fill_color: pairs(colorPairSchema, 'Solid fill colors of layers other than text'),\n text_color: pairs(colorPairSchema, 'Text colors, including colored ranges'),\n stroke_color: pairs(colorPairSchema, 'Solid stroke colors'),\n stroke_weight: pairs(numberPairSchema, 'Stroke weights of layers that have strokes'),\n corner_radius: pairs(\n numberPairSchema,\n 'Corner radii: a layer’s radius, or each corner on its own where they are set separately'\n ),\n font_family: pairs(textPairSchema, 'Font families, keeping each range’s style'),\n font_style: pairs(textPairSchema, 'Font styles such as Regular or Bold, keeping the family'),\n font_size: pairs(numberPairSchema, 'Font sizes')\n}\n\ntype ReplacementKind = keyof typeof replacementInputs\ntype ColorPair = v.InferOutput<typeof colorPairSchema>\ntype NumberPair = v.InferOutput<typeof numberPairSchema>\ntype TextPair = v.InferOutput<typeof textPairSchema>\ntype Replacements = {\n fill_color?: ColorPair[]\n text_color?: ColorPair[]\n stroke_color?: ColorPair[]\n stroke_weight?: NumberPair[]\n corner_radius?: NumberPair[]\n font_family?: TextPair[]\n font_style?: TextPair[]\n font_size?: NumberPair[]\n}\ntype Scope = { ids?: string[]; within: 'page' | 'selection' }\n\nconst CORNERS = [\n 'topLeftRadius',\n 'topRightRadius',\n 'bottomRightRadius',\n 'bottomLeftRadius'\n] as const\n/** Layers that draw their corners rounded; a radius on any other is not shown. */\nconst ROUNDED_TYPES: ReadonlySet<NodeType> = new Set([\n 'FRAME',\n 'RECTANGLE',\n 'ROUNDED_RECTANGLE',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n\n/** Channels as 0–255 integers, so a hex written by hand matches the colour it names. */\nfunction channels(color: Color): string {\n return [color.r, color.g, color.b].map((value) => Math.round(value * 255)).join(',')\n}\n\n/** A colour as a tool reads it, so a bad value fails with the message other tools give. */\nfunction colorOf(value: string, profile: DocumentColorSpace): Color {\n const parsed = parseToolColor(value, profile)\n if ('error' in parsed) throw new Error(parsed.error)\n return parsed\n}\n\ninterface ColorSwap {\n match: (paint: Fill) => boolean\n apply: (paint: Fill) => Fill\n}\n\n/** The swap a colour pair makes; throws on a value that is not a colour. */\nfunction colorSwap(pair: ColorPair, profile: DocumentColorSpace): ColorSwap {\n const from = colorOf(pair.from, profile)\n const to = colorOf(pair.to, profile)\n const key = channels(from)\n const percent = (value: number) => Math.round(value * 100)\n return {\n match: (paint) =>\n paint.type === 'SOLID' &&\n channels(paint.color) === key &&\n (from.a >= 1 || percent(paint.opacity * paint.color.a) === percent(from.a)),\n // A colour's alpha is the paint's opacity, as Figma takes it; without one the paint keeps its own.\n apply: (paint) => ({\n ...paint,\n color: { ...to, a: 1 },\n opacity: to.a < 1 ? to.a : paint.opacity * paint.color.a\n })\n }\n}\n\n/** `paints` with every listed colour swapped, or null when none matched. */\nfunction swapPaints<T extends Fill>(\n paints: readonly T[],\n swaps: readonly ColorSwap[],\n bound: (index: number) => boolean\n): T[] | null {\n const next = paints.map((paint, index) => {\n if (bound(index)) return paint\n const swap = swaps.find((candidate) => candidate.match(paint))\n return swap ? { ...paint, ...swap.apply(paint) } : paint\n })\n return next.some((paint, index) => paint !== paints[index]) ? next : null\n}\n\nfunction swapNumber(value: number, swaps: readonly NumberPair[] | undefined): number | null {\n const swap = swaps?.find((pair) => pair.from === value)\n return swap && swap.to !== value ? swap.to : null\n}\n\nfunction swapText(value: string, swaps: readonly TextPair[] | undefined): string | null {\n const swap = swaps?.find((pair) => pair.from.toLowerCase() === value.toLowerCase())\n return swap && swap.to !== value ? swap.to : null\n}\n\n/** The layers a call searches: the given ones, the selection, or the page's, with descendants. */\nfunction searchedNodes(figma: FigmaAPI, scope: Scope): SceneNode[] | string {\n const graph = figma.graph\n let roots: string[]\n if (scope.ids && scope.ids.length > 0) {\n const missing = scope.ids.find((id) => !graph.getNode(id))\n if (missing) return `Node \"${missing}\" not found`\n roots = scope.ids\n } else if (scope.within === 'selection') {\n roots = figma.currentPage.selection.map((node) => node.id)\n if (roots.length === 0) return 'Nothing is selected'\n } else {\n roots = graph.getNode(figma.currentPage.id)?.childIds ?? []\n }\n const nodes: SceneNode[] = []\n const seen = new Set<string>()\n const walk = (id: string) => {\n const node = seen.has(id) ? undefined : graph.getNode(id)\n if (!node) return\n seen.add(id)\n nodes.push(node)\n for (const childId of node.childIds) walk(childId)\n }\n for (const id of roots) walk(id)\n return nodes\n}\n\ninterface TextEdit {\n start: number\n end: number\n fontName?: { family: string; style: string }\n fontSize?: number\n family: boolean\n style: boolean\n}\n\n/** The font and size changes one text layer takes, range by range. */\nfunction textEdits(node: SceneNode, replacements: Replacements): TextEdit[] {\n if (node.type !== 'TEXT') return []\n const { font_family, font_style, font_size } = replacements\n if (!font_family && !font_style && !font_size) return []\n const edit = (start: number, end: number, font: unknown, size: unknown): TextEdit | null => {\n if (!v.is(fontNameSchema, font)) return null\n const family = swapText(font.family, font_family)\n const style = swapText(font.style, font_style)\n const fontSize = typeof size === 'number' ? swapNumber(size, font_size) : null\n if (!family && !style && fontSize === null) return null\n const textEdit: TextEdit = { start, end, family: family !== null, style: style !== null }\n if (family || style) {\n textEdit.fontName = { family: family ?? font.family, style: style ?? font.style }\n }\n if (fontSize !== null) textEdit.fontSize = fontSize\n return textEdit\n }\n if (node.text.length === 0) {\n // An empty text has no ranges to read; its own face is the first one it lists.\n const face = collectNodeFontFaces(node).at(0)\n const whole = face && edit(0, 0, face, node.fontSize)\n return whole ? [whole] : []\n }\n return getStyledTextSegments(node, ['fontName', 'fontSize']).flatMap(\n (segment) => edit(segment.start, segment.end, segment.fontName, segment.fontSize) ?? []\n )\n}\n\nconst REPLACEMENT_KINDS = Object.keys(replacementInputs) as ReplacementKind[]\n\nfunction colorSwaps(\n pairs: readonly ColorPair[] | undefined,\n profile: DocumentColorSpace\n): ColorSwap[] {\n return (pairs ?? []).map((pair) => colorSwap(pair, profile))\n}\n\nexport const replaceMatchingProperties = defineTool({\n name: 'replace_matching_properties',\n description:\n 'Swap one value for another on every layer that uses it, across the current page (default), the selection, or the given layers with their descendants: fill, text, and stroke colors, stroke weights, corner radii, font families, font styles, and font sizes. Each property takes a list of { from, to } pairs; colors match by hex, ignoring opacity unless from has alpha, and colors bound to variables are left alone. Layers of read-only library components are not changed and come back in read_only. Returns how many values changed per property and the layers changed.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n ids: v.optional(\n v.pipe(\n v.array(v.string()),\n v.description('Layers to search with their descendants (default: see within)')\n )\n ),\n within: v.optional(\n v.pipe(\n v.picklist(['page', 'selection']),\n v.description('Without ids: the current page (default) or the selection')\n ),\n 'page'\n ),\n ...replacementInputs\n }),\n fonts: (figma, args) => {\n const nodes = searchedNodes(figma, args)\n if (typeof nodes === 'string') return []\n const fonts: FigmaFontNameInput[] = []\n for (const node of nodes) {\n const edits = textEdits(node, args)\n if (edits.length === 0) continue\n fonts.push(...textFonts(figma, node.id))\n for (const edit of edits) if (edit.fontName) fonts.push(edit.fontName)\n }\n return fonts\n },\n execute: (figma, args) => {\n const kinds = REPLACEMENT_KINDS.filter((kind) => args[kind] !== undefined)\n if (kinds.length === 0) return { error: 'Name at least one property to replace' }\n const nodes = searchedNodes(figma, args)\n if (typeof nodes === 'string') return { error: nodes }\n const counts = mapValues(replacementInputs, () => 0)\n const changed = new Set<string>()\n const readOnly: string[] = []\n try {\n const swaps = {\n fill: colorSwaps(args.fill_color, figma.graph.documentColorSpace),\n text: colorSwaps(args.text_color, figma.graph.documentColorSpace),\n stroke: colorSwaps(args.stroke_color, figma.graph.documentColorSpace)\n }\n for (const node of nodes) {\n const paint = paintAndGeometryChanges(node, args, swaps)\n const edits = textEdits(node, args)\n if (!paint && edits.length === 0) continue\n // A library's components change in that library, so their layers are reported instead.\n if (!getNodeEditCapability(figma.graph, node.id).editable) {\n readOnly.push(node.id)\n continue\n }\n if (paint) {\n // As the node setters write, so styles detach and instances keep the change.\n editNode(figma.graph, node.id, paint.changes, figma.groupFitOptions)\n for (const kind of REPLACEMENT_KINDS) counts[kind] += paint.counts[kind] ?? 0\n }\n if (edits.length > 0) changeText(figma, node, edits, counts)\n changed.add(node.id)\n }\n } catch (error) {\n return toolFailure(error)\n }\n return {\n replaced: pick(counts, kinds),\n changed: changed.size,\n ids: [...changed],\n ...(readOnly.length > 0 ? { read_only: readOnly } : {})\n }\n }\n})\n\ntype Counts = Record<ReplacementKind, number>\n\n/** What one layer's paints, stroke weight, and corners change to, with the values it changes. */\nfunction paintAndGeometryChanges(\n node: SceneNode,\n replacements: Replacements,\n swaps: { fill: ColorSwap[]; text: ColorSwap[]; stroke: ColorSwap[] }\n): { changes: Partial<SceneNode>; counts: Partial<Counts> } | null {\n const changes: Partial<SceneNode> = {}\n const counts: Partial<Counts> = {}\n const count = (kind: ReplacementKind, amount = 1) => {\n counts[kind] = (counts[kind] ?? 0) + amount\n }\n const isText = node.type === 'TEXT'\n const fillSwaps = isText ? swaps.text : swaps.fill\n const fillKind = isText ? 'text_color' : 'fill_color'\n const bound = (kind: 'fills' | 'strokes') => (index: number) =>\n !!node.boundVariables[`${kind}/${index}/color`]\n if (fillSwaps.length > 0) {\n const fills = swapPaints(node.fills, fillSwaps, bound('fills'))\n if (fills) {\n changes.fills = fills\n count(fillKind, fills.filter((paint, index) => paint !== node.fills[index]).length)\n }\n if (isText) {\n let runs = 0\n const styleRuns = node.styleRuns.map((run) => {\n const runFills = run.style.fills && swapPaints(run.style.fills, fillSwaps, () => false)\n if (!runFills) return run\n runs++\n return { ...run, style: { ...run.style, fills: runFills } }\n })\n if (runs > 0) {\n changes.styleRuns = styleRuns\n count('text_color', runs)\n }\n }\n }\n if (swaps.stroke.length > 0) {\n const strokes = swapPaints(node.strokes, swaps.stroke, bound('strokes'))\n if (strokes) {\n changes.strokes = strokes\n count('stroke_color', strokes.filter((paint, index) => paint !== node.strokes[index]).length)\n }\n }\n const weight =\n node.strokes.length > 0 ? swapNumber(node.strokeWeight, replacements.stroke_weight) : null\n if (weight !== null) {\n // Each stroke draws at its own weight, so they all take it, as the strokeWeight setter does.\n changes.strokeWeight = weight\n changes.strokes = (changes.strokes ?? node.strokes).map((stroke) => ({\n ...copyStroke(stroke),\n weight\n }))\n count('stroke_weight')\n }\n if (replacements.corner_radius && ROUNDED_TYPES.has(node.type)) {\n Object.assign(changes, cornerChanges(node, replacements.corner_radius, count))\n }\n return Object.keys(changes).length > 0 ? { changes, counts } : null\n}\n\n/**\n * The corner radii `swaps` give a layer. Corners set together draw `cornerRadius`, whatever the\n * corner fields hold, so only corners set one by one are matched each on its own.\n */\nfunction cornerChanges(\n node: SceneNode,\n swaps: readonly NumberPair[],\n count: (kind: ReplacementKind) => void\n): Partial<SceneNode> {\n if (!node.independentCorners) {\n const radius = swapNumber(node.cornerRadius, swaps)\n if (radius === null) return {}\n count('corner_radius')\n return {\n cornerRadius: radius,\n ...Object.fromEntries(CORNERS.map((corner) => [corner, radius])),\n independentCorners: false\n }\n }\n const changes: Partial<SceneNode> = {}\n for (const corner of CORNERS) {\n const radius = swapNumber(node[corner], swaps)\n if (radius === null) continue\n changes[corner] = radius\n count('corner_radius')\n }\n const radii = CORNERS.map((corner) => changes[corner] ?? node[corner])\n if (radii.every((radius, index) => radius === node[CORNERS[index]])) return {}\n const uniform = radii.every((radius) => radius === radii[0])\n changes.cornerRadius = uniform ? radii[0] : node.cornerRadius\n changes.independentCorners = !uniform\n return changes\n}\n\nfunction changeText(\n figma: FigmaAPI,\n node: SceneNode,\n edits: readonly TextEdit[],\n counts: Record<ReplacementKind, number>\n): void {\n const text = figma.getNodeById(node.id)\n if (!text) return\n for (const edit of edits) {\n // A range over all of the text sets the text's own font, as set_font does, not a style run.\n const ranged = edit.start > 0 || edit.end < node.text.length\n if (edit.fontName) {\n if (ranged) text.setRangeFontName(edit.start, edit.end, edit.fontName)\n else text.fontName = edit.fontName\n }\n // The size comes after the font, so it lays the text out in the font it ends up in.\n if (edit.fontSize !== undefined) {\n if (ranged) text.setRangeFontSize(edit.start, edit.end, edit.fontSize)\n else text.fontSize = edit.fontSize\n counts.font_size++\n }\n if (edit.family) counts.font_family++\n if (edit.style) counts.font_style++\n }\n}\n"],"mappings":";;;;;;;;;;AAiBA,MAAM,kBAAkB,EAAE,aAAa;CACrC,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,oDAAoD,CAAC;CAC5F,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,qDAAqD,CAAC;AAC7F,CAAC;AACD,MAAM,mBAAmB,EAAE,aAAa;CACtC,MAAM,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,CAAC;CACnE,IAAI,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,YAAY,sBAAsB,CAAC,CAAC;AACzF,CAAC;AACD,MAAM,iBAAiB,EAAE,aAAa;CACpC,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,SAAS,GAAG,EAAE,YAAY,kCAAkC,CAAC;CACxF,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,SAAS,GAAG,EAAE,YAAY,sBAAsB,CAAC;AAC5E,CAAC;AACD,MAAM,iBAAiB,EAAE,OAAO;CAAE,QAAQ,EAAE,OAAO;CAAG,OAAO,EAAE,OAAO;AAAE,CAAC;AAEzE,MAAM,SAAoC,QAAW,gBACnD,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,MAAM,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,YAAY,WAAW,CAAC,CAAC;AAEhF,MAAM,oBAAoB;CACxB,YAAY,MAAM,iBAAiB,6CAA6C;CAChF,YAAY,MAAM,iBAAiB,uCAAuC;CAC1E,cAAc,MAAM,iBAAiB,qBAAqB;CAC1D,eAAe,MAAM,kBAAkB,4CAA4C;CACnF,eAAe,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version":3,"file":"paint.d.ts","names":[],"sources":["../../../src/tools/modify/paint.ts"],"mappings":";;cAwBa,SAAA;cAoEA,WAAA;cA8BA,cAAA"}
1
+ {"version":3,"file":"paint.d.ts","names":[],"sources":["../../../src/tools/modify/paint.ts"],"mappings":";;cA2Da,SAAA;cAiHA,WAAA;cA8BA,cAAA"}
@@ -1,5 +1,6 @@
1
- import { storeImage } from "../../figma-api/images.js";
2
1
  import { defineTool, nodeIdInputSchema, parseToolColor, toolFailure, toolNumber } from "../schema.js";
2
+ import { storeImage } from "../../figma-api/images.js";
3
+ import { PairdrawAPI } from "../../pairdraw-api/index.js";
3
4
  import { isValid, toUint8Array } from "js-base64";
4
5
  import { gradientTransformRows, linearGradientTransform } from "@pairdraw/scene-graph/gradient";
5
6
  import * as v from "valibot";
@@ -17,9 +18,33 @@ const STRETCH_IMAGE_TRANSFORM = [[
17
18
  1,
18
19
  0
19
20
  ]];
21
+ /**
22
+ * `var(--color/brand)` or `var(--color/brand, #4F46E5)`: a token by name, as `get_css` writes it.
23
+ * The fallback runs to the last `)`, since a Display P3 document writes one as `color(display-p3 …)`.
24
+ */
25
+ const COLOR_TOKEN = /^var\(\s*--([^,()]+?)\s*(?:,(.*))?\)$/;
26
+ function colorVariablesNamed(figma, name) {
27
+ const matches = [];
28
+ for (const variable of figma.graph.variables.values()) if (variable.type === "COLOR" && variable.name === name) matches.push(variable);
29
+ return matches;
30
+ }
31
+ /** A colour, as opposed to a token alias or an expression a variable may hold instead. */
32
+ function isColor(value) {
33
+ return typeof value === "object" && "r" in value && "g" in value && "b" in value && "a" in value;
34
+ }
35
+ /** The colour a token holds in its default mode, and its collection, for a fill to take. */
36
+ function tokenColor(figma, variable) {
37
+ const collection = figma.graph.variableCollections.get(variable.collectionId);
38
+ const value = collection ? variable.valuesByMode[collection.defaultModeId] : Object.values(variable.valuesByMode)[0];
39
+ if (!isColor(value)) return { error: `Variable "${variable.name}" holds no colour` };
40
+ return {
41
+ color: value,
42
+ collection
43
+ };
44
+ }
20
45
  const setFill = defineTool({
21
46
  name: "set_fill",
22
- description: "Set fill on a node. Solid: color=\"#ff0000\". Linear gradient: gradient=\"top-bottom\" or \"left-right\" with color (start) and color_end (end).",
47
+ description: "Set fill on a node. Solid: color=\"#ff0000\". A token by name: color=\"var(--color/brand)\" paints its colour and binds the fill. Linear gradient: gradient=\"top-bottom\" or \"left-right\" with color (start) and color_end (end); gradient stops take hex colours, not tokens.",
23
48
  execution: {
24
49
  kind: "sync",
25
50
  mutation: "properties"
@@ -38,10 +63,37 @@ const setFill = defineTool({
38
63
  execute: (figma, { id, color, color_end, gradient }) => {
39
64
  const node = figma.getNodeById(id);
40
65
  if (!node) return { error: `Node "${id}" not found` };
41
- const c = parseToolColor(color);
66
+ const token = COLOR_TOKEN.exec(color);
67
+ const endToken = color_end === void 0 ? null : COLOR_TOKEN.exec(color_end);
68
+ if (gradient && (token !== null || endToken !== null)) return { error: `A gradient cannot take the token ${[token === null ? void 0 : `"${token[1]}"`, endToken === null ? void 0 : `"${endToken[1]}"`].filter((entry) => entry !== void 0).join(" and ")}: gradient stops have no variable binding. Pass hex colours for a gradient, or a token only for a solid fill.` };
69
+ const name = token === null ? null : token[1];
70
+ if (name !== null) {
71
+ const matches = colorVariablesNamed(figma, name);
72
+ if (matches.length === 0) return { error: `No COLOR variable named "${name}". Call find_variables to list the document's tokens.` };
73
+ if (matches.length > 1) {
74
+ const where = matches.map((variable) => figma.graph.variableCollections.get(variable.collectionId)?.name ?? variable.collectionId).join(", ");
75
+ return { error: `${matches.length} variables named "${name}" (${where}); bind one with bind_variable.` };
76
+ }
77
+ for (const variable of matches) {
78
+ const resolved = tokenColor(figma, variable);
79
+ if ("error" in resolved) return resolved;
80
+ node.fills = [{
81
+ type: "SOLID",
82
+ color: resolved.color
83
+ }];
84
+ new PairdrawAPI(figma).bindVariable(node.id, "fills/0/color", variable);
85
+ return {
86
+ id,
87
+ color: resolved.color,
88
+ bound: name
89
+ };
90
+ }
91
+ return { error: `No COLOR variable named "${name}"` };
92
+ }
93
+ const c = parseToolColor(color, figma.graph.documentColorSpace);
42
94
  if ("error" in c) return c;
43
95
  if (gradient && color_end) {
44
- const cEnd = parseToolColor(color_end);
96
+ const cEnd = parseToolColor(color_end, figma.graph.documentColorSpace);
45
97
  if ("error" in cEnd) return cEnd;
46
98
  const ends = {
47
99
  "top-bottom": [{
@@ -122,7 +174,7 @@ const setStroke = defineTool({
122
174
  execute: (figma, { id, color, weight, align }) => {
123
175
  const node = figma.getNodeById(id);
124
176
  if (!node) return { error: `Node "${id}" not found` };
125
- const c = parseToolColor(color);
177
+ const c = parseToolColor(color, figma.graph.documentColorSpace);
126
178
  if ("error" in c) return c;
127
179
  node.strokes = [{
128
180
  type: "SOLID",
@@ -1 +1 @@
1
- {"version":3,"file":"paint.js","names":[],"sources":["../../../src/tools/modify/paint.ts"],"sourcesContent":["import { isValid, toUint8Array } from 'js-base64'\nimport * as v from 'valibot'\n\nimport { gradientTransformRows, linearGradientTransform } from '@pairdraw/scene-graph/gradient'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { storeImage } from '#core/figma-api/images'\nimport {\n defineTool,\n nodeIdInputSchema,\n parseToolColor,\n toolFailure,\n toolNumber\n} from '#core/tools/schema'\n\n/**\n * Stretch as Figma's API writes it: a crop whose window is the whole image, which the image fill\n * panel's Stretch and `.pen`'s `stretch` also store.\n */\nconst STRETCH_IMAGE_TRANSFORM: [[number, number, number], [number, number, number]] = [\n [1, 0, 0],\n [0, 1, 0]\n]\n\nexport const setFill = defineTool({\n name: 'set_fill',\n\n description:\n 'Set fill on a node. Solid: color=\"#ff0000\". Linear gradient: gradient=\"top-bottom\" or \"left-right\" with color (start) and color_end (end).',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n color: v.pipe(v.string(), v.description('Color (hex). For gradient: start color.')),\n color_end: v.optional(\n v.pipe(v.string(), v.description('End color for gradient (if omitted, solid fill)'))\n ),\n gradient: v.optional(\n v.pipe(\n v.picklist(['top-bottom', 'bottom-top', 'left-right', 'right-left']),\n v.description('Gradient direction')\n )\n )\n }),\n execute: (figma, { id, color, color_end, gradient }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n\n const c = parseToolColor(color)\n if ('error' in c) return c\n\n if (gradient && color_end) {\n const cEnd = parseToolColor(color_end)\n if ('error' in cEnd) return cEnd\n // Edge middles of the layer's unit square that each direction runs between.\n const ends: Record<string, [Vector, Vector]> = {\n 'top-bottom': [\n { x: 0.5, y: 0 },\n { x: 0.5, y: 1 }\n ],\n 'bottom-top': [\n { x: 0.5, y: 1 },\n { x: 0.5, y: 0 }\n ],\n 'left-right': [\n { x: 0, y: 0.5 },\n { x: 1, y: 0.5 }\n ],\n 'right-left': [\n { x: 1, y: 0.5 },\n { x: 0, y: 0.5 }\n ]\n }\n const [start, end] = ends[gradient] ?? ends['top-bottom']\n node.fills = [\n {\n type: 'GRADIENT_LINEAR',\n gradientStops: [\n { position: 0, color: c },\n { position: 1, color: cEnd }\n ],\n gradientTransform: gradientTransformRows(linearGradientTransform(start, end))\n }\n ]\n return { id, gradient, start: c, end: cEnd }\n }\n\n // A colour's alpha becomes the paint's opacity, as Figma takes it.\n node.fills = [{ type: 'SOLID', color: c }]\n return { id, color: c }\n }\n})\n\nexport const setStroke = defineTool({\n name: 'set_stroke',\n\n description: 'Set the stroke (border) of a node.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n color: v.pipe(v.string(), v.description('Stroke color (hex)')),\n weight: v.optional(\n toolNumber(v.pipe(v.number(), v.minValue(0.1), v.description('Stroke weight'))),\n 1\n ),\n align: v.optional(\n v.pipe(v.picklist(['INSIDE', 'CENTER', 'OUTSIDE']), v.description('Stroke alignment')),\n 'INSIDE'\n )\n }),\n execute: (figma, { id, color, weight, align }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n\n const c = parseToolColor(color)\n if ('error' in c) return c\n node.strokes = [{ type: 'SOLID', color: c }]\n node.strokeWeight = weight\n node.strokeAlign = align\n return { id, color: c, weight: weight }\n }\n})\n\nexport const setImageFill = defineTool({\n name: 'set_image_fill',\n\n description:\n 'Set an image fill on a node from base64-encoded image data or an image URL (http, https, or data). A URL is fetched as figma.createImageAsync fetches it, up to 64 MB.',\n execution: { kind: 'async', mutation: 'document' },\n capabilities: ['document:write', 'network:access'],\n input: v.strictObject({\n id: nodeIdInputSchema,\n image_data: v.optional(\n v.pipe(v.string(), v.description('Base64-encoded image bytes (PNG, JPEG, or WEBP)'))\n ),\n url: v.optional(\n v.pipe(\n v.string(),\n v.nonEmpty(),\n v.description('Image URL to fetch (http, https, or data), instead of image_data')\n )\n ),\n scale_mode: v.optional(\n v.pipe(\n v.picklist(['FILL', 'FIT', 'CROP', 'TILE', 'STRETCH']),\n v.description(\n 'Image scale mode. STRETCH stretches the whole image to the layer, ignoring its aspect ratio, as the Stretch mode of the image fill panel does.'\n )\n ),\n 'FILL'\n )\n }),\n execute: async (figma, { id, image_data, url, scale_mode }) => {\n if (!figma.getNodeById(id)) return { error: `Node \"${id}\" not found` }\n if ((image_data === undefined) === (url === undefined)) {\n return { error: 'Provide either image_data or url' }\n }\n let imageHash: string\n if (url !== undefined) {\n try {\n imageHash = (await figma.createImageAsync(url)).hash\n } catch (error) {\n return toolFailure(error)\n }\n } else {\n if (!image_data || !isValid(image_data)) return { error: 'image_data is not valid Base64' }\n imageHash = storeImage(figma.graph, toUint8Array(image_data))\n }\n // The fetch may outlast the node: another edit can remove it meanwhile.\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n node.fills = [\n scale_mode === 'STRETCH'\n ? { type: 'IMAGE', imageHash, scaleMode: 'CROP', imageTransform: STRETCH_IMAGE_TRANSFORM }\n : { type: 'IMAGE', imageHash, scaleMode: scale_mode }\n ]\n return { id, imageHash, scaleMode: scale_mode }\n }\n})\n"],"mappings":";;;;;;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/tools/modify/paint.ts"],"sourcesContent":["import { isValid, toUint8Array } from 'js-base64'\nimport * as v from 'valibot'\n\nimport type { Variable, VariableCollection, VariableValue } from '@pairdraw/scene-graph'\nimport { gradientTransformRows, linearGradientTransform } from '@pairdraw/scene-graph/gradient'\nimport type { Color, Vector } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaAPI } from '#core/figma-api'\nimport { storeImage } from '#core/figma-api/images'\nimport { PairdrawAPI } from '#core/pairdraw-api'\nimport {\n defineTool,\n nodeIdInputSchema,\n parseToolColor,\n toolFailure,\n toolNumber\n} from '#core/tools/schema'\n\n/**\n * Stretch as Figma's API writes it: a crop whose window is the whole image, which the image fill\n * panel's Stretch and `.pen`'s `stretch` also store.\n */\nconst STRETCH_IMAGE_TRANSFORM: [[number, number, number], [number, number, number]] = [\n [1, 0, 0],\n [0, 1, 0]\n]\n\n/**\n * `var(--color/brand)` or `var(--color/brand, #4F46E5)`: a token by name, as `get_css` writes it.\n * The fallback runs to the last `)`, since a Display P3 document writes one as `color(display-p3 …)`.\n */\nconst COLOR_TOKEN = /^var\\(\\s*--([^,()]+?)\\s*(?:,(.*))?\\)$/\n\nfunction colorVariablesNamed(figma: FigmaAPI, name: string): Variable[] {\n const matches: Variable[] = []\n for (const variable of figma.graph.variables.values()) {\n if (variable.type === 'COLOR' && variable.name === name) matches.push(variable)\n }\n return matches\n}\n\n/** A colour, as opposed to a token alias or an expression a variable may hold instead. */\nfunction isColor(value: VariableValue | undefined): value is Color {\n return typeof value === 'object' && 'r' in value && 'g' in value && 'b' in value && 'a' in value\n}\n\n/** The colour a token holds in its default mode, and its collection, for a fill to take. */\nfunction tokenColor(\n figma: FigmaAPI,\n variable: Variable\n): { color: Color; collection: VariableCollection | undefined } | { error: string } {\n const collection = figma.graph.variableCollections.get(variable.collectionId)\n const value = collection\n ? variable.valuesByMode[collection.defaultModeId]\n : Object.values(variable.valuesByMode)[0]\n if (!isColor(value)) return { error: `Variable \"${variable.name}\" holds no colour` }\n return { color: value, collection }\n}\n\nexport const setFill = defineTool({\n name: 'set_fill',\n\n description:\n 'Set fill on a node. Solid: color=\"#ff0000\". A token by name: color=\"var(--color/brand)\" paints its colour and binds the fill. Linear gradient: gradient=\"top-bottom\" or \"left-right\" with color (start) and color_end (end); gradient stops take hex colours, not tokens.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n color: v.pipe(v.string(), v.description('Color (hex). For gradient: start color.')),\n color_end: v.optional(\n v.pipe(v.string(), v.description('End color for gradient (if omitted, solid fill)'))\n ),\n gradient: v.optional(\n v.pipe(\n v.picklist(['top-bottom', 'bottom-top', 'left-right', 'right-left']),\n v.description('Gradient direction')\n )\n )\n }),\n execute: (figma, { id, color, color_end, gradient }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n\n // A token name paints the colour it holds and binds the fill, so the layer follows the token.\n const token = COLOR_TOKEN.exec(color)\n const endToken = color_end === undefined ? null : COLOR_TOKEN.exec(color_end)\n // Gradient stops carry no variable binding, so a token there would paint the wrong thing.\n if (gradient && (token !== null || endToken !== null)) {\n const named = [\n token === null ? undefined : `\"${token[1]}\"`,\n endToken === null ? undefined : `\"${endToken[1]}\"`\n ]\n .filter((entry) => entry !== undefined)\n .join(' and ')\n return {\n error: `A gradient cannot take the token ${named}: gradient stops have no variable binding. Pass hex colours for a gradient, or a token only for a solid fill.`\n }\n }\n const name = token === null ? null : token[1]\n if (name !== null) {\n const matches = colorVariablesNamed(figma, name)\n if (matches.length === 0) {\n return {\n error: `No COLOR variable named \"${name}\". Call find_variables to list the document's tokens.`\n }\n }\n if (matches.length > 1) {\n const where = matches\n .map(\n (variable) =>\n figma.graph.variableCollections.get(variable.collectionId)?.name ??\n variable.collectionId\n )\n .join(', ')\n return {\n error: `${matches.length} variables named \"${name}\" (${where}); bind one with bind_variable.`\n }\n }\n for (const variable of matches) {\n const resolved = tokenColor(figma, variable)\n if ('error' in resolved) return resolved\n node.fills = [{ type: 'SOLID', color: resolved.color }]\n new PairdrawAPI(figma).bindVariable(node.id, 'fills/0/color', variable)\n return { id, color: resolved.color, bound: name }\n }\n return { error: `No COLOR variable named \"${name}\"` }\n }\n\n const c = parseToolColor(color, figma.graph.documentColorSpace)\n if ('error' in c) return c\n\n if (gradient && color_end) {\n const cEnd = parseToolColor(color_end, figma.graph.documentColorSpace)\n if ('error' in cEnd) return cEnd\n // Edge middles of the layer's unit square that each direction runs between.\n const ends: Record<string, [Vector, Vector]> = {\n 'top-bottom': [\n { x: 0.5, y: 0 },\n { x: 0.5, y: 1 }\n ],\n 'bottom-top': [\n { x: 0.5, y: 1 },\n { x: 0.5, y: 0 }\n ],\n 'left-right': [\n { x: 0, y: 0.5 },\n { x: 1, y: 0.5 }\n ],\n 'right-left': [\n { x: 1, y: 0.5 },\n { x: 0, y: 0.5 }\n ]\n }\n const [start, end] = ends[gradient] ?? ends['top-bottom']\n node.fills = [\n {\n type: 'GRADIENT_LINEAR',\n gradientStops: [\n { position: 0, color: c },\n { position: 1, color: cEnd }\n ],\n gradientTransform: gradientTransformRows(linearGradientTransform(start, end))\n }\n ]\n return { id, gradient, start: c, end: cEnd }\n }\n\n // A colour's alpha becomes the paint's opacity, as Figma takes it.\n node.fills = [{ type: 'SOLID', color: c }]\n return { id, color: c }\n }\n})\n\nexport const setStroke = defineTool({\n name: 'set_stroke',\n\n description: 'Set the stroke (border) of a node.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n color: v.pipe(v.string(), v.description('Stroke color (hex)')),\n weight: v.optional(\n toolNumber(v.pipe(v.number(), v.minValue(0.1), v.description('Stroke weight'))),\n 1\n ),\n align: v.optional(\n v.pipe(v.picklist(['INSIDE', 'CENTER', 'OUTSIDE']), v.description('Stroke alignment')),\n 'INSIDE'\n )\n }),\n execute: (figma, { id, color, weight, align }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n\n const c = parseToolColor(color, figma.graph.documentColorSpace)\n if ('error' in c) return c\n node.strokes = [{ type: 'SOLID', color: c }]\n node.strokeWeight = weight\n node.strokeAlign = align\n return { id, color: c, weight: weight }\n }\n})\n\nexport const setImageFill = defineTool({\n name: 'set_image_fill',\n\n description:\n 'Set an image fill on a node from base64-encoded image data or an image URL (http, https, or data). A URL is fetched as figma.createImageAsync fetches it, up to 64 MB.',\n execution: { kind: 'async', mutation: 'document' },\n capabilities: ['document:write', 'network:access'],\n input: v.strictObject({\n id: nodeIdInputSchema,\n image_data: v.optional(\n v.pipe(v.string(), v.description('Base64-encoded image bytes (PNG, JPEG, or WEBP)'))\n ),\n url: v.optional(\n v.pipe(\n v.string(),\n v.nonEmpty(),\n v.description('Image URL to fetch (http, https, or data), instead of image_data')\n )\n ),\n scale_mode: v.optional(\n v.pipe(\n v.picklist(['FILL', 'FIT', 'CROP', 'TILE', 'STRETCH']),\n v.description(\n 'Image scale mode. STRETCH stretches the whole image to the layer, ignoring its aspect ratio, as the Stretch mode of the image fill panel does.'\n )\n ),\n 'FILL'\n )\n }),\n execute: async (figma, { id, image_data, url, scale_mode }) => {\n if (!figma.getNodeById(id)) return { error: `Node \"${id}\" not found` }\n if ((image_data === undefined) === (url === undefined)) {\n return { error: 'Provide either image_data or url' }\n }\n let imageHash: string\n if (url !== undefined) {\n try {\n imageHash = (await figma.createImageAsync(url)).hash\n } catch (error) {\n return toolFailure(error)\n }\n } else {\n if (!image_data || !isValid(image_data)) return { error: 'image_data is not valid Base64' }\n imageHash = storeImage(figma.graph, toUint8Array(image_data))\n }\n // The fetch may outlast the node: another edit can remove it meanwhile.\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n node.fills = [\n scale_mode === 'STRETCH'\n ? { type: 'IMAGE', imageHash, scaleMode: 'CROP', imageTransform: STRETCH_IMAGE_TRANSFORM }\n : { type: 'IMAGE', imageHash, scaleMode: scale_mode }\n ]\n return { id, imageHash, scaleMode: scale_mode }\n }\n})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Q,KAAA,GACV,IAAI;GACF,aAAa,MAAM,MAAM,iBAAiB,GAAG,EAAA,CAAG;EAClD,SAAS,OAAO;GACd,OAAO,YAAY,KAAK;EAC1B;OACK;GACL,IAAI,CAAC,cAAc,CAAC,QAAQ,UAAU,GAAG,OAAO,EAAE,OAAO,iCAAiC;GAC1F,YAAY,WAAW,MAAM,OAAO,aAAa,UAAU,CAAC;EAC9D;EAEA,MAAM,OAAO,MAAM,YAAY,EAAE;EACjC,IAAI,CAAC,MAAM,OAAO,EAAE,OAAO,SAAS,GAAG,aAAa;EACpD,KAAK,QAAQ,CACX,eAAe,YACX;GAAE,MAAM;GAAS;GAAW,WAAW;GAAQ,gBAAgB;EAAwB,IACvF;GAAE,MAAM;GAAS;GAAW,WAAW;EAAW,CACxD;EACA,OAAO;GAAE;GAAI;GAAW,WAAW;EAAW;CAChD;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"reactions.d.ts","names":[],"sources":["../../../src/tools/modify/reactions.ts"],"mappings":";;cAwBa,cAAA"}
1
+ {"version":3,"file":"reactions.d.ts","names":[],"sources":["../../../src/tools/modify/reactions.ts"],"mappings":";;cAyBa,cAAA"}
@@ -1,9 +1,9 @@
1
- import { figmaReactionsSchema } from "../../figma-api/reactions.js";
2
1
  import { defineTool, nodeIdInputSchema, nodeNotFound, toolFailure } from "../schema.js";
2
+ import { figmaReactionsSchema } from "../../figma-api/reactions.js";
3
3
  import * as v from "valibot";
4
4
  //#region src/tools/modify/reactions.ts
5
5
  /** Connections in Figma's plugin shape, which the layer's `reactions` reads and writes. */
6
- const reactionsInputSchema = v.pipe(figmaReactionsSchema, v.description("Prototype connections in Figma's plugin shape: [{ trigger: { type: 'ON_CLICK' | 'ON_HOVER' | 'ON_PRESS' } | { type: 'MOUSE_ENTER' | 'MOUSE_LEAVE', delay?: seconds } | { type: 'AFTER_TIMEOUT', timeout: seconds }, actions: [{ type: 'NODE', destinationId, navigation: 'NAVIGATE' | 'OVERLAY' | 'CHANGE_TO' | 'SCROLL_TO', transition: { type: 'INSTANT' | 'DISSOLVE' | 'SMART_ANIMATE', duration: seconds, easing?: { type: 'EASE_OUT' | 'EASE_IN' | 'EASE_IN_AND_OUT' | 'LINEAR' } }, overlayRelativePosition?: 'CENTER' | ... } | { type: 'BACK' } | { type: 'CLOSE' }] }]. NAVIGATE and OVERLAY point at a top-level frame on the same page; CHANGE_TO at another variant of the set the layer is a variant of, an instance of, or inside (set it once on the main component variant and every instance gets it); SCROLL_TO at a layer in the layer's top-level frame. ON_HOVER and ON_PRESS undo their action when the pointer leaves or lifts. SMART_ANIMATE moves the layers two frames or variants share by name and place, and fades the rest; easing defaults to EASE_OUT."));
6
+ const reactionsInputSchema = v.pipe(figmaReactionsSchema, v.description("Prototype connections in Figma's plugin shape: [{ trigger: { type: 'ON_CLICK' | 'ON_HOVER' | 'ON_PRESS' } | { type: 'MOUSE_ENTER' | 'MOUSE_LEAVE', delay?: seconds } | { type: 'AFTER_TIMEOUT', timeout: seconds }, actions: [{ type: 'NODE', destinationId, navigation: 'NAVIGATE' | 'OVERLAY' | 'CHANGE_TO' | 'SCROLL_TO', transition: { type: 'INSTANT' | 'DISSOLVE' | 'SMART_ANIMATE', duration: seconds, easing?: { type: 'EASE_OUT' | 'EASE_IN' | 'EASE_IN_AND_OUT' | 'LINEAR' } }, overlayRelativePosition?: 'CENTER' | ... } | { type: 'BACK' } | { type: 'CLOSE' }] }]. NAVIGATE and OVERLAY point at a top-level frame on the same page; CHANGE_TO at another variant of the set the layer is a variant of, an instance of, or inside (set it once on the main component variant and every instance gets it), named by destinationId or by variantProperties such as { State: \"Hover\" }; SCROLL_TO at a layer in the layer's top-level frame. ON_HOVER and ON_PRESS undo their action when the pointer leaves or lifts. SMART_ANIMATE moves the layers two frames or variants share by name and place, and fades the rest; easing defaults to EASE_OUT."));
7
7
  const setReactions = defineTool({
8
8
  name: "set_reactions",
9
9
  description: "Replace the prototype connections on a layer. Use get_reactions to read them back. Refuses a trigger, action, transition, navigation or destination the prototype play cannot run. Set overflow scrolling with update_node overflow_direction.",
@@ -1 +1 @@
1
- {"version":3,"file":"reactions.js","names":[],"sources":["../../../src/tools/modify/reactions.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { figmaReactionsSchema } from '#core/figma-api/reactions'\nimport { defineTool, nodeIdInputSchema, nodeNotFound, toolFailure } from '#core/tools/schema'\n\n/** Connections in Figma's plugin shape, which the layer's `reactions` reads and writes. */\nconst reactionsInputSchema = v.pipe(\n figmaReactionsSchema,\n v.description(\n \"Prototype connections in Figma's plugin shape: [{ trigger: { type: 'ON_CLICK' | \" +\n \"'ON_HOVER' | 'ON_PRESS' } | { type: 'MOUSE_ENTER' | 'MOUSE_LEAVE', delay?: seconds } | \" +\n \"{ type: 'AFTER_TIMEOUT', timeout: seconds }, actions: [{ type: 'NODE', destinationId, \" +\n \"navigation: 'NAVIGATE' | 'OVERLAY' | 'CHANGE_TO' | 'SCROLL_TO', transition: { type: \" +\n \"'INSTANT' | 'DISSOLVE' | 'SMART_ANIMATE', duration: seconds, easing?: { type: 'EASE_OUT' | \" +\n \"'EASE_IN' | 'EASE_IN_AND_OUT' | 'LINEAR' } }, overlayRelativePosition?: 'CENTER' | ... } | \" +\n \"{ type: 'BACK' } | { type: 'CLOSE' }] }]. NAVIGATE and OVERLAY point at a top-level frame \" +\n 'on the same page; CHANGE_TO at another variant of the set the layer is a variant of, an ' +\n 'instance of, or inside (set it once on the main component variant and every instance ' +\n \"gets it); SCROLL_TO at a layer in the layer's top-level frame. ON_HOVER and ON_PRESS undo \" +\n 'their action when the pointer leaves or lifts. SMART_ANIMATE moves the layers two frames or ' +\n 'variants share by name and place, and fades the rest; easing defaults to EASE_OUT.'\n )\n)\n\nexport const setReactions = defineTool({\n name: 'set_reactions',\n\n description:\n 'Replace the prototype connections on a layer. Use get_reactions to read them back. ' +\n 'Refuses a trigger, action, transition, navigation or destination the prototype play ' +\n 'cannot run. Set overflow scrolling with update_node overflow_direction.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n reactions: reactionsInputSchema\n }),\n execute: (figma, { id, reactions }) => {\n const node = figma.getNodeById(id)\n if (!node) return nodeNotFound(id)\n try {\n node.reactions = reactions\n } catch (error) {\n return toolFailure(error)\n }\n return { id, reactions: node.reactions }\n }\n})\n"],"mappings":";;;;;AAMA,MAAM,uBAAuB,EAAE,KAC7B,sBACA,EAAE,YACA,whCAYF,CACF;AAEA,MAAa,eAAe,WAAW;CACrC,MAAM;CAEN,aACE;CAGF,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAa;CAClD,OAAO,EAAE,aAAa;EACpB,IAAI;EACJ,WAAW;CACb,CAAC;CACD,UAAU,OAAO,EAAE,IAAI,gBAAgB;EACrC,MAAM,OAAO,MAAM,YAAY,EAAE;EACjC,IAAI,CAAC,MAAM,OAAO,aAAa,EAAE;EACjC,IAAI;GACF,KAAK,YAAY;EACnB,SAAS,OAAO;GACd,OAAO,YAAY,KAAK;EAC1B;EACA,OAAO;GAAE;GAAI,WAAW,KAAK;EAAU;CACzC;AACF,CAAC"}
1
+ {"version":3,"file":"reactions.js","names":[],"sources":["../../../src/tools/modify/reactions.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { figmaReactionsSchema } from '#core/figma-api/reactions'\nimport { defineTool, nodeIdInputSchema, nodeNotFound, toolFailure } from '#core/tools/schema'\n\n/** Connections in Figma's plugin shape, which the layer's `reactions` reads and writes. */\nconst reactionsInputSchema = v.pipe(\n figmaReactionsSchema,\n v.description(\n \"Prototype connections in Figma's plugin shape: [{ trigger: { type: 'ON_CLICK' | \" +\n \"'ON_HOVER' | 'ON_PRESS' } | { type: 'MOUSE_ENTER' | 'MOUSE_LEAVE', delay?: seconds } | \" +\n \"{ type: 'AFTER_TIMEOUT', timeout: seconds }, actions: [{ type: 'NODE', destinationId, \" +\n \"navigation: 'NAVIGATE' | 'OVERLAY' | 'CHANGE_TO' | 'SCROLL_TO', transition: { type: \" +\n \"'INSTANT' | 'DISSOLVE' | 'SMART_ANIMATE', duration: seconds, easing?: { type: 'EASE_OUT' | \" +\n \"'EASE_IN' | 'EASE_IN_AND_OUT' | 'LINEAR' } }, overlayRelativePosition?: 'CENTER' | ... } | \" +\n \"{ type: 'BACK' } | { type: 'CLOSE' }] }]. NAVIGATE and OVERLAY point at a top-level frame \" +\n 'on the same page; CHANGE_TO at another variant of the set the layer is a variant of, an ' +\n 'instance of, or inside (set it once on the main component variant and every instance gets ' +\n 'it), named by destinationId or by variantProperties such as { State: \"Hover\" }; SCROLL_TO ' +\n \"at a layer in the layer's top-level frame. ON_HOVER and ON_PRESS undo \" +\n 'their action when the pointer leaves or lifts. SMART_ANIMATE moves the layers two frames or ' +\n 'variants share by name and place, and fades the rest; easing defaults to EASE_OUT.'\n )\n)\n\nexport const setReactions = defineTool({\n name: 'set_reactions',\n\n description:\n 'Replace the prototype connections on a layer. Use get_reactions to read them back. ' +\n 'Refuses a trigger, action, transition, navigation or destination the prototype play ' +\n 'cannot run. Set overflow scrolling with update_node overflow_direction.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n reactions: reactionsInputSchema\n }),\n execute: (figma, { id, reactions }) => {\n const node = figma.getNodeById(id)\n if (!node) return nodeNotFound(id)\n try {\n node.reactions = reactions\n } catch (error) {\n return toolFailure(error)\n }\n return { id, reactions: node.reactions }\n }\n})\n"],"mappings":";;;;;AAMA,MAAM,uBAAuB,EAAE,KAC7B,sBACA,EAAE,YACA,qmCAaF,CACF;AAEA,MAAa,eAAe,WAAW;CACrC,MAAM;CAEN,aACE;CAGF,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAa;CAClD,OAAO,EAAE,aAAa;EACpB,IAAI;EACJ,WAAW;CACb,CAAC;CACD,UAAU,OAAO,EAAE,IAAI,gBAAgB;EACrC,MAAM,OAAO,MAAM,YAAY,EAAE;EACjC,IAAI,CAAC,MAAM,OAAO,aAAa,EAAE;EACjC,IAAI;GACF,KAAK,YAAY;EACnB,SAAS,OAAO;GACd,OAAO,YAAY,KAAK;EAC1B;EACA,OAAO;GAAE;GAAI,WAAW,KAAK;EAAU;CACzC;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"text.d.ts","names":[],"sources":["../../../src/tools/modify/text.ts"],"mappings":";;;;;iBAqEgB,UAAU,OAAO,UAAU,aAAa;cAK3C,SAAA;cAyFA,SAAA;cA4FA,cAAA;cA2DA,eAAA;cAqBA,mBAAA"}
1
+ {"version":3,"file":"text.d.ts","names":[],"sources":["../../../src/tools/modify/text.ts"],"mappings":";;;;;iBAsEgB,UAAU,OAAO,UAAU,aAAa;cAK3C,SAAA;cAyFA,SAAA;cA+FA,cAAA;cA2DA,eAAA;cAqBA,mBAAA"}
@@ -159,11 +159,11 @@ function badVariationTag(variations) {
159
159
  return tag === void 0 ? null : { error: `"${tag}" is not a four-letter OpenType axis tag` };
160
160
  }
161
161
  /** What a range edit sets, or why it cannot run: nothing named, a bad colour, or a bad link. */
162
- function rangeEdit(args) {
162
+ function rangeEdit(args, profile) {
163
163
  if (!args.family && !args.size && !args.style && !args.variations && !args.font_features && !args.color && args.hyperlink === void 0) return { error: "set_font_range needs at least one of family, size, style, variations, font_features, color, or hyperlink" };
164
164
  const hyperlink = requestedHyperlink(args.hyperlink);
165
165
  if (hyperlink && "error" in hyperlink) return hyperlink;
166
- const color = parseOptionalToolColor(args.color);
166
+ const color = parseOptionalToolColor(args.color, profile);
167
167
  if ("error" in color) return color;
168
168
  return {
169
169
  hyperlink: hyperlink ?? null,
@@ -204,7 +204,7 @@ const setFontRange = defineTool({
204
204
  if (badTag) return badTag;
205
205
  const badFeature = badFeatureEntry(args.font_features);
206
206
  if (badFeature) return badFeature;
207
- const edit = rangeEdit(args);
207
+ const edit = rangeEdit(args, figma.graph.documentColorSpace);
208
208
  if ("error" in edit) return edit;
209
209
  const { hyperlink, color } = edit;
210
210
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../../../src/tools/modify/text.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'\nimport type { FigmaFontName, FigmaFontNameInput } from '#core/figma-api/fonts/names'\nimport type { FigmaVariationSettings } from '#core/figma-api/fonts/variations'\nimport { PairdrawAPI } from '#core/pairdraw-api'\nimport { normalizeLinkURL } from '#core/text/hyperlink'\nimport { collectNodeFontFaces } from '#core/text/requirements/collect'\nimport {\n parseOptionalToolColor,\n toolNumber,\n nodeIdInputSchema,\n defineTool,\n nodeNotFound,\n toolFailure\n} from '#core/tools/schema'\n\n/**\n * A link a text tool sets, as the editor's link field takes it: a web or mail address, with\n * `https:` or `mailto:` added when typed without a scheme. Null or blank removes the link.\n */\nconst hyperlinkInputSchema = v.optional(\n v.pipe(\n v.nullable(v.string()),\n v.description(\n 'Link the text opens: an http(s) or mailto address (\"example.com\" becomes https://example.com, \"hi@example.com\" becomes mailto:). null or \"\" removes the link. Links are not underlined automatically; set text_decoration for that.'\n )\n )\n)\n\n/**\n * A scheme at the start of a typed link, even with a digit after its colon (`tel:123`), unless it\n * reads as a host and port (`localhost:3000`, `example.com:8080`), which gets `https://`.\n */\nconst TYPED_SCHEME = /^([a-z][a-z\\d+.-]*):/i\n\n/** A web address in the form the Figma API's link setter takes: `http(s)://host…`. */\nconst WEB_URL = /^https?:\\/\\/[^\\s/?#]+\\S*$/\n\n/** Whether a typed link names a scheme other than the http, https, and mailto links take. */\nfunction hasForeignScheme(typed: string): boolean {\n const scheme = TYPED_SCHEME.exec(typed)?.[1]?.toLowerCase()\n if (!scheme || scheme.includes('.') || scheme === 'localhost') return false\n return !['http', 'https', 'mailto'].includes(scheme)\n}\n\n/** What setting `hyperlink` asks for: no change, a removal, a URL, or an address it refuses. */\nfunction requestedHyperlink(\n hyperlink: string | null | undefined\n): { link: { type: 'URL'; value: string } | null } | { error: string } | null {\n if (hyperlink === undefined) return null\n if (hyperlink === null || hyperlink.trim() === '') return { link: null }\n const url = hasForeignScheme(hyperlink.trim()) ? null : normalizeLinkURL(hyperlink)\n if (!url) {\n return {\n error: `\"${hyperlink}\" is not a link the editor opens: use an http, https, or mailto address`\n }\n }\n // Figma keeps schemes in lower case and web addresses as `scheme://host`, so a loosely typed\n // `http:example.com` is written as the URL it parses to.\n const lowered = url.replace(TYPED_SCHEME, (scheme) => scheme.toLowerCase())\n const value =\n lowered.startsWith('mailto:') || WEB_URL.test(lowered) ? lowered : new URL(lowered).href\n return { link: { type: 'URL', value } }\n}\n\n/** The fonts a text layer uses, which an edit that lays it out again needs loaded. */\nexport function textFonts(figma: FigmaAPI, id: string): FigmaFontNameInput[] {\n const node = figma.graph.getNode(id)\n return node ? collectNodeFontFaces(node) : []\n}\n\nexport const setText = defineTool({\n name: 'set_text',\n\n description: 'Set text content of a text node.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n text: v.pipe(v.string(), v.description('Text content'))\n }),\n fonts: (figma, { id }) => textFonts(figma, id),\n execute: (figma, { id, text }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n node.characters = text\n return { id, text }\n }\n})\n\n/** Variable font axes a font tool can set, as Figma's `variationSettings`. */\n// An object with a value for every key rather than a record: a record publishes `propertyNames`,\n// which OpenAI refuses, and a JSON object's keys are strings anyway.\nconst variationsInputSchema = v.optional(\n v.pipe(\n v.objectWithRest({}, v.number()),\n v.description(\n 'Variable font axis values by OpenType tag (e.g. {\"wght\": 550, \"wdth\": 75}); axes left out keep the style\\'s values. Without a style, the nearest named style is picked.'\n )\n )\n)\n\n/** OpenType features a text tool sets, by tag; tags left out keep their state. */\nconst fontFeaturesInputSchema = v.optional(\n v.pipe(\n v.objectWithRest({}, v.boolean()),\n v.description(\n 'OpenType feature toggles by four-letter tag (e.g. {\"TNUM\": true, \"LIGA\": false, \"SS02\": true}); tags left out keep their state. Only features the font has take effect.'\n )\n )\n)\n\n/** Why a feature map cannot apply: a tag is not four letters, or a value is not a boolean. */\nfunction badFeatureEntry(features: Record<string, boolean> | undefined): { error: string } | null {\n for (const [tag, enabled] of Object.entries(features ?? {})) {\n if (tag.length !== 4) return { error: `\"${tag}\" is not a four-letter OpenType feature tag` }\n if (typeof enabled !== 'boolean') {\n return { error: `Feature \"${tag}\" needs a boolean value, received ${typeof enabled}` }\n }\n }\n return null\n}\n\n/**\n * The font a font tool gives text: what it names, the rest from `current`. Axes without a style\n * leave the style out, for the nearest named style to be picked.\n */\nfunction fontNameInput(\n args: { family?: string; style?: string; variations?: FigmaVariationSettings },\n current: FigmaFontName | null\n): FigmaFontNameInput {\n return {\n family: args.family ?? current?.family ?? '',\n style: args.style ?? (args.variations ? undefined : (current?.style ?? 'Regular')),\n variationSettings: args.variations\n }\n}\n\n/**\n * The font `set_font` gives the text, or null when it keeps the text's. Text set in several fonts\n * takes the given family or style for all of it, keeping the rest from its first character. Axes\n * without a style are set per range, each range taking its nearest named style, as in Figma.\n */\nfunction requestedFont(\n node: FigmaNodeProxy,\n args: { family?: string; style?: string; variations?: FigmaVariationSettings }\n): { whole: FigmaFontName } | { perRange: FigmaFontNameInput } | null {\n if (!args.family && !args.style && !args.variations) return null\n const fontName =\n typeof node.fontName === 'symbol' && node.characters.length > 0\n ? node.getRangeFontName(0, 1)\n : node.fontName\n const current = typeof fontName === 'symbol' ? null : fontName\n const family = args.family ?? current?.family ?? ''\n if (args.variations && !args.style && node.characters.length > 0) {\n return { perRange: { family, variationSettings: args.variations } }\n }\n const style = args.style ?? current?.style ?? 'Regular'\n return { whole: { family, style, variationSettings: args.variations } }\n}\n\nexport const setFont = defineTool({\n name: 'set_font',\n\n description: 'Set font properties of a text node.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n family: v.optional(v.pipe(v.string(), v.description('Font family name'))),\n size: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))),\n style: v.optional(\n v.pipe(v.string(), v.description('Font style (e.g. \"Bold\", \"Regular\", \"Bold Italic\")'))\n ),\n variations: variationsInputSchema\n }),\n // A new font replaces the text's, which then need not be loaded, so a missing font can be\n // replaced; a size or per-range axes lay out the text in its own fonts.\n fonts: (figma, args) => {\n const node = figma.getNodeById(args.id)\n const font = node && requestedFont(node, args)\n if (font && 'whole' in font) return [font.whole]\n return [...(font ? [font.perRange] : []), ...textFonts(figma, args.id)]\n },\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n const badTag = badVariationTag(args.variations)\n if (badTag) return badTag\n const font = requestedFont(node, args)\n try {\n if (font && 'whole' in font) node.fontName = font.whole\n else if (font) node.setRangeFontName(0, node.characters.length, font.perRange)\n // The size comes after the font, so it lays the text out in the font it ends up in.\n if (args.size !== undefined) node.fontSize = args.size\n } catch (error) {\n return toolFailure(error)\n }\n return { id: args.id, fontName: node.fontName, fontSize: node.fontSize }\n }\n})\n\n/** The font `set_font_range` gives its range: what it names, the rest from the range's start. */\nfunction rangeFont(\n node: FigmaNodeProxy,\n args: { start: number; family?: string; style?: string; variations?: FigmaVariationSettings }\n): FigmaFontNameInput {\n const inText = args.start < node.characters.length\n const current = inText ? node.getRangeFontName(args.start, args.start + 1) : node.fontName\n return fontNameInput(args, typeof current === 'symbol' ? null : current)\n}\n\ntype RangeEdit = {\n hyperlink: { link: { type: 'URL'; value: string } | null } | null\n color: Color | undefined\n}\n\n/** Why a variation setting cannot apply: an axis tag is not four letters. */\nfunction badVariationTag(variations: FigmaVariationSettings | undefined): { error: string } | null {\n const tag = Object.keys(variations ?? {}).find((key) => key.length !== 4)\n return tag === undefined ? null : { error: `\"${tag}\" is not a four-letter OpenType axis tag` }\n}\n\n/** What a range edit sets, or why it cannot run: nothing named, a bad colour, or a bad link. */\nfunction rangeEdit(args: {\n family?: string\n size?: number\n style?: string\n variations?: unknown\n font_features?: Record<string, boolean>\n color?: string\n hyperlink?: string | null\n}): RangeEdit | { error: string } {\n if (\n !args.family &&\n !args.size &&\n !args.style &&\n !args.variations &&\n !args.font_features &&\n !args.color &&\n args.hyperlink === undefined\n ) {\n return {\n error:\n 'set_font_range needs at least one of family, size, style, variations, font_features, color, or hyperlink'\n }\n }\n const hyperlink = requestedHyperlink(args.hyperlink)\n if (hyperlink && 'error' in hyperlink) return hyperlink\n const color = parseOptionalToolColor(args.color)\n if ('error' in color) return color\n return { hyperlink: hyperlink ?? null, color: color.color }\n}\n\nexport const setFontRange = defineTool({\n name: 'set_font_range',\n\n description: 'Set font properties, OpenType features, color, or a link for a text range.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n start: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Start character index'))),\n end: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('End character index'))),\n family: v.optional(v.pipe(v.string(), v.description('Font family name'))),\n size: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))),\n style: v.optional(v.pipe(v.string(), v.description('Font style'))),\n variations: variationsInputSchema,\n font_features: fontFeaturesInputSchema,\n color: v.optional(v.pipe(v.string(), v.description('Text color (hex)'))),\n hyperlink: hyperlinkInputSchema\n }),\n fonts: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return []\n const font = args.family || args.style || args.variations ? rangeFont(node, args) : null\n // A colour alone is a paint and lays nothing out, so text in a missing font can still take it.\n // Features reshape glyphs, so they need the text's fonts as a size change does.\n const laysOut = font !== null || args.size !== undefined || args.font_features !== undefined\n return [...(font ? [font] : []), ...(laysOut ? textFonts(figma, args.id) : [])]\n },\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n const { start, end } = args\n const badTag = badVariationTag(args.variations)\n if (badTag) return badTag\n const badFeature = badFeatureEntry(args.font_features)\n if (badFeature) return badFeature\n const edit = rangeEdit(args)\n if ('error' in edit) return edit\n const { hyperlink, color } = edit\n // The range methods reject an empty range or one past the text, before changing anything.\n try {\n if (args.size) node.setRangeFontSize(start, end, args.size)\n if (args.family || args.style || args.variations) {\n node.setRangeFontName(start, end, rangeFont(node, args))\n }\n if (color) node.setRangeFills(start, end, [{ type: 'SOLID', color }])\n if (hyperlink) node.setRangeHyperlink(start, end, hyperlink.link)\n if (args.font_features) {\n new PairdrawAPI(figma).setRangeFontFeatures(node, start, end, args.font_features)\n }\n } catch (error) {\n return toolFailure(error)\n }\n return {\n id: args.id,\n range: { start, end },\n ...(hyperlink ? { hyperlink: hyperlink.link?.value ?? null } : {})\n }\n }\n})\n\nexport const setTextResize = defineTool({\n name: 'set_text_resize',\n\n description: 'Set text auto-resize mode.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n mode: v.pipe(\n v.picklist(['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']),\n v.description('Resize mode')\n )\n }),\n fonts: (figma, { id }) => textFonts(figma, id),\n execute: (figma, { id, mode }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n node.textAutoResize = mode\n return { id, textAutoResize: mode }\n }\n})\n\nexport const setTextProperties = defineTool({\n name: 'set_text_properties',\n\n description:\n 'Set text layout properties: alignment, auto-resize, text case, decoration, truncation, OpenType features, and a link for the whole text.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Text node ID')),\n align_horizontal: v.optional(\n v.pipe(\n v.picklist(['LEFT', 'CENTER', 'RIGHT', 'JUSTIFIED']),\n v.description('Horizontal text alignment')\n )\n ),\n align_vertical: v.optional(\n v.pipe(v.picklist(['TOP', 'CENTER', 'BOTTOM']), v.description('Vertical text alignment'))\n ),\n auto_resize: v.optional(\n v.pipe(\n v.picklist(['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']),\n v.description('Text auto-resize mode')\n )\n ),\n direction: v.optional(\n v.pipe(v.picklist(['AUTO', 'LTR', 'RTL']), v.description('Text direction'))\n ),\n text_decoration: v.optional(\n v.pipe(v.picklist(['NONE', 'UNDERLINE', 'STRIKETHROUGH']), v.description('Text decoration'))\n ),\n hyperlink: hyperlinkInputSchema,\n font_features: fontFeaturesInputSchema\n }),\n fonts: (figma, { id }) => textFonts(figma, id),\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n if (node.type !== 'TEXT') return { error: `Node \"${args.id}\" is not a TEXT node` }\n // Refused before anything changes, so a bad address leaves the text as it was.\n const hyperlink = requestedHyperlink(args.hyperlink)\n if (hyperlink && 'error' in hyperlink) return hyperlink\n const badFeature = badFeatureEntry(args.font_features)\n if (badFeature) return badFeature\n const updated: string[] = []\n if (args.align_horizontal !== undefined) {\n node.textAlignHorizontal = args.align_horizontal\n updated.push('textAlignHorizontal')\n }\n if (args.align_vertical !== undefined) {\n node.textAlignVertical = args.align_vertical\n updated.push('textAlignVertical')\n }\n if (args.auto_resize !== undefined) {\n node.textAutoResize = args.auto_resize\n updated.push('textAutoResize')\n }\n if (args.direction !== undefined) {\n new PairdrawAPI(figma).setTextDirection(node, args.direction)\n updated.push('textDirection')\n }\n if (args.text_decoration !== undefined) {\n node.textDecoration = args.text_decoration\n updated.push('textDecoration')\n }\n if (args.font_features) {\n new PairdrawAPI(figma).setFontFeatures(node, args.font_features)\n updated.push('fontFeatures')\n }\n if (hyperlink) {\n try {\n node.hyperlink = hyperlink.link\n } catch (error) {\n return toolFailure(error)\n }\n updated.push('hyperlink')\n }\n return { id: args.id, updated }\n }\n})\n"],"mappings":";;;;;;;;;;AAuBA,MAAM,uBAAuB,EAAE,SAC7B,EAAE,KACA,EAAE,SAAS,EAAE,OAAO,CAAC,GACrB,EAAE,YACA,2OACF,CACF,CACF;;;;;AAMA,MAAM,eAAe;;AAGrB,MAAM,UAAU;;AAGhB,SAAS,iBAAiB,OAAwB;CAChD,MAAM,SAAS,aAAa,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Q,KAAK,gBAAgB;EAC/B;EACA,IAAI,KAAK,cAAc,KAAA,GAAW;GAChC,IAAI,YAAY,KAAK,CAAC,CAAC,iBAAiB,MAAM,KAAK,SAAS;GAC5D,QAAQ,KAAK,eAAe;EAC9B;EACA,IAAI,KAAK,oBAAoB,KAAA,GAAW;GACtC,KAAK,iBAAiB,KAAK;GAC3B,QAAQ,KAAK,gBAAgB;EAC/B;EACA,IAAI,KAAK,eAAe;GACtB,IAAI,YAAY,KAAK,CAAC,CAAC,gBAAgB,MAAM,KAAK,aAAa;GAC/D,QAAQ,KAAK,cAAc;EAC7B;EACA,IAAI,WAAW;GACb,IAAI;IACF,KAAK,YAAY,UAAU;GAC7B,SAAS,OAAO;IACd,OAAO,YAAY,KAAK;GAC1B;GACA,QAAQ,KAAK,WAAW;EAC1B;EACA,OAAO;GAAE,IAAI,KAAK;GAAI;EAAQ;CAChC;AACF,CAAC"}
1
+ {"version":3,"file":"text.js","names":[],"sources":["../../../src/tools/modify/text.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { DocumentColorSpace } from '@pairdraw/scene-graph'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'\nimport type { FigmaFontName, FigmaFontNameInput } from '#core/figma-api/fonts/names'\nimport type { FigmaVariationSettings } from '#core/figma-api/fonts/variations'\nimport { PairdrawAPI } from '#core/pairdraw-api'\nimport { normalizeLinkURL } from '#core/text/hyperlink'\nimport { collectNodeFontFaces } from '#core/text/requirements/collect'\nimport {\n parseOptionalToolColor,\n toolNumber,\n nodeIdInputSchema,\n defineTool,\n nodeNotFound,\n toolFailure\n} from '#core/tools/schema'\n\n/**\n * A link a text tool sets, as the editor's link field takes it: a web or mail address, with\n * `https:` or `mailto:` added when typed without a scheme. Null or blank removes the link.\n */\nconst hyperlinkInputSchema = v.optional(\n v.pipe(\n v.nullable(v.string()),\n v.description(\n 'Link the text opens: an http(s) or mailto address (\"example.com\" becomes https://example.com, \"hi@example.com\" becomes mailto:). null or \"\" removes the link. Links are not underlined automatically; set text_decoration for that.'\n )\n )\n)\n\n/**\n * A scheme at the start of a typed link, even with a digit after its colon (`tel:123`), unless it\n * reads as a host and port (`localhost:3000`, `example.com:8080`), which gets `https://`.\n */\nconst TYPED_SCHEME = /^([a-z][a-z\\d+.-]*):/i\n\n/** A web address in the form the Figma API's link setter takes: `http(s)://host…`. */\nconst WEB_URL = /^https?:\\/\\/[^\\s/?#]+\\S*$/\n\n/** Whether a typed link names a scheme other than the http, https, and mailto links take. */\nfunction hasForeignScheme(typed: string): boolean {\n const scheme = TYPED_SCHEME.exec(typed)?.[1]?.toLowerCase()\n if (!scheme || scheme.includes('.') || scheme === 'localhost') return false\n return !['http', 'https', 'mailto'].includes(scheme)\n}\n\n/** What setting `hyperlink` asks for: no change, a removal, a URL, or an address it refuses. */\nfunction requestedHyperlink(\n hyperlink: string | null | undefined\n): { link: { type: 'URL'; value: string } | null } | { error: string } | null {\n if (hyperlink === undefined) return null\n if (hyperlink === null || hyperlink.trim() === '') return { link: null }\n const url = hasForeignScheme(hyperlink.trim()) ? null : normalizeLinkURL(hyperlink)\n if (!url) {\n return {\n error: `\"${hyperlink}\" is not a link the editor opens: use an http, https, or mailto address`\n }\n }\n // Figma keeps schemes in lower case and web addresses as `scheme://host`, so a loosely typed\n // `http:example.com` is written as the URL it parses to.\n const lowered = url.replace(TYPED_SCHEME, (scheme) => scheme.toLowerCase())\n const value =\n lowered.startsWith('mailto:') || WEB_URL.test(lowered) ? lowered : new URL(lowered).href\n return { link: { type: 'URL', value } }\n}\n\n/** The fonts a text layer uses, which an edit that lays it out again needs loaded. */\nexport function textFonts(figma: FigmaAPI, id: string): FigmaFontNameInput[] {\n const node = figma.graph.getNode(id)\n return node ? collectNodeFontFaces(node) : []\n}\n\nexport const setText = defineTool({\n name: 'set_text',\n\n description: 'Set text content of a text node.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n text: v.pipe(v.string(), v.description('Text content'))\n }),\n fonts: (figma, { id }) => textFonts(figma, id),\n execute: (figma, { id, text }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n node.characters = text\n return { id, text }\n }\n})\n\n/** Variable font axes a font tool can set, as Figma's `variationSettings`. */\n// An object with a value for every key rather than a record: a record publishes `propertyNames`,\n// which OpenAI refuses, and a JSON object's keys are strings anyway.\nconst variationsInputSchema = v.optional(\n v.pipe(\n v.objectWithRest({}, v.number()),\n v.description(\n 'Variable font axis values by OpenType tag (e.g. {\"wght\": 550, \"wdth\": 75}); axes left out keep the style\\'s values. Without a style, the nearest named style is picked.'\n )\n )\n)\n\n/** OpenType features a text tool sets, by tag; tags left out keep their state. */\nconst fontFeaturesInputSchema = v.optional(\n v.pipe(\n v.objectWithRest({}, v.boolean()),\n v.description(\n 'OpenType feature toggles by four-letter tag (e.g. {\"TNUM\": true, \"LIGA\": false, \"SS02\": true}); tags left out keep their state. Only features the font has take effect.'\n )\n )\n)\n\n/** Why a feature map cannot apply: a tag is not four letters, or a value is not a boolean. */\nfunction badFeatureEntry(features: Record<string, boolean> | undefined): { error: string } | null {\n for (const [tag, enabled] of Object.entries(features ?? {})) {\n if (tag.length !== 4) return { error: `\"${tag}\" is not a four-letter OpenType feature tag` }\n if (typeof enabled !== 'boolean') {\n return { error: `Feature \"${tag}\" needs a boolean value, received ${typeof enabled}` }\n }\n }\n return null\n}\n\n/**\n * The font a font tool gives text: what it names, the rest from `current`. Axes without a style\n * leave the style out, for the nearest named style to be picked.\n */\nfunction fontNameInput(\n args: { family?: string; style?: string; variations?: FigmaVariationSettings },\n current: FigmaFontName | null\n): FigmaFontNameInput {\n return {\n family: args.family ?? current?.family ?? '',\n style: args.style ?? (args.variations ? undefined : (current?.style ?? 'Regular')),\n variationSettings: args.variations\n }\n}\n\n/**\n * The font `set_font` gives the text, or null when it keeps the text's. Text set in several fonts\n * takes the given family or style for all of it, keeping the rest from its first character. Axes\n * without a style are set per range, each range taking its nearest named style, as in Figma.\n */\nfunction requestedFont(\n node: FigmaNodeProxy,\n args: { family?: string; style?: string; variations?: FigmaVariationSettings }\n): { whole: FigmaFontName } | { perRange: FigmaFontNameInput } | null {\n if (!args.family && !args.style && !args.variations) return null\n const fontName =\n typeof node.fontName === 'symbol' && node.characters.length > 0\n ? node.getRangeFontName(0, 1)\n : node.fontName\n const current = typeof fontName === 'symbol' ? null : fontName\n const family = args.family ?? current?.family ?? ''\n if (args.variations && !args.style && node.characters.length > 0) {\n return { perRange: { family, variationSettings: args.variations } }\n }\n const style = args.style ?? current?.style ?? 'Regular'\n return { whole: { family, style, variationSettings: args.variations } }\n}\n\nexport const setFont = defineTool({\n name: 'set_font',\n\n description: 'Set font properties of a text node.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n family: v.optional(v.pipe(v.string(), v.description('Font family name'))),\n size: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))),\n style: v.optional(\n v.pipe(v.string(), v.description('Font style (e.g. \"Bold\", \"Regular\", \"Bold Italic\")'))\n ),\n variations: variationsInputSchema\n }),\n // A new font replaces the text's, which then need not be loaded, so a missing font can be\n // replaced; a size or per-range axes lay out the text in its own fonts.\n fonts: (figma, args) => {\n const node = figma.getNodeById(args.id)\n const font = node && requestedFont(node, args)\n if (font && 'whole' in font) return [font.whole]\n return [...(font ? [font.perRange] : []), ...textFonts(figma, args.id)]\n },\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n const badTag = badVariationTag(args.variations)\n if (badTag) return badTag\n const font = requestedFont(node, args)\n try {\n if (font && 'whole' in font) node.fontName = font.whole\n else if (font) node.setRangeFontName(0, node.characters.length, font.perRange)\n // The size comes after the font, so it lays the text out in the font it ends up in.\n if (args.size !== undefined) node.fontSize = args.size\n } catch (error) {\n return toolFailure(error)\n }\n return { id: args.id, fontName: node.fontName, fontSize: node.fontSize }\n }\n})\n\n/** The font `set_font_range` gives its range: what it names, the rest from the range's start. */\nfunction rangeFont(\n node: FigmaNodeProxy,\n args: { start: number; family?: string; style?: string; variations?: FigmaVariationSettings }\n): FigmaFontNameInput {\n const inText = args.start < node.characters.length\n const current = inText ? node.getRangeFontName(args.start, args.start + 1) : node.fontName\n return fontNameInput(args, typeof current === 'symbol' ? null : current)\n}\n\ntype RangeEdit = {\n hyperlink: { link: { type: 'URL'; value: string } | null } | null\n color: Color | undefined\n}\n\n/** Why a variation setting cannot apply: an axis tag is not four letters. */\nfunction badVariationTag(variations: FigmaVariationSettings | undefined): { error: string } | null {\n const tag = Object.keys(variations ?? {}).find((key) => key.length !== 4)\n return tag === undefined ? null : { error: `\"${tag}\" is not a four-letter OpenType axis tag` }\n}\n\n/** What a range edit sets, or why it cannot run: nothing named, a bad colour, or a bad link. */\nfunction rangeEdit(\n args: {\n family?: string\n size?: number\n style?: string\n variations?: unknown\n font_features?: Record<string, boolean>\n color?: string\n hyperlink?: string | null\n },\n profile: DocumentColorSpace\n): RangeEdit | { error: string } {\n if (\n !args.family &&\n !args.size &&\n !args.style &&\n !args.variations &&\n !args.font_features &&\n !args.color &&\n args.hyperlink === undefined\n ) {\n return {\n error:\n 'set_font_range needs at least one of family, size, style, variations, font_features, color, or hyperlink'\n }\n }\n const hyperlink = requestedHyperlink(args.hyperlink)\n if (hyperlink && 'error' in hyperlink) return hyperlink\n const color = parseOptionalToolColor(args.color, profile)\n if ('error' in color) return color\n return { hyperlink: hyperlink ?? null, color: color.color }\n}\n\nexport const setFontRange = defineTool({\n name: 'set_font_range',\n\n description: 'Set font properties, OpenType features, color, or a link for a text range.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n start: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Start character index'))),\n end: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('End character index'))),\n family: v.optional(v.pipe(v.string(), v.description('Font family name'))),\n size: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))),\n style: v.optional(v.pipe(v.string(), v.description('Font style'))),\n variations: variationsInputSchema,\n font_features: fontFeaturesInputSchema,\n color: v.optional(v.pipe(v.string(), v.description('Text color (hex)'))),\n hyperlink: hyperlinkInputSchema\n }),\n fonts: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return []\n const font = args.family || args.style || args.variations ? rangeFont(node, args) : null\n // A colour alone is a paint and lays nothing out, so text in a missing font can still take it.\n // Features reshape glyphs, so they need the text's fonts as a size change does.\n const laysOut = font !== null || args.size !== undefined || args.font_features !== undefined\n return [...(font ? [font] : []), ...(laysOut ? textFonts(figma, args.id) : [])]\n },\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n const { start, end } = args\n const badTag = badVariationTag(args.variations)\n if (badTag) return badTag\n const badFeature = badFeatureEntry(args.font_features)\n if (badFeature) return badFeature\n const edit = rangeEdit(args, figma.graph.documentColorSpace)\n if ('error' in edit) return edit\n const { hyperlink, color } = edit\n // The range methods reject an empty range or one past the text, before changing anything.\n try {\n if (args.size) node.setRangeFontSize(start, end, args.size)\n if (args.family || args.style || args.variations) {\n node.setRangeFontName(start, end, rangeFont(node, args))\n }\n if (color) node.setRangeFills(start, end, [{ type: 'SOLID', color }])\n if (hyperlink) node.setRangeHyperlink(start, end, hyperlink.link)\n if (args.font_features) {\n new PairdrawAPI(figma).setRangeFontFeatures(node, start, end, args.font_features)\n }\n } catch (error) {\n return toolFailure(error)\n }\n return {\n id: args.id,\n range: { start, end },\n ...(hyperlink ? { hyperlink: hyperlink.link?.value ?? null } : {})\n }\n }\n})\n\nexport const setTextResize = defineTool({\n name: 'set_text_resize',\n\n description: 'Set text auto-resize mode.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n mode: v.pipe(\n v.picklist(['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']),\n v.description('Resize mode')\n )\n }),\n fonts: (figma, { id }) => textFonts(figma, id),\n execute: (figma, { id, mode }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n node.textAutoResize = mode\n return { id, textAutoResize: mode }\n }\n})\n\nexport const setTextProperties = defineTool({\n name: 'set_text_properties',\n\n description:\n 'Set text layout properties: alignment, auto-resize, text case, decoration, truncation, OpenType features, and a link for the whole text.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Text node ID')),\n align_horizontal: v.optional(\n v.pipe(\n v.picklist(['LEFT', 'CENTER', 'RIGHT', 'JUSTIFIED']),\n v.description('Horizontal text alignment')\n )\n ),\n align_vertical: v.optional(\n v.pipe(v.picklist(['TOP', 'CENTER', 'BOTTOM']), v.description('Vertical text alignment'))\n ),\n auto_resize: v.optional(\n v.pipe(\n v.picklist(['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']),\n v.description('Text auto-resize mode')\n )\n ),\n direction: v.optional(\n v.pipe(v.picklist(['AUTO', 'LTR', 'RTL']), v.description('Text direction'))\n ),\n text_decoration: v.optional(\n v.pipe(v.picklist(['NONE', 'UNDERLINE', 'STRIKETHROUGH']), v.description('Text decoration'))\n ),\n hyperlink: hyperlinkInputSchema,\n font_features: fontFeaturesInputSchema\n }),\n fonts: (figma, { id }) => textFonts(figma, id),\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n if (node.type !== 'TEXT') return { error: `Node \"${args.id}\" is not a TEXT node` }\n // Refused before anything changes, so a bad address leaves the text as it was.\n const hyperlink = requestedHyperlink(args.hyperlink)\n if (hyperlink && 'error' in hyperlink) return hyperlink\n const badFeature = badFeatureEntry(args.font_features)\n if (badFeature) return badFeature\n const updated: string[] = []\n if (args.align_horizontal !== undefined) {\n node.textAlignHorizontal = args.align_horizontal\n updated.push('textAlignHorizontal')\n }\n if (args.align_vertical !== undefined) {\n node.textAlignVertical = args.align_vertical\n updated.push('textAlignVertical')\n }\n if (args.auto_resize !== undefined) {\n node.textAutoResize = args.auto_resize\n updated.push('textAutoResize')\n }\n if (args.direction !== undefined) {\n new PairdrawAPI(figma).setTextDirection(node, args.direction)\n updated.push('textDirection')\n }\n if (args.text_decoration !== undefined) {\n node.textDecoration = args.text_decoration\n updated.push('textDecoration')\n }\n if (args.font_features) {\n new PairdrawAPI(figma).setFontFeatures(node, args.font_features)\n updated.push('fontFeatures')\n }\n if (hyperlink) {\n try {\n node.hyperlink = hyperlink.link\n } catch (error) {\n return toolFailure(error)\n }\n updated.push('hyperlink')\n }\n return { id: args.id, updated }\n }\n})\n"],"mappings":";;;;;;;;;;AAwBA,MAAM,uBAAuB,EAAE,SAC7B,EAAE,KACA,EAAE,SAAS,EAAE,OAAO,CAAC,GACrB,EAAE,YACA,2OACF,CACF,CACF;;;;;AAMA,MAAM,eAAe;;AAGrB,MAAM,UAAU;;AAGhB,SAAS,iBAAiB,OAAwB;CAChD,MAAM,SAAS,aAAa,KAAK,KAAK,CAAC,GAAG,EAAE,EAAE,YAAY;CAC1D,IAAI,CAAC,UAAU,OAAO,SAAS,GAAG,KAAK,WAAW,aAAa,OAAO;CACtE,OAAO,CAAC;EAAC;EAAQ;EAAS;CAAQ,CAAC,CAAC,SAAS,MAAM;AACrD;;AAGA,SAAS,mBACP,WAC4E;CAC5E,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,cAAc,QAAQ,UAAU,KAAK,MAAM,IAAI,OAAO,EAAE,MAAM,KAAK;CACvE,MAAM,MAAM,iBAAiB,UAAU,KAAK,CAAC,IAAI,OAAO,iBAAiB,SAAS;CAClF,IAAI,CAAC,KACH,OAAO,EACL,OAAO,IAAI,UAAU,yEACvB;CAIF,MAAM,UAAU,IAAI,QAAQ,eAAe,WAAW,OAAO,YAAY,CAAC;CAG1E,OAAO,EAAE,MAAM;EAAE,MAAM;EAAO,OAD5B,QAA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