@pairdraw/core 0.19.1 → 0.19.2

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 (263) hide show
  1. package/dist/canvas/images/previews.d.ts +1 -1
  2. package/dist/canvas/overlays/index.d.ts +2 -2
  3. package/dist/canvas/overlays/index.js +2 -2
  4. package/dist/canvas/overlays/selection.d.ts +1 -2
  5. package/dist/canvas/overlays/selection.d.ts.map +1 -1
  6. package/dist/canvas/overlays/selection.js +2 -9
  7. package/dist/canvas/overlays/selection.js.map +1 -1
  8. package/dist/canvas/renderer/fonts.d.ts.map +1 -1
  9. package/dist/canvas/renderer/fonts.js +2 -0
  10. package/dist/canvas/renderer/fonts.js.map +1 -1
  11. package/dist/canvas/renderer/methods.d.ts +0 -1
  12. package/dist/canvas/renderer/methods.d.ts.map +1 -1
  13. package/dist/canvas/renderer/methods.js +1 -4
  14. package/dist/canvas/renderer/methods.js.map +1 -1
  15. package/dist/canvas/renderer/overlay-pass.d.ts.map +1 -1
  16. package/dist/canvas/renderer/overlay-pass.js +0 -1
  17. package/dist/canvas/renderer/overlay-pass.js.map +1 -1
  18. package/dist/canvas/renderer/pipeline.d.ts.map +1 -1
  19. package/dist/canvas/renderer/pipeline.js +0 -1
  20. package/dist/canvas/renderer/pipeline.js.map +1 -1
  21. package/dist/canvas/renderer/types.d.ts +0 -1
  22. package/dist/canvas/renderer/types.d.ts.map +1 -1
  23. package/dist/canvas/renderer.d.ts +0 -1
  24. package/dist/canvas/renderer.d.ts.map +1 -1
  25. package/dist/canvas/renderer.js.map +1 -1
  26. package/dist/design-jsx/index.d.ts +2 -2
  27. package/dist/design-jsx/index.js +2 -2
  28. package/dist/design-jsx/renderer.d.ts +3 -2
  29. package/dist/design-jsx/renderer.d.ts.map +1 -1
  30. package/dist/design-jsx/renderer.js +2 -2
  31. package/dist/design-jsx/renderer.js.map +1 -1
  32. package/dist/editor/clipboard/snapshot.d.ts.map +1 -1
  33. package/dist/editor/clipboard/snapshot.js +12 -4
  34. package/dist/editor/clipboard/snapshot.js.map +1 -1
  35. package/dist/editor/clipboard.d.ts.map +1 -1
  36. package/dist/editor/clipboard.js +2 -7
  37. package/dist/editor/clipboard.js.map +1 -1
  38. package/dist/editor/color-space.d.ts.map +1 -1
  39. package/dist/editor/color-space.js +33 -38
  40. package/dist/editor/color-space.js.map +1 -1
  41. package/dist/editor/create.d.ts +9 -5
  42. package/dist/editor/create.d.ts.map +1 -1
  43. package/dist/editor/create.js +10 -1
  44. package/dist/editor/create.js.map +1 -1
  45. package/dist/editor/history/edit.d.ts.map +1 -1
  46. package/dist/editor/history/edit.js +2 -1
  47. package/dist/editor/history/edit.js.map +1 -1
  48. package/dist/editor/nudge.js +1 -1
  49. package/dist/editor/nudge.js.map +1 -1
  50. package/dist/editor/read-only/actions.js +2 -0
  51. package/dist/editor/read-only/actions.js.map +1 -1
  52. package/dist/editor/selection/container.d.ts +2 -0
  53. package/dist/editor/selection/container.d.ts.map +1 -1
  54. package/dist/editor/selection/container.js +17 -1
  55. package/dist/editor/selection/container.js.map +1 -1
  56. package/dist/editor/selection/navigation.js +7 -4
  57. package/dist/editor/selection/navigation.js.map +1 -1
  58. package/dist/editor/selection/read.d.ts +2 -2
  59. package/dist/editor/selection.d.ts +4 -2
  60. package/dist/editor/selection.d.ts.map +1 -1
  61. package/dist/editor/shapes/with-text.d.ts.map +1 -1
  62. package/dist/editor/shapes/with-text.js +2 -5
  63. package/dist/editor/shapes/with-text.js.map +1 -1
  64. package/dist/editor/structure/auto-layout-wrap.js +1 -1
  65. package/dist/editor/structure/auto-layout-wrap.js.map +1 -1
  66. package/dist/editor/structure/boolean.d.ts +2 -3
  67. package/dist/editor/structure/boolean.d.ts.map +1 -1
  68. package/dist/editor/structure/boolean.js.map +1 -1
  69. package/dist/editor/structure/group/bounds.d.ts.map +1 -1
  70. package/dist/editor/structure/group/bounds.js +1 -3
  71. package/dist/editor/structure/group/bounds.js.map +1 -1
  72. package/dist/editor/structure/outline-stroke.js +3 -3
  73. package/dist/editor/structure/outline-stroke.js.map +1 -1
  74. package/dist/editor/structure/reorder.d.ts.map +1 -1
  75. package/dist/editor/structure/reorder.js +7 -14
  76. package/dist/editor/structure/reorder.js.map +1 -1
  77. package/dist/editor/structure/state.js +1 -1
  78. package/dist/editor/structure/state.js.map +1 -1
  79. package/dist/editor/structure.d.ts +1 -2
  80. package/dist/editor/structure.d.ts.map +1 -1
  81. package/dist/editor/structure.js +3 -3
  82. package/dist/editor/structure.js.map +1 -1
  83. package/dist/editor/types.d.ts +4 -1
  84. package/dist/editor/types.d.ts.map +1 -1
  85. package/dist/editor/variables.d.ts.map +1 -1
  86. package/dist/editor/variables.js +57 -1
  87. package/dist/editor/variables.js.map +1 -1
  88. package/dist/figma-api/accessors/text/index.d.ts.map +1 -1
  89. package/dist/figma-api/accessors/text/index.js +4 -1
  90. package/dist/figma-api/accessors/text/index.js.map +1 -1
  91. package/dist/figma-api/fonts/loaded.d.ts +3 -1
  92. package/dist/figma-api/fonts/loaded.d.ts.map +1 -1
  93. package/dist/figma-api/fonts/loaded.js +8 -1
  94. package/dist/figma-api/fonts/loaded.js.map +1 -1
  95. package/dist/figma-api/index.d.ts +13 -0
  96. package/dist/figma-api/index.d.ts.map +1 -1
  97. package/dist/figma-api/index.js +13 -0
  98. package/dist/figma-api/index.js.map +1 -1
  99. package/dist/figma-api/serialization.d.ts.map +1 -1
  100. package/dist/figma-api/serialization.js +2 -1
  101. package/dist/figma-api/serialization.js.map +1 -1
  102. package/dist/figma-api/shape-details.d.ts +26 -0
  103. package/dist/figma-api/shape-details.d.ts.map +1 -0
  104. package/dist/figma-api/shape-details.js +28 -0
  105. package/dist/figma-api/shape-details.js.map +1 -0
  106. package/dist/figma-api/shape-with-text.js +2 -5
  107. package/dist/figma-api/shape-with-text.js.map +1 -1
  108. package/dist/figma-api/surface.d.ts +1 -1
  109. package/dist/figma-api/surface.d.ts.map +1 -1
  110. package/dist/figma-api/surface.js +1 -0
  111. package/dist/figma-api/surface.js.map +1 -1
  112. package/dist/icons/svg.js +1 -1
  113. package/dist/icons/svg.js.map +1 -1
  114. package/dist/io/formats/drawio/index.d.ts.map +1 -1
  115. package/dist/io/formats/drawio/index.js +1 -1
  116. package/dist/io/formats/drawio/index.js.map +1 -1
  117. package/dist/io/formats/html/layers.d.ts +7 -4
  118. package/dist/io/formats/html/layers.d.ts.map +1 -1
  119. package/dist/io/formats/html/layers.js +4 -1
  120. package/dist/io/formats/html/layers.js.map +1 -1
  121. package/dist/io/formats/pdf/dom.d.ts +6 -1
  122. package/dist/io/formats/pdf/dom.d.ts.map +1 -1
  123. package/dist/io/formats/pdf/dom.js +9 -22
  124. package/dist/io/formats/pdf/dom.js.map +1 -1
  125. package/dist/io/formats/pdf/export.js +1 -1
  126. package/dist/io/formats/pdf/export.js.map +1 -1
  127. package/dist/io/formats/svg/defs.d.ts.map +1 -1
  128. package/dist/io/formats/svg/defs.js +3 -1
  129. package/dist/io/formats/svg/defs.js.map +1 -1
  130. package/dist/io/formats/svg/export.d.ts.map +1 -1
  131. package/dist/io/formats/svg/export.js +52 -16
  132. package/dist/io/formats/svg/export.js.map +1 -1
  133. package/dist/layout/apply.d.ts.map +1 -1
  134. package/dist/layout/apply.js +50 -12
  135. package/dist/layout/apply.js.map +1 -1
  136. package/dist/layout/derived.d.ts +7 -1
  137. package/dist/layout/derived.d.ts.map +1 -1
  138. package/dist/layout/derived.js +11 -1
  139. package/dist/layout/derived.js.map +1 -1
  140. package/dist/layout/grid.d.ts +7 -2
  141. package/dist/layout/grid.d.ts.map +1 -1
  142. package/dist/layout/grid.js +27 -9
  143. package/dist/layout/grid.js.map +1 -1
  144. package/dist/layout/mutations.d.ts +1 -0
  145. package/dist/layout/mutations.d.ts.map +1 -1
  146. package/dist/layout/mutations.js +10 -0
  147. package/dist/layout/mutations.js.map +1 -1
  148. package/dist/layout/strokes.d.ts +9 -1
  149. package/dist/layout/strokes.d.ts.map +1 -1
  150. package/dist/layout/strokes.js +12 -1
  151. package/dist/layout/strokes.js.map +1 -1
  152. package/dist/layout/yoga-helpers.d.ts +3 -1
  153. package/dist/layout/yoga-helpers.d.ts.map +1 -1
  154. package/dist/layout/yoga-helpers.js +16 -2
  155. package/dist/layout/yoga-helpers.js.map +1 -1
  156. package/dist/layout.d.ts.map +1 -1
  157. package/dist/layout.js +71 -38
  158. package/dist/layout.js.map +1 -1
  159. package/dist/lint/linter.d.ts +1 -0
  160. package/dist/lint/linter.d.ts.map +1 -1
  161. package/dist/lint/linter.js +13 -1
  162. package/dist/lint/linter.js.map +1 -1
  163. package/dist/lint/rules/effect-style-required.js +1 -0
  164. package/dist/lint/rules/effect-style-required.js.map +1 -1
  165. package/dist/lint/rules/text-style-required.js +1 -0
  166. package/dist/lint/rules/text-style-required.js.map +1 -1
  167. package/dist/lint/types.d.ts +7 -0
  168. package/dist/lint/types.d.ts.map +1 -1
  169. package/dist/rpc/commands.d.ts +2 -2
  170. package/dist/rpc/index.d.ts +2 -2
  171. package/dist/rpc/read-commands.d.ts +18 -8
  172. package/dist/rpc/read-commands.d.ts.map +1 -1
  173. package/dist/rpc/read-commands.js +18 -9
  174. package/dist/rpc/read-commands.js.map +1 -1
  175. package/dist/text/font/faces.d.ts +12 -1
  176. package/dist/text/font/faces.d.ts.map +1 -1
  177. package/dist/text/font/faces.js +15 -1
  178. package/dist/text/font/faces.js.map +1 -1
  179. package/dist/text/font/manager.d.ts.map +1 -1
  180. package/dist/text/font/manager.js +6 -11
  181. package/dist/text/font/manager.js.map +1 -1
  182. package/dist/text/index.d.ts +2 -2
  183. package/dist/text/index.js +2 -2
  184. package/dist/tools/modify/layout.d.ts.map +1 -1
  185. package/dist/tools/modify/layout.js +1 -0
  186. package/dist/tools/modify/layout.js.map +1 -1
  187. package/dist/tools/read/nodes.d.ts.map +1 -1
  188. package/dist/tools/read/nodes.js.map +1 -1
  189. package/dist/tools/structure/batch.d.ts.map +1 -1
  190. package/dist/tools/structure/batch.js +14 -0
  191. package/dist/tools/structure/batch.js.map +1 -1
  192. package/dist/tools/vector/path.d.ts.map +1 -1
  193. package/dist/tools/vector/path.js +39 -7
  194. package/dist/tools/vector/path.js.map +1 -1
  195. package/dist/xpath.d.ts +3 -0
  196. package/dist/xpath.d.ts.map +1 -1
  197. package/dist/xpath.js +3 -1
  198. package/dist/xpath.js.map +1 -1
  199. package/package.json +9 -9
  200. package/src/canvas/overlays/index.ts +0 -1
  201. package/src/canvas/overlays/selection.ts +1 -12
  202. package/src/canvas/renderer/fonts.ts +2 -0
  203. package/src/canvas/renderer/methods.ts +0 -9
  204. package/src/canvas/renderer/overlay-pass.ts +0 -1
  205. package/src/canvas/renderer/pipeline.ts +0 -1
  206. package/src/canvas/renderer/types.ts +0 -1
  207. package/src/canvas/renderer.ts +0 -1
  208. package/src/design-jsx/index.ts +1 -1
  209. package/src/design-jsx/renderer.ts +1 -1
  210. package/src/editor/clipboard/snapshot.ts +21 -4
  211. package/src/editor/clipboard.ts +4 -14
  212. package/src/editor/color-space.ts +47 -38
  213. package/src/editor/create.ts +14 -2
  214. package/src/editor/history/edit.ts +5 -1
  215. package/src/editor/nudge.ts +1 -1
  216. package/src/editor/read-only/actions.ts +2 -0
  217. package/src/editor/selection/container.ts +24 -1
  218. package/src/editor/selection/navigation.ts +8 -6
  219. package/src/editor/shapes/with-text.ts +2 -5
  220. package/src/editor/structure/auto-layout-wrap.ts +1 -1
  221. package/src/editor/structure/boolean.ts +1 -3
  222. package/src/editor/structure/group/bounds.ts +1 -5
  223. package/src/editor/structure/outline-stroke.ts +3 -3
  224. package/src/editor/structure/reorder.ts +8 -14
  225. package/src/editor/structure/state.ts +1 -1
  226. package/src/editor/structure.ts +5 -8
  227. package/src/editor/types.ts +4 -1
  228. package/src/editor/variables.ts +74 -2
  229. package/src/figma-api/accessors/text/index.ts +10 -1
  230. package/src/figma-api/fonts/loaded.ts +9 -0
  231. package/src/figma-api/index.ts +25 -0
  232. package/src/figma-api/serialization.ts +2 -1
  233. package/src/figma-api/shape-details.ts +50 -0
  234. package/src/figma-api/shape-with-text.ts +2 -5
  235. package/src/figma-api/surface.ts +1 -0
  236. package/src/global.d.ts +5 -0
  237. package/src/icons/svg.ts +3 -1
  238. package/src/io/formats/drawio/index.ts +3 -1
  239. package/src/io/formats/html/layers.ts +11 -2
  240. package/src/io/formats/pdf/dom.ts +10 -18
  241. package/src/io/formats/pdf/export.ts +1 -1
  242. package/src/io/formats/svg/defs.ts +10 -1
  243. package/src/io/formats/svg/export.ts +94 -19
  244. package/src/layout/apply.ts +87 -21
  245. package/src/layout/derived.ts +14 -0
  246. package/src/layout/grid.ts +33 -9
  247. package/src/layout/mutations.ts +13 -1
  248. package/src/layout/strokes.ts +12 -0
  249. package/src/layout/yoga-helpers.ts +18 -1
  250. package/src/layout.ts +94 -49
  251. package/src/lint/linter.ts +17 -2
  252. package/src/lint/rules/effect-style-required.ts +2 -0
  253. package/src/lint/rules/text-style-required.ts +2 -0
  254. package/src/lint/types.ts +8 -0
  255. package/src/rpc/index.ts +1 -0
  256. package/src/rpc/read-commands.ts +40 -23
  257. package/src/text/font/faces.ts +22 -0
  258. package/src/text/font/manager.ts +9 -11
  259. package/src/tools/modify/layout.ts +5 -0
  260. package/src/tools/read/nodes.ts +0 -1
  261. package/src/tools/structure/batch.ts +22 -0
  262. package/src/tools/vector/path.ts +30 -6
  263. package/src/xpath.ts +6 -1
@@ -1,6 +1,8 @@
1
+ import { computeAccurateBounds } from "../../vector/curve-math.js";
2
+ import { regenerateFillGeometry } from "../../vector/fill-geometry.js";
1
3
  import { defineTool, nodeIdInputSchema, nodeInputSchema, toolNumber } from "../schema.js";
2
4
  import { parseVectorNetworkJSON } from "./network.js";
3
- import { cloneVectorNetwork } from "@pairdraw/scene-graph/vector-network";
5
+ import { cloneVectorNetwork, transformVectorNetwork } from "@pairdraw/scene-graph/vector-network";
4
6
  import * as v from "valibot";
5
7
  //#region src/tools/vector/path.ts
6
8
  function getVectorNode(figma, id) {
@@ -12,6 +14,35 @@ function getVectorNode(figma, id) {
12
14
  vn: cloneVectorNetwork(node.vectorNetwork)
13
15
  };
14
16
  }
17
+ /**
18
+ * Writes an edited path as the plugin API's vectorNetwork setter does: the layer's box fits the
19
+ * path, the vertices rebase to it, and imported fillGeometry rebuilds from the new path so fills
20
+ * follow the edit instead of drawing the old shape.
21
+ */
22
+ function writePath(figma, node, network) {
23
+ const bounds = computeAccurateBounds(network);
24
+ const hasGeometry = network.vertices.length > 0;
25
+ const rebased = hasGeometry ? transformVectorNetwork([
26
+ 1,
27
+ 0,
28
+ -bounds.x,
29
+ 0,
30
+ 1,
31
+ -bounds.y,
32
+ 0,
33
+ 0,
34
+ 1
35
+ ], network) : network;
36
+ figma.graph.updateNode(node.id, {
37
+ x: hasGeometry ? node.x + bounds.x : node.x,
38
+ y: hasGeometry ? node.y + bounds.y : node.y,
39
+ width: hasGeometry ? bounds.width : 0,
40
+ height: hasGeometry ? bounds.height : 0,
41
+ vectorNetwork: rebased,
42
+ fillGeometry: regenerateFillGeometry(rebased, node.fillGeometry, node.cornerRadius),
43
+ strokeGeometry: []
44
+ });
45
+ }
15
46
  const pathGet = defineTool({
16
47
  name: "path_get",
17
48
  description: "Get vector path data of a node.",
@@ -43,10 +74,11 @@ const pathSet = defineTool({
43
74
  path: v.pipe(v.string(), v.description("VectorNetwork JSON"))
44
75
  }),
45
76
  execute: (figma, args) => {
46
- if (!figma.graph.getNode(args.id)) return { error: `Node "${args.id}" not found` };
77
+ const raw = figma.graph.getNode(args.id);
78
+ if (!raw) return { error: `Node "${args.id}" not found` };
47
79
  const parsed = parseVectorNetworkJSON(args.path);
48
80
  if ("error" in parsed) return parsed;
49
- figma.graph.updateNode(args.id, { vectorNetwork: parsed.network });
81
+ writePath(figma, raw, parsed.network);
50
82
  return { id: args.id };
51
83
  }
52
84
  });
@@ -77,7 +109,7 @@ const pathScale = defineTool({
77
109
  segment.tangentEnd.x *= factor;
78
110
  segment.tangentEnd.y *= factor;
79
111
  }
80
- figma.graph.updateNode(id, { vectorNetwork: vn });
112
+ writePath(figma, raw, vn);
81
113
  return {
82
114
  id,
83
115
  factor
@@ -109,7 +141,7 @@ const pathFlip = defineTool({
109
141
  if (axis === "horizontal") segment.tangentEnd.x = -segment.tangentEnd.x;
110
142
  else segment.tangentEnd.y = -segment.tangentEnd.y;
111
143
  }
112
- figma.graph.updateNode(id, { vectorNetwork: vn });
144
+ writePath(figma, raw, vn);
113
145
  return {
114
146
  id,
115
147
  axis
@@ -131,12 +163,12 @@ const pathMove = defineTool({
131
163
  execute: (figma, { id, dx, dy }) => {
132
164
  const result = getVectorNode(figma, id);
133
165
  if ("error" in result) return result;
134
- const { vn } = result;
166
+ const { node: raw, vn } = result;
135
167
  for (const vertex of vn.vertices) {
136
168
  vertex.x += dx;
137
169
  vertex.y += dy;
138
170
  }
139
- figma.graph.updateNode(id, { vectorNetwork: vn });
171
+ writePath(figma, raw, vn);
140
172
  return {
141
173
  id,
142
174
  dx,
@@ -1 +1 @@
1
- {"version":3,"file":"path.js","names":[],"sources":["../../../src/tools/vector/path.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { SceneNode, VectorNetwork } from '@pairdraw/scene-graph'\nimport { cloneVectorNetwork } from '@pairdraw/scene-graph/vector-network'\n\nimport type { FigmaAPI } from '#core/figma-api'\nimport { defineTool, nodeIdInputSchema, nodeInputSchema, toolNumber } from '#core/tools/schema'\nimport { parseVectorNetworkJSON } from '#core/tools/vector/network'\n\nfunction getVectorNode(\n figma: FigmaAPI,\n id: string\n): { node: SceneNode; vn: VectorNetwork } | { error: string } {\n const node = figma.graph.getNode(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n if (!node.vectorNetwork) return { error: `Node \"${id}\" has no vector data` }\n return { node, vn: cloneVectorNetwork(node.vectorNetwork) }\n}\n\nexport const pathGet = defineTool({\n name: 'path_get',\n description: 'Get vector path data of a node.',\n execution: { kind: 'sync', mutation: 'none' },\n exposure: { webmcp: false },\n input: nodeInputSchema,\n execute: (figma, { id }) => {\n const raw = figma.graph.getNode(id)\n if (!raw) return { error: `Node \"${id}\" not found` }\n const vectorNetwork = raw.vectorNetwork\n return vectorNetwork ? { id, vectorNetwork } : { error: `Node \"${id}\" has no vector data` }\n }\n})\n\nexport const pathSet = defineTool({\n name: 'path_set',\n\n description: 'Set vector path data on a node. Provide a VectorNetwork JSON.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n path: v.pipe(v.string(), v.description('VectorNetwork JSON'))\n }),\n execute: (figma, args) => {\n const raw = figma.graph.getNode(args.id)\n if (!raw) return { error: `Node \"${args.id}\" not found` }\n const parsed = parseVectorNetworkJSON(args.path)\n if ('error' in parsed) return parsed\n figma.graph.updateNode(args.id, { vectorNetwork: parsed.network })\n return { id: args.id }\n }\n})\n\nexport const pathScale = defineTool({\n name: 'path_scale',\n\n description: 'Scale vector path from center.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n factor: toolNumber(v.pipe(v.number(), v.description('Scale factor (e.g. 2 for double)')))\n }),\n execute: (figma, { id, factor }) => {\n const result = getVectorNode(figma, id)\n if ('error' in result) return result\n const { node: raw, vn } = result\n const centerX = raw.width / 2\n const centerY = raw.height / 2\n for (const vertex of vn.vertices) {\n vertex.x = centerX + (vertex.x - centerX) * factor\n vertex.y = centerY + (vertex.y - centerY) * factor\n }\n for (const segment of vn.segments) {\n segment.tangentStart.x *= factor\n segment.tangentStart.y *= factor\n segment.tangentEnd.x *= factor\n segment.tangentEnd.y *= factor\n }\n\n figma.graph.updateNode(id, { vectorNetwork: vn })\n return { id, factor }\n }\n})\n\nexport const pathFlip = defineTool({\n name: 'path_flip',\n\n description: 'Flip vector path horizontally or vertically.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n axis: v.pipe(v.picklist(['horizontal', 'vertical']), v.description('Flip axis'))\n }),\n execute: (figma, { id, axis }) => {\n const result = getVectorNode(figma, id)\n if ('error' in result) return result\n const { node: raw, vn } = result\n const width = raw.width\n const height = raw.height\n for (const vertex of vn.vertices) {\n if (axis === 'horizontal') vertex.x = width - vertex.x\n else vertex.y = height - vertex.y\n }\n for (const segment of vn.segments) {\n if (axis === 'horizontal') segment.tangentStart.x = -segment.tangentStart.x\n else segment.tangentStart.y = -segment.tangentStart.y\n if (axis === 'horizontal') segment.tangentEnd.x = -segment.tangentEnd.x\n else segment.tangentEnd.y = -segment.tangentEnd.y\n }\n\n figma.graph.updateNode(id, { vectorNetwork: vn })\n return { id, axis }\n }\n})\n\nexport const pathMove = defineTool({\n name: 'path_move',\n\n description: 'Move all path points by an offset.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n dx: toolNumber(v.pipe(v.number(), v.description('X offset'))),\n dy: toolNumber(v.pipe(v.number(), v.description('Y offset')))\n }),\n execute: (figma, { id, dx, dy }) => {\n const result = getVectorNode(figma, id)\n if ('error' in result) return result\n const { vn } = result\n for (const vertex of vn.vertices) {\n vertex.x += dx\n vertex.y += dy\n }\n\n figma.graph.updateNode(id, { vectorNetwork: vn })\n return { id, dx, dy }\n }\n})\n"],"mappings":";;;;;AASA,SAAS,cACP,OACA,IAC4D;CAC5D,MAAM,OAAO,MAAM,MAAM,QAAQ,EAAE;CACnC,IAAI,CAAC,MAAM,OAAO,EAAE,OAAO,SAAS,GAAG,aAAa;CACpD,IAAI,CAAC,KAAK,eAAe,OAAO,EAAE,OAAO,SAAS,GAAG,sBAAsB;CAC3E,OAAO;EAAE;EAAM,IAAI,mBAAmB,KAAK,aAAa;CAAE;AAC5D;AAEA,MAAa,UAAU,WAAW;CAChC,MAAM;CACN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAO;CAC5C,UAAU,EAAE,QAAQ,MAAM;CAC1B,OAAO;CACP,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,MAAM,MAAM,MAAM,QAAQ,EAAE;EAClC,IAAI,CA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AChD,OAAO,EAAE,aAAa;EACpB,IAAI;EACJ,IAAI,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,UAAU,CAAC,CAAC;EAC5D,IAAI,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,UAAU,CAAC,CAAC;CAC9D,CAAC;CACD,UAAU,OAAO,EAAE,IAAI,IAAI,SAAS;EAClC,MAAM,SAAS,cAAc,OAAO,EAAE;EACtC,IAAI,WAAW,QAAQ,OAAO;EAC9B,MAAM,EAAE,OAAO;EACf,KAAK,MAAM,UAAU,GAAG,UAAU;GAChC,OAAO,KAAK;GACZ,OAAO,KAAK;EACd;EAEA,MAAM,MAAM,WAAW,IAAI,EAAE,eAAe,GAAG,CAAC;EAChD,OAAO;GAAE;GAAI;GAAI;EAAG;CACtB;AACF,CAAC"}
1
+ {"version":3,"file":"path.js","names":[],"sources":["../../../src/tools/vector/path.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { SceneNode, VectorNetwork } from '@pairdraw/scene-graph'\nimport { cloneVectorNetwork, transformVectorNetwork } from '@pairdraw/scene-graph/vector-network'\n\nimport type { FigmaAPI } from '#core/figma-api'\nimport { defineTool, nodeIdInputSchema, nodeInputSchema, toolNumber } from '#core/tools/schema'\nimport { parseVectorNetworkJSON } from '#core/tools/vector/network'\nimport { computeAccurateBounds } from '#core/vector/curve-math'\nimport { regenerateFillGeometry } from '#core/vector/fill-geometry'\n\nfunction getVectorNode(\n figma: FigmaAPI,\n id: string\n): { node: SceneNode; vn: VectorNetwork } | { error: string } {\n const node = figma.graph.getNode(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n if (!node.vectorNetwork) return { error: `Node \"${id}\" has no vector data` }\n return { node, vn: cloneVectorNetwork(node.vectorNetwork) }\n}\n\n/**\n * Writes an edited path as the plugin API's vectorNetwork setter does: the layer's box fits the\n * path, the vertices rebase to it, and imported fillGeometry rebuilds from the new path so fills\n * follow the edit instead of drawing the old shape.\n */\nfunction writePath(figma: FigmaAPI, node: SceneNode, network: VectorNetwork): void {\n const bounds = computeAccurateBounds(network)\n const hasGeometry = network.vertices.length > 0\n const rebased = hasGeometry\n ? transformVectorNetwork([1, 0, -bounds.x, 0, 1, -bounds.y, 0, 0, 1], network)\n : network\n figma.graph.updateNode(node.id, {\n x: hasGeometry ? node.x + bounds.x : node.x,\n y: hasGeometry ? node.y + bounds.y : node.y,\n width: hasGeometry ? bounds.width : 0,\n height: hasGeometry ? bounds.height : 0,\n vectorNetwork: rebased,\n fillGeometry: regenerateFillGeometry(rebased, node.fillGeometry, node.cornerRadius),\n strokeGeometry: []\n })\n}\n\nexport const pathGet = defineTool({\n name: 'path_get',\n description: 'Get vector path data of a node.',\n execution: { kind: 'sync', mutation: 'none' },\n exposure: { webmcp: false },\n input: nodeInputSchema,\n execute: (figma, { id }) => {\n const raw = figma.graph.getNode(id)\n if (!raw) return { error: `Node \"${id}\" not found` }\n const vectorNetwork = raw.vectorNetwork\n return vectorNetwork ? { id, vectorNetwork } : { error: `Node \"${id}\" has no vector data` }\n }\n})\n\nexport const pathSet = defineTool({\n name: 'path_set',\n\n description: 'Set vector path data on a node. Provide a VectorNetwork JSON.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n path: v.pipe(v.string(), v.description('VectorNetwork JSON'))\n }),\n execute: (figma, args) => {\n const raw = figma.graph.getNode(args.id)\n if (!raw) return { error: `Node \"${args.id}\" not found` }\n const parsed = parseVectorNetworkJSON(args.path)\n if ('error' in parsed) return parsed\n writePath(figma, raw, parsed.network)\n return { id: args.id }\n }\n})\n\nexport const pathScale = defineTool({\n name: 'path_scale',\n\n description: 'Scale vector path from center.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n factor: toolNumber(v.pipe(v.number(), v.description('Scale factor (e.g. 2 for double)')))\n }),\n execute: (figma, { id, factor }) => {\n const result = getVectorNode(figma, id)\n if ('error' in result) return result\n const { node: raw, vn } = result\n const centerX = raw.width / 2\n const centerY = raw.height / 2\n for (const vertex of vn.vertices) {\n vertex.x = centerX + (vertex.x - centerX) * factor\n vertex.y = centerY + (vertex.y - centerY) * factor\n }\n for (const segment of vn.segments) {\n segment.tangentStart.x *= factor\n segment.tangentStart.y *= factor\n segment.tangentEnd.x *= factor\n segment.tangentEnd.y *= factor\n }\n\n writePath(figma, raw, vn)\n return { id, factor }\n }\n})\n\nexport const pathFlip = defineTool({\n name: 'path_flip',\n\n description: 'Flip vector path horizontally or vertically.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n axis: v.pipe(v.picklist(['horizontal', 'vertical']), v.description('Flip axis'))\n }),\n execute: (figma, { id, axis }) => {\n const result = getVectorNode(figma, id)\n if ('error' in result) return result\n const { node: raw, vn } = result\n const width = raw.width\n const height = raw.height\n for (const vertex of vn.vertices) {\n if (axis === 'horizontal') vertex.x = width - vertex.x\n else vertex.y = height - vertex.y\n }\n for (const segment of vn.segments) {\n if (axis === 'horizontal') segment.tangentStart.x = -segment.tangentStart.x\n else segment.tangentStart.y = -segment.tangentStart.y\n if (axis === 'horizontal') segment.tangentEnd.x = -segment.tangentEnd.x\n else segment.tangentEnd.y = -segment.tangentEnd.y\n }\n\n writePath(figma, raw, vn)\n return { id, axis }\n }\n})\n\nexport const pathMove = defineTool({\n name: 'path_move',\n\n description: 'Move all path points by an offset.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n dx: toolNumber(v.pipe(v.number(), v.description('X offset'))),\n dy: toolNumber(v.pipe(v.number(), v.description('Y offset')))\n }),\n execute: (figma, { id, dx, dy }) => {\n const result = getVectorNode(figma, id)\n if ('error' in result) return result\n const { node: raw, vn } = result\n for (const vertex of vn.vertices) {\n vertex.x += dx\n vertex.y += dy\n }\n\n writePath(figma, raw, vn)\n return { id, dx, dy }\n }\n})\n"],"mappings":";;;;;;;AAWA,SAAS,cACP,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OAAO,EAAE;EACtC,IAAI,WAAW,QAAQ,OAAO;EAC9B,MAAM,EAAE,MAAM,KAAK,OAAO;EAC1B,KAAK,MAAM,UAAU,GAAG,UAAU;GAChC,OAAO,KAAK;GACZ,OAAO,KAAK;EACd;EAEA,UAAU,OAAO,KAAK,EAAE;EACxB,OAAO;GAAE;GAAI;GAAI;EAAG;CACtB;AACF,CAAC"}
package/dist/xpath.d.ts CHANGED
@@ -2,7 +2,10 @@ import { SceneGraph, SceneNode } from "@pairdraw/scene-graph";
2
2
  //#region src/xpath.d.ts
3
3
  interface XPathQueryOptions {
4
4
  limit?: number;
5
+ /** The name of the page to search; `pageId` takes precedence. */
5
6
  page?: string;
7
+ /** The ID of the page to search. */
8
+ pageId?: string;
6
9
  }
7
10
  declare function queryByXPath(graph: SceneGraph, selector: string, options?: XPathQueryOptions): Promise<SceneNode[]>;
8
11
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"xpath.d.ts","names":[],"sources":["../src/xpath.ts"],"mappings":";;UA+OiB;EACf;EACA;;iBAGoB,aACpB,OAAO,YACP,kBACA,UAAS,oBACR,QAAQ;;;;;;;;;iBAqCK,YAAY,OAAO,YAAY;iBA4CzB,aACpB,OAAO,YACP,kBACA,MAAM,YACL"}
1
+ {"version":3,"file":"xpath.d.ts","names":[],"sources":["../src/xpath.ts"],"mappings":";;UA+OiB;EACf;;EAEA;;EAEA;;iBAGoB,aACpB,OAAO,YACP,kBACA,UAAS,oBACR,QAAQ;;;;;;;;;iBAuCK,YAAY,OAAO,YAAY;iBA4CzB,aACpB,OAAO,YACP,kBACA,MAAM,YACL"}
package/dist/xpath.js CHANGED
@@ -155,7 +155,9 @@ async function loadFontoxpath() {
155
155
  async function queryByXPath(graph, selector, options = {}) {
156
156
  const { limit = 1e3 } = options;
157
157
  const pages = graph.getPages();
158
- const targetPages = options.page ? pages.filter((p) => p.name === options.page) : pages;
158
+ let targetPages = pages;
159
+ if (options.pageId) targetPages = pages.filter((p) => p.id === options.pageId);
160
+ else if (options.page) targetPages = pages.filter((p) => p.name === options.page);
159
161
  if (targetPages.length === 0) return [];
160
162
  const { evaluateXPathToNodes } = await loadFontoxpath();
161
163
  const domFacade = createDomFacade(graph);
package/dist/xpath.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"xpath.js","names":[],"sources":["../src/xpath.ts"],"sourcesContent":["import type * as FontoxpathModule from 'fontoxpath'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { lineHeightPixels, textLengthPixels } from '@pairdraw/scene-graph/text'\n\nconst NODE_TYPES = {\n ELEMENT_NODE: 1,\n ATTRIBUTE_NODE: 2,\n TEXT_NODE: 3,\n DOCUMENT_NODE: 9\n}\n\nconst QUERYABLE_ATTRS = [\n 'id',\n 'name',\n 'width',\n 'height',\n 'x',\n 'y',\n 'visible',\n 'opacity',\n 'cornerRadius',\n 'fontSize',\n 'fontFamily',\n 'fontWeight',\n 'textDirection',\n 'layoutMode',\n 'layoutDirection',\n 'itemSpacing',\n 'paddingTop',\n 'paddingBottom',\n 'paddingLeft',\n 'paddingRight',\n 'strokeWeight',\n 'rotation',\n 'locked',\n 'blendMode',\n 'text',\n 'lineHeight',\n 'letterSpacing'\n]\n\ninterface XPathDocument {\n nodeType: number\n nodeName: string\n documentElement: XPathNode | null\n _children?: XPathNode[]\n}\n\ninterface XPathAttr {\n nodeType: number\n nodeName: string\n name: string\n localName: string\n namespaceURI: null\n prefix: null\n value: string\n ownerElement: XPathNode\n}\n\ninterface XPathNode {\n nodeType: number\n nodeName: string\n localName: string\n namespaceURI: null\n prefix: null\n _sceneNode: SceneNode\n _attrs?: XPathAttr[]\n _parent?: XPathNode | XPathDocument | null\n _children?: XPathNode[]\n}\n\nfunction wrapNode(\n _graph: SceneGraph,\n node: SceneNode,\n parent?: XPathNode | XPathDocument | null\n): XPathNode {\n const wrapped: XPathNode = {\n nodeType: NODE_TYPES.ELEMENT_NODE,\n nodeName: node.type,\n localName: node.type,\n namespaceURI: null,\n prefix: null,\n _sceneNode: node,\n _parent: parent\n }\n return wrapped\n}\n\nfunction createDocument(graph: SceneGraph, rootNode: SceneNode): XPathDocument {\n const doc: XPathDocument = {\n nodeType: NODE_TYPES.DOCUMENT_NODE,\n nodeName: '#document',\n documentElement: null\n }\n const root = wrapNode(graph, rootNode, doc)\n doc.documentElement = root\n doc._children = [root]\n return doc\n}\n\n/** An attribute's value; text lengths compare in pixels, as `fontSize` does. */\nfunction attrValue(node: SceneNode, name: string): unknown {\n if (name === 'lineHeight') return lineHeightPixels(node.lineHeight, node.fontSize)\n if (name === 'letterSpacing') return textLengthPixels(node.letterSpacing, node.fontSize)\n return Reflect.get(node, name)\n}\n\nfunction getAttrs(wrapped: XPathNode): XPathAttr[] {\n if (wrapped._attrs) return wrapped._attrs\n\n const node = wrapped._sceneNode\n const attrs: XPathAttr[] = []\n\n for (const attrName of QUERYABLE_ATTRS) {\n if (attrName in node) {\n const value = attrValue(node, attrName)\n if (value === undefined || value === null || typeof value === 'symbol') continue\n const stringValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'bigint'\n ? String(value)\n : JSON.stringify(value)\n attrs.push({\n nodeType: NODE_TYPES.ATTRIBUTE_NODE,\n nodeName: attrName,\n name: attrName,\n localName: attrName,\n namespaceURI: null,\n prefix: null,\n value: stringValue,\n ownerElement: wrapped\n })\n }\n }\n\n wrapped._attrs = attrs\n return attrs\n}\n\nfunction getChildren(graph: SceneGraph, wrapped: XPathNode): XPathNode[] {\n if (wrapped._children) return wrapped._children\n\n const node = wrapped._sceneNode\n wrapped._children = node.childIds\n .map((id) => graph.getNode(id))\n .filter((n): n is SceneNode => n !== undefined)\n .map((child) => wrapNode(graph, child, wrapped))\n\n return wrapped._children\n}\n\nfunction isDocument(node: unknown): node is XPathDocument {\n return (node as XPathDocument).nodeType === NODE_TYPES.DOCUMENT_NODE\n}\n\nfunction siblingNode(\n graph: SceneGraph,\n node: XPathNode | XPathDocument,\n offset: -1 | 1\n): XPathNode | null {\n if (isDocument(node)) return null\n const parent = node._parent\n if (!parent || isDocument(parent)) return null\n const siblings = getChildren(graph, parent)\n const index = siblings.indexOf(node)\n if (index === -1) return null\n return siblings[index + offset] ?? null\n}\n\nfunction createDomFacade(graph: SceneGraph) {\n return {\n getAllAttributes(node: XPathNode | XPathDocument): XPathAttr[] {\n if (isDocument(node)) return []\n return getAttrs(node)\n },\n\n getAttribute(node: XPathNode | XPathDocument, attributeName: string): string | null {\n if (isDocument(node)) return null\n const sceneNode = node._sceneNode\n if (attributeName in sceneNode) {\n const value = Reflect.get(sceneNode, attributeName)\n if (value === undefined || value === null || typeof value === 'symbol') return null\n return typeof value === 'object'\n ? JSON.stringify(value)\n : String(value as string | number | boolean)\n }\n return null\n },\n\n getChildNodes(node: XPathNode | XPathDocument): XPathNode[] {\n if (isDocument(node)) return node._children ?? []\n return getChildren(graph, node)\n },\n\n getData(node: XPathAttr): string {\n return node.value\n },\n\n getFirstChild(node: XPathNode | XPathDocument): XPathNode | null {\n if (isDocument(node)) return node.documentElement\n const children = getChildren(graph, node)\n return children[0] ?? null\n },\n\n getLastChild(node: XPathNode | XPathDocument): XPathNode | null {\n if (isDocument(node)) return node.documentElement\n const children = getChildren(graph, node)\n return children[children.length - 1] ?? null\n },\n\n getNextSibling(node: XPathNode | XPathDocument): XPathNode | null {\n return siblingNode(graph, node, 1)\n },\n\n getParentNode(node: XPathNode | XPathDocument): XPathNode | XPathDocument | null {\n if (isDocument(node)) return null\n return node._parent ?? null\n },\n\n getPreviousSibling(node: XPathNode | XPathDocument): XPathNode | null {\n return siblingNode(graph, node, -1)\n }\n }\n}\n\ntype Fontoxpath = typeof FontoxpathModule\n\n// fontoxpath is CommonJS. Bundlers and Bun hand its exports out as named\n// exports, but Node's ESM loader exposes them only on `default`.\nasync function loadFontoxpath(): Promise<Fontoxpath> {\n const mod: Partial<Fontoxpath> & { default?: Fontoxpath } = await import('fontoxpath')\n if (mod.evaluateXPathToNodes && mod.evaluateXPathToBoolean) return mod as Fontoxpath\n if (mod.default) return mod.default\n throw new Error('fontoxpath exports not found')\n}\n\nexport interface XPathQueryOptions {\n limit?: number\n page?: string\n}\n\nexport async function queryByXPath(\n graph: SceneGraph,\n selector: string,\n options: XPathQueryOptions = {}\n): Promise<SceneNode[]> {\n const { limit = 1000 } = options\n const pages = graph.getPages()\n const targetPages = options.page ? pages.filter((p) => p.name === options.page) : pages\n\n if (targetPages.length === 0) return []\n\n const { evaluateXPathToNodes } = await loadFontoxpath()\n const domFacade = createDomFacade(graph) as FontoxpathModule.IDomFacade\n const results: SceneNode[] = []\n\n for (const page of targetPages) {\n const doc = createDocument(graph, page)\n const nodes = evaluateXPathToNodes(selector, doc, domFacade)\n\n for (const node of nodes) {\n if (results.length >= limit) break\n const sceneNode = (node as XPathNode)._sceneNode\n if (sceneNode.type !== 'CANVAS') {\n results.push(sceneNode)\n }\n }\n\n if (results.length >= limit) break\n }\n\n return results\n}\n\n/**\n * Build an XPath selector that uniquely identifies a node in its page.\n *\n * Strategy: walk from the node up to the page root, building path segments.\n * Each segment uses the node type as the element name. If the name is\n * unique among siblings of the same type, use `[@name='...']`.\n * Otherwise fall back to a positional predicate `[n]`.\n */\nexport function nodeToXPath(graph: SceneGraph, nodeId: string): string | null {\n const node = graph.getNode(nodeId)\n if (!node) return null\n\n const segments: string[] = []\n let current = node\n\n for (;;) {\n if (current.type === 'CANVAS') break\n const parentId: string | null = current.parentId\n const parent: SceneNode | undefined = parentId ? graph.getNode(parentId) : undefined\n\n segments.unshift(buildSegment(graph, current, parent))\n if (!parent || parent.type === 'CANVAS') break\n current = parent\n }\n\n return segments.length > 0 ? '//' + segments.join('/') : null\n}\n\nfunction buildSegment(graph: SceneGraph, node: SceneNode, parent: SceneNode | undefined): string {\n const tag = node.type\n const escaped = escapeXPathName(node.name)\n\n if (!parent) return `${tag}[@name=${escaped}]`\n\n const siblings = parent.childIds\n .map((id) => graph.getNode(id))\n .filter((n): n is SceneNode => n?.type === tag)\n\n const sameNameCount = siblings.filter((s) => s.name === node.name).length\n if (sameNameCount <= 1) return `${tag}[@name=${escaped}]`\n\n const index = siblings.findIndex((s) => s.id === node.id) + 1\n return `${tag}[${index}]`\n}\n\nfunction escapeXPathName(s: string): string {\n if (!s.includes(\"'\")) return `'${s}'`\n if (!s.includes('\"')) return `\"${s}\"`\n const parts = s.split(\"'\").map((p) => `'${p}'`)\n return `concat(${parts.join(', \"\\'\", ')})`\n}\n\nexport async function matchByXPath(\n graph: SceneGraph,\n selector: string,\n node: SceneNode\n): Promise<boolean> {\n const { evaluateXPathToBoolean } = await loadFontoxpath()\n const domFacade = createDomFacade(graph) as FontoxpathModule.IDomFacade\n const wrapped = wrapNode(graph, node)\n try {\n return evaluateXPathToBoolean(`self::*[${selector}]`, wrapped, domFacade)\n } catch {\n return false\n }\n}\n"],"mappings":";;AAKA,MAAM,aAAa;CACjB,cAAc;CACd,gBAAgB;CAChB,WAAW;CACX,eAAe;AACjB;AAEA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAgCA,SAAS,SACP,QACA,MACA,QACW;CAUX,OAAO;EARL,UAAU,WAAW;EACrB,UAAU,KAAK;EACf,WAAW,KAAK;EAChB,cAAc;EACd,QAAQ;EACR,YAAY;EACZ,SAAS;CAEE;AACf;AAEA,SAAS,eAAe,OAAmB,UAAoC;CAC7E,MAAM,MAAqB;EACzB,UAAU,WAAW;EACrB,UAAU;EACV,iBAAiB;CACnB;CACA,MAAM,OAAO,SAAS,OAAO,UAAU,GAAG;CAC1C,IAAI,kBAAkB;CACtB,IAAI,YAAY,CAAC,IAAI;CACrB,OAAO;AACT;;AAGA,SAAS,UAAU,MAAiB,MAAuB;CACzD,IAAI,SAAS,cAAc,OAAO,iBAAiB,KAAK,YAAY,KAAK,QAAQ;CACjF,I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,MAAM,KAAK;CACjB,MAAM,UAAU,gBAAgB,KAAK,IAAI;CAEzC,IAAI,CAAC,QAAQ,OAAO,GAAG,IAAI,SAAS,QAAQ;CAE5C,MAAM,WAAW,OAAO,SACrB,KAAK,OAAO,MAAM,QAAQ,EAAE,CAAC,CAAC,CAC9B,QAAQ,MAAsB,GAAG,SAAS,GAAG;CAGhD,IADsB,SAAS,QAAQ,MAAM,EAAE,SAAS,KAAK,IAAI,CAAC,CAAC,UAC9C,GAAG,OAAO,GAAG,IAAI,SAAS,QAAQ;CAGvD,OAAO,GAAG,IAAI,GADA,SAAS,WAAW,MAAM,EAAE,OAAO,KAAK,EAAE,IAAI,EACrC;AACzB;AAEA,SAAS,gBAAgB,GAAmB;CAC1C,IAAI,CAAC,EAAE,SAAS,GAAG,GAAG,OAAO,IAAI,EAAE;CACnC,IAAI,CAAC,EAAE,SAAS,IAAG,GAAG,OAAO,IAAI,EAAE;CAEnC,OAAO,UADO,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,MAAM,IAAI,EAAE,EACvB,CAAC,CAAC,KAAK,WAAU,EAAE;AAC1C;AAEA,eAAsB,aACpB,OACA,UACA,MACkB;CAClB,MAAM,EAAE,2BAA2B,MAAM,eAAe;CACxD,MAAM,YAAY,gBAAgB,KAAK;CACvC,MAAM,UAAU,SAAS,OAAO,IAAI;CACpC,IAAI;EACF,OAAO,uBAAuB,WAAW,SAAS,IAAI,SAAS,SAAS;CAC1E,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"xpath.js","names":[],"sources":["../src/xpath.ts"],"sourcesContent":["import type * as FontoxpathModule from 'fontoxpath'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { lineHeightPixels, textLengthPixels } from '@pairdraw/scene-graph/text'\n\nconst NODE_TYPES = {\n ELEMENT_NODE: 1,\n ATTRIBUTE_NODE: 2,\n TEXT_NODE: 3,\n DOCUMENT_NODE: 9\n}\n\nconst QUERYABLE_ATTRS = [\n 'id',\n 'name',\n 'width',\n 'height',\n 'x',\n 'y',\n 'visible',\n 'opacity',\n 'cornerRadius',\n 'fontSize',\n 'fontFamily',\n 'fontWeight',\n 'textDirection',\n 'layoutMode',\n 'layoutDirection',\n 'itemSpacing',\n 'paddingTop',\n 'paddingBottom',\n 'paddingLeft',\n 'paddingRight',\n 'strokeWeight',\n 'rotation',\n 'locked',\n 'blendMode',\n 'text',\n 'lineHeight',\n 'letterSpacing'\n]\n\ninterface XPathDocument {\n nodeType: number\n nodeName: string\n documentElement: XPathNode | null\n _children?: XPathNode[]\n}\n\ninterface XPathAttr {\n nodeType: number\n nodeName: string\n name: string\n localName: string\n namespaceURI: null\n prefix: null\n value: string\n ownerElement: XPathNode\n}\n\ninterface XPathNode {\n nodeType: number\n nodeName: string\n localName: string\n namespaceURI: null\n prefix: null\n _sceneNode: SceneNode\n _attrs?: XPathAttr[]\n _parent?: XPathNode | XPathDocument | null\n _children?: XPathNode[]\n}\n\nfunction wrapNode(\n _graph: SceneGraph,\n node: SceneNode,\n parent?: XPathNode | XPathDocument | null\n): XPathNode {\n const wrapped: XPathNode = {\n nodeType: NODE_TYPES.ELEMENT_NODE,\n nodeName: node.type,\n localName: node.type,\n namespaceURI: null,\n prefix: null,\n _sceneNode: node,\n _parent: parent\n }\n return wrapped\n}\n\nfunction createDocument(graph: SceneGraph, rootNode: SceneNode): XPathDocument {\n const doc: XPathDocument = {\n nodeType: NODE_TYPES.DOCUMENT_NODE,\n nodeName: '#document',\n documentElement: null\n }\n const root = wrapNode(graph, rootNode, doc)\n doc.documentElement = root\n doc._children = [root]\n return doc\n}\n\n/** An attribute's value; text lengths compare in pixels, as `fontSize` does. */\nfunction attrValue(node: SceneNode, name: string): unknown {\n if (name === 'lineHeight') return lineHeightPixels(node.lineHeight, node.fontSize)\n if (name === 'letterSpacing') return textLengthPixels(node.letterSpacing, node.fontSize)\n return Reflect.get(node, name)\n}\n\nfunction getAttrs(wrapped: XPathNode): XPathAttr[] {\n if (wrapped._attrs) return wrapped._attrs\n\n const node = wrapped._sceneNode\n const attrs: XPathAttr[] = []\n\n for (const attrName of QUERYABLE_ATTRS) {\n if (attrName in node) {\n const value = attrValue(node, attrName)\n if (value === undefined || value === null || typeof value === 'symbol') continue\n const stringValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'bigint'\n ? String(value)\n : JSON.stringify(value)\n attrs.push({\n nodeType: NODE_TYPES.ATTRIBUTE_NODE,\n nodeName: attrName,\n name: attrName,\n localName: attrName,\n namespaceURI: null,\n prefix: null,\n value: stringValue,\n ownerElement: wrapped\n })\n }\n }\n\n wrapped._attrs = attrs\n return attrs\n}\n\nfunction getChildren(graph: SceneGraph, wrapped: XPathNode): XPathNode[] {\n if (wrapped._children) return wrapped._children\n\n const node = wrapped._sceneNode\n wrapped._children = node.childIds\n .map((id) => graph.getNode(id))\n .filter((n): n is SceneNode => n !== undefined)\n .map((child) => wrapNode(graph, child, wrapped))\n\n return wrapped._children\n}\n\nfunction isDocument(node: unknown): node is XPathDocument {\n return (node as XPathDocument).nodeType === NODE_TYPES.DOCUMENT_NODE\n}\n\nfunction siblingNode(\n graph: SceneGraph,\n node: XPathNode | XPathDocument,\n offset: -1 | 1\n): XPathNode | null {\n if (isDocument(node)) return null\n const parent = node._parent\n if (!parent || isDocument(parent)) return null\n const siblings = getChildren(graph, parent)\n const index = siblings.indexOf(node)\n if (index === -1) return null\n return siblings[index + offset] ?? null\n}\n\nfunction createDomFacade(graph: SceneGraph) {\n return {\n getAllAttributes(node: XPathNode | XPathDocument): XPathAttr[] {\n if (isDocument(node)) return []\n return getAttrs(node)\n },\n\n getAttribute(node: XPathNode | XPathDocument, attributeName: string): string | null {\n if (isDocument(node)) return null\n const sceneNode = node._sceneNode\n if (attributeName in sceneNode) {\n const value = Reflect.get(sceneNode, attributeName)\n if (value === undefined || value === null || typeof value === 'symbol') return null\n return typeof value === 'object'\n ? JSON.stringify(value)\n : String(value as string | number | boolean)\n }\n return null\n },\n\n getChildNodes(node: XPathNode | XPathDocument): XPathNode[] {\n if (isDocument(node)) return node._children ?? []\n return getChildren(graph, node)\n },\n\n getData(node: XPathAttr): string {\n return node.value\n },\n\n getFirstChild(node: XPathNode | XPathDocument): XPathNode | null {\n if (isDocument(node)) return node.documentElement\n const children = getChildren(graph, node)\n return children[0] ?? null\n },\n\n getLastChild(node: XPathNode | XPathDocument): XPathNode | null {\n if (isDocument(node)) return node.documentElement\n const children = getChildren(graph, node)\n return children[children.length - 1] ?? null\n },\n\n getNextSibling(node: XPathNode | XPathDocument): XPathNode | null {\n return siblingNode(graph, node, 1)\n },\n\n getParentNode(node: XPathNode | XPathDocument): XPathNode | XPathDocument | null {\n if (isDocument(node)) return null\n return node._parent ?? null\n },\n\n getPreviousSibling(node: XPathNode | XPathDocument): XPathNode | null {\n return siblingNode(graph, node, -1)\n }\n }\n}\n\ntype Fontoxpath = typeof FontoxpathModule\n\n// fontoxpath is CommonJS. Bundlers and Bun hand its exports out as named\n// exports, but Node's ESM loader exposes them only on `default`.\nasync function loadFontoxpath(): Promise<Fontoxpath> {\n const mod: Partial<Fontoxpath> & { default?: Fontoxpath } = await import('fontoxpath')\n if (mod.evaluateXPathToNodes && mod.evaluateXPathToBoolean) return mod as Fontoxpath\n if (mod.default) return mod.default\n throw new Error('fontoxpath exports not found')\n}\n\nexport interface XPathQueryOptions {\n limit?: number\n /** The name of the page to search; `pageId` takes precedence. */\n page?: string\n /** The ID of the page to search. */\n pageId?: string\n}\n\nexport async function queryByXPath(\n graph: SceneGraph,\n selector: string,\n options: XPathQueryOptions = {}\n): Promise<SceneNode[]> {\n const { limit = 1000 } = options\n const pages = graph.getPages()\n let targetPages = pages\n if (options.pageId) targetPages = pages.filter((p) => p.id === options.pageId)\n else if (options.page) targetPages = pages.filter((p) => p.name === options.page)\n\n if (targetPages.length === 0) return []\n\n const { evaluateXPathToNodes } = await loadFontoxpath()\n const domFacade = createDomFacade(graph) as FontoxpathModule.IDomFacade\n const results: SceneNode[] = []\n\n for (const page of targetPages) {\n const doc = createDocument(graph, page)\n const nodes = evaluateXPathToNodes(selector, doc, domFacade)\n\n for (const node of nodes) {\n if (results.length >= limit) break\n const sceneNode = (node as XPathNode)._sceneNode\n if (sceneNode.type !== 'CANVAS') {\n results.push(sceneNode)\n }\n }\n\n if (results.length >= limit) break\n }\n\n return results\n}\n\n/**\n * Build an XPath selector that uniquely identifies a node in its page.\n *\n * Strategy: walk from the node up to the page root, building path segments.\n * Each segment uses the node type as the element name. If the name is\n * unique among siblings of the same type, use `[@name='...']`.\n * Otherwise fall back to a positional predicate `[n]`.\n */\nexport function nodeToXPath(graph: SceneGraph, nodeId: string): string | null {\n const node = graph.getNode(nodeId)\n if (!node) return null\n\n const segments: string[] = []\n let current = node\n\n for (;;) {\n if (current.type === 'CANVAS') break\n const parentId: string | null = current.parentId\n const parent: SceneNode | undefined = parentId ? graph.getNode(parentId) : undefined\n\n segments.unshift(buildSegment(graph, current, parent))\n if (!parent || parent.type === 'CANVAS') break\n current = parent\n }\n\n return segments.length > 0 ? '//' + segments.join('/') : null\n}\n\nfunction buildSegment(graph: SceneGraph, node: SceneNode, parent: SceneNode | undefined): string {\n const tag = node.type\n const escaped = escapeXPathName(node.name)\n\n if (!parent) return `${tag}[@name=${escaped}]`\n\n const siblings = parent.childIds\n .map((id) => graph.getNode(id))\n .filter((n): n is SceneNode => n?.type === tag)\n\n const sameNameCount = siblings.filter((s) => s.name === node.name).length\n if (sameNameCount <= 1) return `${tag}[@name=${escaped}]`\n\n const index = siblings.findIndex((s) => s.id === node.id) + 1\n return `${tag}[${index}]`\n}\n\nfunction escapeXPathName(s: string): string {\n if (!s.includes(\"'\")) return `'${s}'`\n if (!s.includes('\"')) return `\"${s}\"`\n const parts = s.split(\"'\").map((p) => `'${p}'`)\n return `concat(${parts.join(', \"\\'\", ')})`\n}\n\nexport async function matchByXPath(\n graph: SceneGraph,\n selector: string,\n node: SceneNode\n): Promise<boolean> {\n const { evaluateXPathToBoolean } = await loadFontoxpath()\n const domFacade = createDomFacade(graph) as FontoxpathModule.IDomFacade\n const wrapped = wrapNode(graph, node)\n try {\n return evaluateXPathToBoolean(`self::*[${selector}]`, wrapped, domFacade)\n } catch {\n return false\n }\n}\n"],"mappings":";;AAKA,MAAM,aAAa;CACjB,cAAc;CACd,gBAAgB;CAChB,WAAW;CACX,eAAe;AACjB;AAEA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAgCA,SAAS,SACP,QACA,MACA,QACW;CAUX,OAAO;EARL,UAAU,WAAW;EACrB,UAAU,KAAK;EACf,WAAW,KAAK;EAChB,cAAc;EACd,QAAQ;EACR,YAAY;EACZ,SAAS;CAEE;AACf;AAEA,SAAS,eAAe,OAAmB,UAAoC;CAC7E,MAAM,MAAqB;EACzB,UAAU,WAAW;EACrB,UAAU;EACV,iBAAiB;CACnB;CACA,MAAM,OAAO,SAAS,OAAO,UAAU,GAAG;CAC1C,IAAI,kBAAkB;CACtB,IAAI,YAAY,CAAC,IAAI;CACrB,OAAO;AACT;;AAGA,SAAS,UAAU,MAAiB,MAAuB;CACzD,IAAI,SAAS,cAAc,OAAO,iBAAiB,KAAK,YAAY,KAAK,QAAQ;CACjF,IAAI,SAAS,iBAAiB,OAAO,iBAAiB,KAAK,eAAe,KAAK,QAAQ;CACvF,OAAO,QAAQ,IAAI,MAAM,IAAI;AAC/B;AAEA,SAAS,SAAS,SAAiC;CACjD,IAAI,QAAQ,QAAQ,OAAO,QAAQ;CAEnC,MAAM,OAAO,QAAQ;CACrB,MAAM,QAAqB,CAAC;CAE5B,KAAK,MAAM,YAAY,iBACrB,IAAI,YAAY,MAAM;EACpB,MAAM,QAAQ,UAAU,MAAM,QAAQ;EACtC,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,OAAO,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KAAK,IAAI,CAAC,CAAC,UAC9C,GAAG,OAAO,GAAG,IAAI,SAAS,QAAQ;CAGvD,OAAO,GAAG,IAAI,GADA,SAAS,WAAW,MAAM,EAAE,OAAO,KAAK,EAAE,IAAI,EACrC;AACzB;AAEA,SAAS,gBAAgB,GAAmB;CAC1C,IAAI,CAAC,EAAE,SAAS,GAAG,GAAG,OAAO,IAAI,EAAE;CACnC,IAAI,CAAC,EAAE,SAAS,IAAG,GAAG,OAAO,IAAI,EAAE;CAEnC,OAAO,UADO,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,MAAM,IAAI,EAAE,EACvB,CAAC,CAAC,KAAK,WAAU,EAAE;AAC1C;AAEA,eAAsB,aACpB,OACA,UACA,MACkB;CAClB,MAAM,EAAE,2BAA2B,MAAM,eAAe;CACxD,MAAM,YAAY,gBAAgB,KAAK;CACvC,MAAM,UAAU,SAAS,OAAO,IAAI;CACpC,IAAI;EACF,OAAO,uBAAuB,WAAW,SAAS,IAAI,SAAS,SAAS;CAC1E,QAAQ;EACN,OAAO;CACT;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/core",
3
- "version": "0.19.1",
3
+ "version": "0.19.2",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -11,14 +11,14 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "dependencies": {
13
13
  "@iconify/utils": "^3.1.4",
14
- "@pairdraw/design-jsx": "^0.19.1",
15
- "@pairdraw/dom-css": "^0.19.1",
16
- "@pairdraw/drawio": "^0.19.1",
17
- "@pairdraw/fig": "^0.19.1",
18
- "@pairdraw/kiwi": "^0.19.1",
19
- "@pairdraw/mermaid": "^0.19.1",
20
- "@pairdraw/pen": "^0.19.1",
21
- "@pairdraw/scene-graph": "^0.19.1",
14
+ "@pairdraw/design-jsx": "^0.19.2",
15
+ "@pairdraw/dom-css": "^0.19.2",
16
+ "@pairdraw/drawio": "^0.19.2",
17
+ "@pairdraw/fig": "^0.19.2",
18
+ "@pairdraw/kiwi": "^0.19.2",
19
+ "@pairdraw/mermaid": "^0.19.2",
20
+ "@pairdraw/pen": "^0.19.2",
21
+ "@pairdraw/scene-graph": "^0.19.2",
22
22
  "@tauri-apps/api": "^2.12.1",
23
23
  "@valibot/to-json-schema": "^1.8.0",
24
24
  "@xmldom/xmldom": "^0.9.12",
@@ -1,5 +1,4 @@
1
1
  export {
2
- drawEnteredContainer,
3
2
  drawGroupBounds,
4
3
  drawHandle,
5
4
  drawHoverHighlight,
@@ -28,7 +28,7 @@ import {
28
28
  } from '#core/geometry'
29
29
  import { pointAtArc, textPathStartArc } from '#core/text/path'
30
30
 
31
- import { inNodeSpace, outlineNode, withScreenStroke } from './outline'
31
+ import { inNodeSpace, withScreenStroke } from './outline'
32
32
 
33
33
  /** The dash of faint selection bounds, in screen pixels. */
34
34
  const SELECTION_DASH = [4, 4] as const
@@ -79,17 +79,6 @@ export function drawCodeFocus(
79
79
  })
80
80
  }
81
81
 
82
- export function drawEnteredContainer(
83
- r: SkiaRenderer,
84
- canvas: Canvas,
85
- graph: SceneGraph,
86
- enteredContainerId?: string | null,
87
- preview?: RotationPreview | null
88
- ): void {
89
- const stroke = { color: r.selColor(SELECTION_DASH_ALPHA), dash: SELECTION_DASH }
90
- outlineNode(r, canvas, graph, enteredContainerId, stroke, preview)
91
- }
92
-
93
82
  /** Single-node selection overlay: path-text curve/band for imported TEXT_PATH,
94
83
  * the standard rect+handles otherwise. */
95
84
  function drawSingleSelection(
@@ -21,6 +21,7 @@ import {
21
21
  } from '#core/constants'
22
22
  import { withTextMeasurer } from '#core/layout/text-measurement'
23
23
  import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'
24
+ import { resetFontCollection } from '#core/text/font/collection'
24
25
  import { fontManager } from '#core/text/font/manager'
25
26
  import { prepareGraphFonts } from '#core/text/prepare'
26
27
  import {
@@ -112,6 +113,7 @@ function registerSectionTitleFont(r: SkiaRenderer, data: ArrayBuffer) {
112
113
  if (provider && !sectionTitleProviders.has(provider)) {
113
114
  sectionTitleProviders.add(provider)
114
115
  provider.registerFont(data, SECTION_TITLE_FONT_FAMILY)
116
+ resetFontCollection(provider)
115
117
  fontManager.registerFontInBrowser(SECTION_TITLE_FONT_FAMILY, 'SemiBold', data)
116
118
  }
117
119
  const typeface = r.ck.Typeface.MakeFreeTypeFaceFromData(data)
@@ -40,15 +40,6 @@ const rendererMethods = {
40
40
  Overlays.drawMeasurements(this, canvas, graph, selectedIds, targetId)
41
41
  },
42
42
 
43
- drawEnteredContainer(
44
- canvas: Canvas,
45
- graph: SceneGraph,
46
- enteredContainerId?: string | null,
47
- preview?: RenderOverlays['rotationPreview']
48
- ): void {
49
- Overlays.drawEnteredContainer(this, canvas, graph, enteredContainerId, preview)
50
- },
51
-
52
43
  drawSelection(
53
44
  canvas: Canvas,
54
45
  graph: SceneGraph,
@@ -93,7 +93,6 @@ export function drawOverlayPass(
93
93
  if (!measuring) drawPrototypeConnections(r, canvas, graph, selectedIds, overlays.rotationPreview)
94
94
  r.drawHoverHighlight(canvas, graph, hoveredNodeId, overlays.rotationPreview)
95
95
  drawIssueHighlight(r, canvas, graph, overlays.designIssueHighlight, overlays.rotationPreview)
96
- r.drawEnteredContainer(canvas, graph, overlays.enteredContainerId, overlays.rotationPreview)
97
96
  drawDropTarget(r, canvas, graph, overlays.dropTargetId, overlays.rotationPreview)
98
97
  drawConnectorTarget(r, canvas, graph, overlays.connectorTarget, overlays.rotationPreview)
99
98
  drawEditingText(r, canvas, graph, overlays)
@@ -102,7 +102,6 @@ export function renderFromEditorState(
102
102
  imageEdit: state.imageEdit,
103
103
  transforming: state.transforming,
104
104
  measurementMode: state.measurementMode,
105
- enteredContainerId: state.enteredContainerId,
106
105
  editingTextId: state.editingTextId,
107
106
  renamingLabelId: state.renamingLabelId,
108
107
  textEditor: textEditor as RenderOverlays['textEditor'],
@@ -53,7 +53,6 @@ export interface RenderOverlays {
53
53
  imageEdit?: ImageEdit | null
54
54
  transforming?: boolean
55
55
  measurementMode?: MeasurementMode
56
- enteredContainerId?: string | null
57
56
  editingTextId?: string | null
58
57
  /** The layer whose name a field over the canvas renames, whose title the canvas leaves out. */
59
58
  renamingLabelId?: string | null
@@ -280,7 +280,6 @@ export class SkiaRenderer {
280
280
 
281
281
  declare drawHoverHighlight: RendererDomainMethods['drawHoverHighlight']
282
282
  declare drawMeasurements: RendererDomainMethods['drawMeasurements']
283
- declare drawEnteredContainer: RendererDomainMethods['drawEnteredContainer']
284
283
  declare drawSelection: RendererDomainMethods['drawSelection']
285
284
  declare drawNodeSelection: RendererDomainMethods['drawNodeSelection']
286
285
  declare drawSelectionLabels: RendererDomainMethods['drawSelectionLabels']
@@ -1,4 +1,4 @@
1
- export { designJSXRenderer, renderJSX, renderTree } from './renderer'
1
+ export { designJSXRenderer, renderJSX, renderRoots, renderTree } from './renderer'
2
2
  export {
3
3
  finishRenderPlacement,
4
4
  resolveRenderPlacement,
@@ -74,4 +74,4 @@ export function designJSXRenderer(icons: IconProvider = defaultIcons) {
74
74
  }
75
75
 
76
76
  /** Design JSX rendering with Iconify's icons. */
77
- export const { renderJSX, renderTree } = designJSXRenderer()
77
+ export const { renderJSX, renderRoots, renderTree } = designJSXRenderer()
@@ -1,3 +1,5 @@
1
+ import { uniqBy } from 'es-toolkit'
2
+
1
3
  import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
2
4
  import { styleRunReferences } from '@pairdraw/scene-graph/text'
3
5
  import { captureAppliedBoundPaints, type AppliedBoundPaints } from '@pairdraw/scene-graph/variables'
@@ -65,14 +67,29 @@ export function captureClipboardSnapshot(
65
67
  }
66
68
  return { ...structuredClone(node), children: graph.getChildren(node.id).map(capture) }
67
69
  }
68
- const nodes = roots.map(capture)
70
+ // A variant cannot stand without its set: its variant properties, the values each variant sets,
71
+ // and the properties the set defines live there. Copying selected variants brings the set, as
72
+ // Figma does, and two variants of one set bring it once.
73
+ const copiedRoots = uniqBy(
74
+ roots.map((node) => {
75
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
76
+ return node.type === 'COMPONENT' && parent?.type === 'COMPONENT_SET' ? parent : node
77
+ }),
78
+ (node) => node.id
79
+ )
80
+ const nodes = copiedRoots.map(capture)
69
81
  const componentDependencies = new Map<string, ClipboardNodeTree>()
70
82
  function captureComponent(id: string) {
71
83
  if (componentDependencies.has(id) || selectedIds.has(id)) return
72
84
  const component = graph.getNode(id)
73
85
  if (!component || (component.type !== 'COMPONENT' && component.type !== 'COMPONENT_SET')) return
74
- const tree = capture(component)
75
- componentDependencies.set(id, tree)
86
+ // A variant travels as its set: the variant properties, the values each variant sets, and the
87
+ // properties defined on the set live there, so a copy of one variant without it cannot switch.
88
+ const parent = component.parentId ? graph.getNode(component.parentId) : undefined
89
+ const carried = parent?.type === 'COMPONENT_SET' ? parent : component
90
+ if (componentDependencies.has(carried.id) || selectedIds.has(carried.id)) return
91
+ const tree = capture(carried)
92
+ componentDependencies.set(carried.id, tree)
76
93
  visitReferences(tree)
77
94
  }
78
95
  function visitReferences(node: ClipboardNodeTree) {
@@ -91,7 +108,7 @@ export function captureClipboardSnapshot(
91
108
  styleDefinitions,
92
109
  variableDependencies: captureClipboardVariables(graph, capturedNodes),
93
110
  nodes,
94
- placement: clipboardPlacement(graph, roots),
111
+ placement: clipboardPlacement(graph, copiedRoots),
95
112
  images,
96
113
  appliedBoundPaints: captureAppliedBoundPaints(
97
114
  graph,
@@ -130,15 +130,9 @@ export function createClipboardActions(ctx: EditorContext) {
130
130
  const stack = () => {
131
131
  for (const { id, parentId, index } of stacking) ctx.graph.insertChildAt(id, parentId, index)
132
132
  }
133
- // Auto layout parents lay out again, so a copy joins the flow and a hugging parent resizes.
134
- // Undo and redo do it too, because neither stores the parent's layout. Other parents, such
135
- // as the page, are skipped: laying out a page reaches every frame on it.
136
- const layoutParentIds = [...new Set(parents)].filter(
137
- (id) => ctx.graph.getNode(id)?.layoutMode !== 'NONE'
138
- )
139
- const relayoutParents = () => {
140
- for (const parentId of layoutParentIds) ctx.runLayoutForNode(parentId)
141
- }
133
+ // A copy joins its parent's flow and a hugging parent resizes, on undo and redo too, since
134
+ // neither stores the parent's layout.
135
+ const relayoutParents = () => ctx.runLayoutForParents(parents)
142
136
  stack()
143
137
 
144
138
  if (newRootIds.length > 0) {
@@ -540,11 +534,7 @@ export function createClipboardActions(ctx: EditorContext) {
540
534
  subtree: snapshotSubtree(ctx.graph, entry.id)
541
535
  }))
542
536
 
543
- const relayoutParents = () => {
544
- for (const parentId of new Set(entries.map((entry) => entry.parentId))) {
545
- ctx.runLayoutForNode(parentId)
546
- }
547
- }
537
+ const relayoutParents = () => ctx.runLayoutForParents(entries.map((entry) => entry.parentId))
548
538
  hideLayers()
549
539
 
550
540
  const prevSelection = new Set(ctx.state.selectedIds)
@@ -1,64 +1,72 @@
1
- import type { DocumentColorSpace, SceneNode } from '@pairdraw/scene-graph'
2
- import { resolveOkHCLForPreview, rgbaToOkHCL } from '@pairdraw/scene-graph/color'
1
+ import type { DocumentColorSpace, Fill, SceneNode } from '@pairdraw/scene-graph'
2
+ import { okhclToRGBA, rgbaToOkHCL } from '@pairdraw/scene-graph/color'
3
3
  import { copyEffects, copyFill, copyStyleRuns, copyStroke } from '@pairdraw/scene-graph/copy'
4
4
 
5
5
  import type { EditorContext } from './types'
6
6
 
7
7
  export type DocumentColorProfileMode = 'assign' | 'convert'
8
8
 
9
- function remapColor(color: SceneNode['fills'][number]['color'], target: DocumentColorSpace) {
10
- return resolveOkHCLForPreview(rgbaToOkHCL(color), { documentColorSpace: target }).color
9
+ function remapColor(
10
+ color: SceneNode['fills'][number]['color'],
11
+ source: DocumentColorSpace,
12
+ target: DocumentColorSpace
13
+ ) {
14
+ if (source === target) return color
15
+ return okhclToRGBA(rgbaToOkHCL(color, source), target)
16
+ }
17
+
18
+ /** A paint's colours in the target space: the base colour, a gradient's stops, and mesh points. */
19
+ function remapPaint<T extends Fill>(
20
+ next: T,
21
+ fill: T,
22
+ source: DocumentColorSpace,
23
+ target: DocumentColorSpace
24
+ ): T {
25
+ const resolved = remapColor(fill.color, source, target)
26
+ next.color = resolved
27
+ if (fill.type === 'SOLID') next.opacity = resolved.a
28
+ if (fill.gradientStops)
29
+ next.gradientStops = fill.gradientStops.map((stop) => ({
30
+ ...stop,
31
+ color: remapColor(stop.color, source, target)
32
+ }))
33
+ if (fill.meshPoints)
34
+ next.meshPoints = fill.meshPoints.map((point) => ({
35
+ ...point,
36
+ color: remapColor(point.color, source, target)
37
+ }))
38
+ return next
39
+ }
40
+
41
+ function remapFill(fill: Fill, source: DocumentColorSpace, target: DocumentColorSpace): Fill {
42
+ return remapPaint(copyFill(fill), fill, source, target)
11
43
  }
12
44
 
13
45
  function remapNodeColors(
14
46
  node: SceneNode,
47
+ source: DocumentColorSpace,
15
48
  target: DocumentColorSpace,
16
49
  mode: DocumentColorProfileMode
17
50
  ): Partial<SceneNode> | null {
18
51
  if (mode === 'assign') return null
19
52
 
20
- const fills = node.fills.map((fill) => {
21
- const next = copyFill(fill)
22
- if (fill.type === 'SOLID') {
23
- const resolved = remapColor(fill.color, target)
24
- next.color = resolved
25
- next.opacity = resolved.a
26
- return next
27
- }
28
- if (fill.gradientStops) {
29
- next.gradientStops = fill.gradientStops.map((stop) => ({
30
- ...stop,
31
- color: remapColor(stop.color, target)
32
- }))
33
- }
34
- return next
35
- })
53
+ const fills = node.fills.map((fill) => remapFill(fill, source, target))
36
54
 
37
- const strokes = node.strokes.map((stroke) => {
38
- const next = copyStroke(stroke)
39
- const resolved = remapColor(stroke.color, target)
40
- next.color = resolved
41
- next.opacity = resolved.a
42
- return next
43
- })
55
+ const strokes = node.strokes.map((stroke) =>
56
+ remapPaint(copyStroke(stroke), stroke, source, target)
57
+ )
44
58
 
45
59
  const effects = copyEffects(node.effects).map((effect) =>
46
- effect.type === 'SHADER' ? effect : { ...effect, color: remapColor(effect.color, target) }
60
+ effect.type === 'SHADER'
61
+ ? effect
62
+ : { ...effect, color: remapColor(effect.color, source, target) }
47
63
  )
48
64
 
49
65
  const styleRuns = copyStyleRuns(node.styleRuns).map((run) => ({
50
66
  ...run,
51
67
  style: {
52
68
  ...run.style,
53
- fills: run.style.fills?.map((fill) => {
54
- const next = copyFill(fill)
55
- if (fill.type === 'SOLID') {
56
- const resolved = remapColor(fill.color, target)
57
- next.color = resolved
58
- next.opacity = resolved.a
59
- }
60
- return next
61
- })
69
+ fills: run.style.fills?.map((fill) => remapFill(fill, source, target))
62
70
  }
63
71
  }))
64
72
 
@@ -73,8 +81,9 @@ export function createColorSpaceActions(ctx: EditorContext) {
73
81
  if (ctx.graph.documentColorSpace === colorSpace) return
74
82
 
75
83
  if (mode === 'convert') {
84
+ const source = ctx.graph.documentColorSpace
76
85
  for (const node of ctx.graph.getAllNodes()) {
77
- const changes = remapNodeColors(node, colorSpace, mode)
86
+ const changes = remapNodeColors(node, source, colorSpace, mode)
78
87
  if (changes) ctx.graph.updateNode(node.id, changes)
79
88
  }
80
89
  }