@pairdraw/core 0.16.2 → 0.18.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 (257) hide show
  1. package/dist/canvas/outline-stroke.d.ts.map +1 -1
  2. package/dist/canvas/outline-stroke.js.map +1 -1
  3. package/dist/canvas/overlays/prototype.d.ts +2 -5
  4. package/dist/canvas/overlays/prototype.d.ts.map +1 -1
  5. package/dist/canvas/overlays/prototype.js +3 -19
  6. package/dist/canvas/overlays/prototype.js.map +1 -1
  7. package/dist/canvas/renderer/fonts.js +2 -1
  8. package/dist/canvas/renderer/fonts.js.map +1 -1
  9. package/dist/canvas/renderer.d.ts +4 -0
  10. package/dist/canvas/renderer.d.ts.map +1 -1
  11. package/dist/canvas/renderer.js +4 -0
  12. package/dist/canvas/renderer.js.map +1 -1
  13. package/dist/canvas/rulers.js +1 -1
  14. package/dist/canvas/rulers.js.map +1 -1
  15. package/dist/canvas/scene.d.ts.map +1 -1
  16. package/dist/canvas/scene.js +61 -37
  17. package/dist/canvas/scene.js.map +1 -1
  18. package/dist/canvas/text/font-families.d.ts +4 -3
  19. package/dist/canvas/text/font-families.d.ts.map +1 -1
  20. package/dist/canvas/text/font-families.js +8 -7
  21. package/dist/canvas/text/font-families.js.map +1 -1
  22. package/dist/canvas/text/index.d.ts.map +1 -1
  23. package/dist/canvas/text/index.js +1 -1
  24. package/dist/canvas/text/index.js.map +1 -1
  25. package/dist/canvas/text/paragraph/index.js +2 -2
  26. package/dist/canvas/text/paragraph/index.js.map +1 -1
  27. package/dist/canvas/text/placed.js +2 -2
  28. package/dist/canvas/text/placed.js.map +1 -1
  29. package/dist/canvas/text/renderer.d.ts +2 -0
  30. package/dist/canvas/text/renderer.d.ts.map +1 -1
  31. package/dist/clipboard/pairdraw.d.ts.map +1 -1
  32. package/dist/clipboard/pairdraw.js +53 -7
  33. package/dist/clipboard/pairdraw.js.map +1 -1
  34. package/dist/design-jsx/preview/picture.js +6 -1
  35. package/dist/design-jsx/preview/picture.js.map +1 -1
  36. package/dist/design-jsx/renderer.d.ts.map +1 -1
  37. package/dist/editor/alignment.d.ts.map +1 -1
  38. package/dist/editor/alignment.js +35 -27
  39. package/dist/editor/alignment.js.map +1 -1
  40. package/dist/editor/bridges/undo.d.ts +1 -1
  41. package/dist/editor/clipboard/detach.d.ts.map +1 -1
  42. package/dist/editor/clipboard/detach.js +3 -3
  43. package/dist/editor/clipboard/detach.js.map +1 -1
  44. package/dist/editor/clipboard/paste/properties.d.ts.map +1 -1
  45. package/dist/editor/clipboard/paste/properties.js +3 -1
  46. package/dist/editor/clipboard/paste/properties.js.map +1 -1
  47. package/dist/editor/create.d.ts +1 -1
  48. package/dist/editor/structure.d.ts.map +1 -1
  49. package/dist/editor/structure.js +3 -1
  50. package/dist/editor/structure.js.map +1 -1
  51. package/dist/editor/viewport.js +2 -2
  52. package/dist/editor/viewport.js.map +1 -1
  53. package/dist/figma-api/index.d.ts +43 -8
  54. package/dist/figma-api/index.d.ts.map +1 -1
  55. package/dist/figma-api/index.js +48 -6
  56. package/dist/figma-api/index.js.map +1 -1
  57. package/dist/figma-api/serialization.js +10 -0
  58. package/dist/figma-api/serialization.js.map +1 -1
  59. package/dist/figma-api/text/bindings.d.ts.map +1 -1
  60. package/dist/figma-api/text/bindings.js +20 -8
  61. package/dist/figma-api/text/bindings.js.map +1 -1
  62. package/dist/figma-api/text/index.js +1 -1
  63. package/dist/geometry/connectors.js +2 -14
  64. package/dist/geometry/connectors.js.map +1 -1
  65. package/dist/geometry/index.d.ts +2 -2
  66. package/dist/geometry/scene.d.ts +3 -1
  67. package/dist/geometry/scene.d.ts.map +1 -1
  68. package/dist/geometry/scene.js +16 -1
  69. package/dist/geometry/scene.js.map +1 -1
  70. package/dist/geometry/types.d.ts +7 -1
  71. package/dist/geometry/types.d.ts.map +1 -1
  72. package/dist/io/formats/drawio/export.d.ts.map +1 -1
  73. package/dist/io/formats/drawio/export.js +10 -0
  74. package/dist/io/formats/drawio/export.js.map +1 -1
  75. package/dist/io/formats/drawio/index.d.ts.map +1 -1
  76. package/dist/io/formats/drawio/index.js +32 -1
  77. package/dist/io/formats/drawio/index.js.map +1 -1
  78. package/dist/io/formats/drawio/shapes.d.ts +10 -5
  79. package/dist/io/formats/drawio/shapes.d.ts.map +1 -1
  80. package/dist/io/formats/drawio/shapes.js +10 -6
  81. package/dist/io/formats/drawio/shapes.js.map +1 -1
  82. package/dist/io/formats/drawio/warnings.d.ts +11 -0
  83. package/dist/io/formats/drawio/warnings.d.ts.map +1 -0
  84. package/dist/io/formats/drawio/warnings.js +23 -0
  85. package/dist/io/formats/drawio/warnings.js.map +1 -0
  86. package/dist/io/formats/pdf/dom.d.ts +10 -1
  87. package/dist/io/formats/pdf/dom.d.ts.map +1 -1
  88. package/dist/io/formats/pdf/dom.js +31 -1
  89. package/dist/io/formats/pdf/dom.js.map +1 -1
  90. package/dist/io/formats/pdf/export.js +3 -2
  91. package/dist/io/formats/pdf/export.js.map +1 -1
  92. package/dist/io/formats/raster/headless.d.ts +2 -2
  93. package/dist/io/formats/raster/headless.d.ts.map +1 -1
  94. package/dist/io/formats/raster/headless.js +2 -2
  95. package/dist/io/formats/raster/headless.js.map +1 -1
  96. package/dist/io/formats/raster/render.d.ts +1 -1
  97. package/dist/io/formats/raster/render.d.ts.map +1 -1
  98. package/dist/io/formats/raster/render.js +2 -2
  99. package/dist/io/formats/raster/render.js.map +1 -1
  100. package/dist/io/formats.d.ts.map +1 -1
  101. package/dist/io/formats.js +6 -6
  102. package/dist/io/formats.js.map +1 -1
  103. package/dist/io/registry.d.ts +2 -0
  104. package/dist/io/registry.d.ts.map +1 -1
  105. package/dist/io/registry.js +5 -0
  106. package/dist/io/registry.js.map +1 -1
  107. package/dist/io/types.d.ts +2 -0
  108. package/dist/io/types.d.ts.map +1 -1
  109. package/dist/library/snapshot.d.ts.map +1 -1
  110. package/dist/library/snapshot.js +1 -0
  111. package/dist/library/snapshot.js.map +1 -1
  112. package/dist/lint/linter.d.ts.map +1 -1
  113. package/dist/lint/linter.js +11 -2
  114. package/dist/lint/linter.js.map +1 -1
  115. package/dist/rpc/variables-command.d.ts.map +1 -1
  116. package/dist/rpc/variables-command.js +4 -2
  117. package/dist/rpc/variables-command.js.map +1 -1
  118. package/dist/text/character-style.d.ts.map +1 -1
  119. package/dist/text/character-style.js +2 -1
  120. package/dist/text/character-style.js.map +1 -1
  121. package/dist/text/coverage.d.ts.map +1 -1
  122. package/dist/text/coverage.js +6 -3
  123. package/dist/text/coverage.js.map +1 -1
  124. package/dist/text/fallbacks.d.ts +8 -2
  125. package/dist/text/fallbacks.d.ts.map +1 -1
  126. package/dist/text/fallbacks.js +73 -7
  127. package/dist/text/fallbacks.js.map +1 -1
  128. package/dist/text/font/manager.d.ts +14 -6
  129. package/dist/text/font/manager.d.ts.map +1 -1
  130. package/dist/text/font/manager.js +40 -14
  131. package/dist/text/font/manager.js.map +1 -1
  132. package/dist/text/index.d.ts +2 -2
  133. package/dist/text/index.js +3 -3
  134. package/dist/text/outlines.js +1 -1
  135. package/dist/text/outlines.js.map +1 -1
  136. package/dist/text/path/caret.d.ts +2 -4
  137. package/dist/text/path/caret.d.ts.map +1 -1
  138. package/dist/text/path/caret.js.map +1 -1
  139. package/dist/text/prepare.d.ts +5 -1
  140. package/dist/text/prepare.d.ts.map +1 -1
  141. package/dist/text/prepare.js +19 -2
  142. package/dist/text/prepare.js.map +1 -1
  143. package/dist/text/web-font/assets.d.ts.map +1 -1
  144. package/dist/text/web-font/assets.js +13 -21
  145. package/dist/text/web-font/assets.js.map +1 -1
  146. package/dist/text/web-font/resolver.d.ts.map +1 -1
  147. package/dist/text/web-font/resolver.js +4 -1
  148. package/dist/text/web-font/resolver.js.map +1 -1
  149. package/dist/tools/create/components.d.ts +2 -1
  150. package/dist/tools/create/components.d.ts.map +1 -1
  151. package/dist/tools/create/components.js +27 -1
  152. package/dist/tools/create/components.js.map +1 -1
  153. package/dist/tools/create/icons.d.ts.map +1 -1
  154. package/dist/tools/create/icons.js +11 -5
  155. package/dist/tools/create/icons.js.map +1 -1
  156. package/dist/tools/create/vector.d.ts.map +1 -1
  157. package/dist/tools/create/vector.js +9 -6
  158. package/dist/tools/create/vector.js.map +1 -1
  159. package/dist/tools/create.d.ts +2 -2
  160. package/dist/tools/create.js +2 -2
  161. package/dist/tools/modify/effects.d.ts.map +1 -1
  162. package/dist/tools/modify/effects.js +5 -3
  163. package/dist/tools/modify/effects.js.map +1 -1
  164. package/dist/tools/modify/matching.d.ts.map +1 -1
  165. package/dist/tools/modify/matching.js +9 -6
  166. package/dist/tools/modify/matching.js.map +1 -1
  167. package/dist/tools/modify/paint.d.ts.map +1 -1
  168. package/dist/tools/modify/paint.js +7 -5
  169. package/dist/tools/modify/paint.js.map +1 -1
  170. package/dist/tools/modify/text.d.ts.map +1 -1
  171. package/dist/tools/modify/text.js +28 -8
  172. package/dist/tools/modify/text.js.map +1 -1
  173. package/dist/tools/read/libraries.d.ts.map +1 -1
  174. package/dist/tools/read/libraries.js +20 -8
  175. package/dist/tools/read/libraries.js.map +1 -1
  176. package/dist/tools/read/pages.d.ts.map +1 -1
  177. package/dist/tools/read/pages.js.map +1 -1
  178. package/dist/tools/registry/extended.d.ts.map +1 -1
  179. package/dist/tools/registry/extended.js +2 -1
  180. package/dist/tools/registry/extended.js.map +1 -1
  181. package/dist/tools/schema.d.ts +24 -5
  182. package/dist/tools/schema.d.ts.map +1 -1
  183. package/dist/tools/schema.js +80 -6
  184. package/dist/tools/schema.js.map +1 -1
  185. package/dist/tools/structure/batch.d.ts.map +1 -1
  186. package/dist/tools/structure/batch.js +4 -3
  187. package/dist/tools/structure/batch.js.map +1 -1
  188. package/dist/tools/variables/values.d.ts.map +1 -1
  189. package/dist/tools/variables/values.js +4 -2
  190. package/dist/tools/variables/values.js.map +1 -1
  191. package/dist/tools/vector/export.d.ts.map +1 -1
  192. package/dist/tools/vector/export.js +5 -2
  193. package/dist/tools/vector/export.js.map +1 -1
  194. package/package.json +9 -9
  195. package/src/canvas/outline-stroke.ts +2 -6
  196. package/src/canvas/overlays/prototype.ts +5 -27
  197. package/src/canvas/renderer/fonts.ts +2 -1
  198. package/src/canvas/renderer.ts +4 -0
  199. package/src/canvas/rulers.ts +1 -1
  200. package/src/canvas/scene.ts +92 -63
  201. package/src/canvas/text/font-families.ts +8 -7
  202. package/src/canvas/text/index.ts +3 -1
  203. package/src/canvas/text/paragraph/index.ts +2 -2
  204. package/src/canvas/text/placed.ts +2 -2
  205. package/src/canvas/text/renderer.ts +2 -0
  206. package/src/clipboard/pairdraw.ts +51 -7
  207. package/src/design-jsx/preview/picture.ts +8 -2
  208. package/src/editor/alignment.ts +33 -29
  209. package/src/editor/clipboard/detach.ts +9 -3
  210. package/src/editor/clipboard/paste/properties.ts +3 -1
  211. package/src/editor/structure.ts +3 -1
  212. package/src/editor/viewport.ts +2 -2
  213. package/src/figma-api/index.ts +90 -9
  214. package/src/figma-api/serialization.ts +14 -0
  215. package/src/figma-api/text/bindings.ts +26 -8
  216. package/src/geometry/connectors.ts +2 -12
  217. package/src/geometry/index.ts +1 -1
  218. package/src/geometry/scene.ts +19 -0
  219. package/src/geometry/types.ts +8 -0
  220. package/src/io/formats/drawio/export.ts +11 -0
  221. package/src/io/formats/drawio/index.ts +36 -1
  222. package/src/io/formats/drawio/shapes.ts +13 -9
  223. package/src/io/formats/drawio/warnings.ts +27 -0
  224. package/src/io/formats/pdf/dom.ts +29 -0
  225. package/src/io/formats/pdf/export.ts +3 -2
  226. package/src/io/formats/raster/headless.ts +10 -3
  227. package/src/io/formats/raster/render.ts +4 -2
  228. package/src/io/formats.ts +8 -10
  229. package/src/io/registry.ts +12 -0
  230. package/src/io/types.ts +2 -0
  231. package/src/library/snapshot.ts +1 -0
  232. package/src/lint/linter.ts +12 -2
  233. package/src/rpc/variables-command.ts +6 -5
  234. package/src/text/character-style.ts +8 -4
  235. package/src/text/coverage.ts +17 -2
  236. package/src/text/fallbacks.ts +81 -7
  237. package/src/text/font/manager.ts +50 -17
  238. package/src/text/outlines.ts +1 -1
  239. package/src/text/path/caret.ts +3 -4
  240. package/src/text/prepare.ts +34 -2
  241. package/src/text/web-font/assets.ts +11 -15
  242. package/src/text/web-font/resolver.ts +7 -1
  243. package/src/tools/create/components.ts +33 -0
  244. package/src/tools/create/icons.ts +13 -5
  245. package/src/tools/create/vector.ts +16 -6
  246. package/src/tools/create.ts +1 -0
  247. package/src/tools/modify/effects.ts +11 -4
  248. package/src/tools/modify/matching.ts +10 -6
  249. package/src/tools/modify/paint.ts +13 -5
  250. package/src/tools/modify/text.ts +53 -20
  251. package/src/tools/read/libraries.ts +35 -11
  252. package/src/tools/read/pages.ts +1 -0
  253. package/src/tools/registry/extended.ts +2 -0
  254. package/src/tools/schema.ts +109 -5
  255. package/src/tools/structure/batch.ts +10 -5
  256. package/src/tools/variables/values.ts +6 -3
  257. package/src/tools/vector/export.ts +5 -1
@@ -1,3 +1,4 @@
1
+ import { isPlainObject, omit } from 'es-toolkit'
1
2
  import { deflateSync, inflateSync } from 'fflate'
2
3
  import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
3
4
  import * as v from 'valibot'
@@ -16,6 +17,7 @@ import {
16
17
  setInstanceOverride,
17
18
  type InstanceOverrideState
18
19
  } from '@pairdraw/scene-graph/instances/overrides'
20
+ import { fillSchema } from '@pairdraw/scene-graph/paints'
19
21
  import type { JSONObject } from '@pairdraw/scene-graph/primitives'
20
22
 
21
23
  import type { ClipboardSnapshot } from '#core/editor/clipboard/copy'
@@ -93,6 +95,42 @@ const serializedClipboardNodeSchema: v.GenericSchema<unknown, SerializedClipboar
93
95
  children: v.optional(v.array(v.lazy(() => serializedClipboardNodeSchema)))
94
96
  })
95
97
 
98
+ const paintsSchema = v.array(fillSchema)
99
+ const effectsSchema = v.array(v.unknown())
100
+ const sourceMetadataSchema = v.looseObject({
101
+ format: v.nullable(v.literal('fig')),
102
+ id: v.nullable(v.string()),
103
+ orderKey: v.nullable(v.string()),
104
+ editedFields: v.array(v.string()),
105
+ fig: v.looseObject({})
106
+ })
107
+
108
+ /**
109
+ * Fields the graph reads without checking. `v.is` checks them without parsing, which would reorder
110
+ * paint keys; a malformed field is dropped and the rest of the layer kept.
111
+ */
112
+ const CHECKED_FIELDS: [string, v.GenericSchema][] = [
113
+ ['fills', paintsSchema],
114
+ ['strokes', paintsSchema],
115
+ ['effects', effectsSchema],
116
+ ['source', sourceMetadataSchema]
117
+ ]
118
+
119
+ function malformedFields(fields: Record<string, unknown>, checked = CHECKED_FIELDS): string[] {
120
+ return checked
121
+ .filter(([key, schema]) => key in fields && !v.is(schema, fields[key]))
122
+ .map(([key]) => key)
123
+ }
124
+
125
+ /** Payloads from v0.15.1 and earlier wrote strokes without a paint type; they are solid. */
126
+ function withStrokeTypes(fields: Record<string, unknown>): Record<string, unknown> {
127
+ if (!Array.isArray(fields.strokes)) return fields
128
+ const strokes = fields.strokes.map((stroke: unknown) =>
129
+ isPlainObject(stroke) && !Object.hasOwn(stroke, 'type') ? { ...stroke, type: 'SOLID' } : stroke
130
+ )
131
+ return { ...fields, strokes }
132
+ }
133
+
96
134
  /** Clipboard HTML is writable by any application, so the payload is validated before paste. */
97
135
  const pairdrawClipboardSchema = v.pipe(
98
136
  v.string(),
@@ -154,10 +192,14 @@ function legacyInstanceOverrides(
154
192
  }
155
193
 
156
194
  function restoreGeometry(paths: SerializedGeometryPath[] | undefined): GeometryPath[] {
157
- return (paths ?? []).map((path) => ({
158
- ...path,
159
- commandsBlob: Uint8Array.from(Object.values(path.commandsBlob))
160
- }))
195
+ return (paths ?? []).map((path) => {
196
+ const { fills, ...rest } = path
197
+ return {
198
+ ...rest,
199
+ ...(v.is(paintsSchema, fills) ? { fills } : {}),
200
+ commandsBlob: Uint8Array.from(Object.values(path.commandsBlob))
201
+ }
202
+ })
161
203
  }
162
204
 
163
205
  /** Clipboard HTML comes from other applications, so its Base64 is checked before decoding. */
@@ -168,14 +210,16 @@ function clipboardBytes(value: string): Uint8Array {
168
210
 
169
211
  function restoreNodeData(nodes: SerializedClipboardNode[]): ClipboardNode[] {
170
212
  return nodes.map((node) => {
171
- const { children, instanceOverrides, overrides, textPicture, ...rest } = node
213
+ const { children, instanceOverrides, overrides, textPicture, ...fields } = node
214
+ const typed = withStrokeTypes(fields)
215
+ const rest = { ...omit(typed, malformedFields(typed)), id: node.id, type: node.type }
172
216
  const overrideState = instanceOverrides
173
217
  ? deserializeInstanceOverrideState(instanceOverrides)
174
218
  : legacyInstanceOverrides(rest.id, overrides)
175
219
  return {
176
220
  ...rest,
177
- fillGeometry: restoreGeometry(rest.fillGeometry),
178
- strokeGeometry: restoreGeometry(rest.strokeGeometry),
221
+ fillGeometry: restoreGeometry(node.fillGeometry),
222
+ strokeGeometry: restoreGeometry(node.strokeGeometry),
179
223
  instanceOverrides: overrideState,
180
224
  textPicture: typeof textPicture === 'string' ? clipboardBytes(textPicture) : textPicture,
181
225
  ...(children ? { children: restoreNodeData(children) } : {})
@@ -64,9 +64,15 @@ export function createJSXPreviewRecorder(ck: CanvasKit): JSXPreviewRecorder {
64
64
  const surface = ck.MakeSurface(1, 1)
65
65
  if (!surface) return null
66
66
  const created = new SkiaRenderer(ck, surface)
67
+ // Loading fonts drops every cache, so it happens once rather than before each record; a
68
+ // renderer whose fonts failed to load is not kept, so the next record tries again.
69
+ try {
70
+ await created.loadFonts()
71
+ } catch (error) {
72
+ created.destroy()
73
+ throw error
74
+ }
67
75
  renderer = created
68
- // Loading fonts drops every cache, so it happens once rather than before each record.
69
- await created.loadFonts()
70
76
  return created
71
77
  }
72
78
 
@@ -1,7 +1,11 @@
1
1
  import { sumBy } from 'es-toolkit'
2
2
 
3
3
  import type { SceneNode } from '@pairdraw/scene-graph'
4
- import { getAbsolutePositionFull, getWorldMatrix } from '@pairdraw/scene-graph/coordinate'
4
+ import {
5
+ getAbsolutePositionFull,
6
+ getAxisAlignedWorldBounds,
7
+ getWorldMatrix
8
+ } from '@pairdraw/scene-graph/coordinate'
5
9
  import { computeAbsoluteBounds } from '@pairdraw/scene-graph/geometry'
6
10
  import Matrix from '@pairdraw/scene-graph/matrix'
7
11
  import type { Vector } from '@pairdraw/scene-graph/primitives'
@@ -30,15 +34,23 @@ function alignSingleNode(
30
34
  axis: 'horizontal' | 'vertical',
31
35
  align: 'min' | 'center' | 'max'
32
36
  ) {
37
+ // The layer's drawn box against the parent's, so a rotated layer's visible edge lands on the
38
+ // target as it does when several layers align together.
33
39
  const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined
34
- const pw = parent?.width ?? 0
35
- const ph = parent?.height ?? 0
36
-
37
- if (axis === 'horizontal') {
38
- ctx.graph.updateNode(node.id, { x: computeAlignTarget(0, pw, node.width, align) })
39
- } else {
40
- ctx.graph.updateNode(node.id, { y: computeAlignTarget(0, ph, node.height, align) })
41
- }
40
+ const target = parent
41
+ ? getAxisAlignedWorldBounds(parent, ctx.graph)
42
+ : { x: 0, y: 0, width: 0, height: 0 }
43
+ const box = getAxisAlignedWorldBounds(node, ctx.graph)
44
+ const worldDelta =
45
+ axis === 'horizontal'
46
+ ? { x: computeAlignTarget(target.x, target.x + target.width, box.width, align) - box.x, y: 0 }
47
+ : {
48
+ x: 0,
49
+ y: computeAlignTarget(target.y, target.y + target.height, box.height, align) - box.y
50
+ }
51
+ const localDelta = parentLocalDelta(ctx, node, worldDelta)
52
+ if (!localDelta) return
53
+ ctx.graph.updateNode(node.id, { x: node.x + localDelta.x, y: node.y + localDelta.y })
42
54
  }
43
55
 
44
56
  function alignMultipleNodes(
@@ -47,28 +59,20 @@ function alignMultipleNodes(
47
59
  axis: 'horizontal' | 'vertical',
48
60
  align: 'min' | 'center' | 'max'
49
61
  ) {
50
- const absPositions = new Map<string, Vector>()
51
- for (const n of nodes) absPositions.set(n.id, ctx.graph.getAbsolutePosition(n.id))
52
-
53
- const getPos = (id: string) => absPositions.get(id) ?? { x: 0, y: 0 }
54
- const b = computeAbsoluteBounds(nodes, getPos)
55
- const minX = b.x
56
- const minY = b.y
57
- const maxX = b.x + b.width
58
- const maxY = b.y + b.height
62
+ // Each layer's drawn box, so a rotated layer's visible edge lands on the target.
63
+ const boxes = new Map(nodes.map((n) => [n.id, getAxisAlignedWorldBounds(n, ctx.graph)]))
64
+ const b = computeAbsoluteBounds(nodes, ctx.graph)
59
65
 
60
66
  for (const n of nodes) {
61
- const abs = absPositions.get(n.id)
62
- if (!abs) continue
63
- const parentAbs = n.parentId ? ctx.graph.getAbsolutePosition(n.parentId) : { x: 0, y: 0 }
64
-
65
- if (axis === 'horizontal') {
66
- const target = computeAlignTarget(minX, maxX, n.width, align)
67
- ctx.graph.updateNode(n.id, { x: target - parentAbs.x })
68
- } else {
69
- const target = computeAlignTarget(minY, maxY, n.height, align)
70
- ctx.graph.updateNode(n.id, { y: target - parentAbs.y })
71
- }
67
+ const box = boxes.get(n.id)
68
+ if (!box) continue
69
+ const worldDelta =
70
+ axis === 'horizontal'
71
+ ? { x: computeAlignTarget(b.x, b.x + b.width, box.width, align) - box.x, y: 0 }
72
+ : { x: 0, y: computeAlignTarget(b.y, b.y + b.height, box.height, align) - box.y }
73
+ const localDelta = parentLocalDelta(ctx, n, worldDelta)
74
+ if (!localDelta) continue
75
+ ctx.graph.updateNode(n.id, { x: n.x + localDelta.x, y: n.y + localDelta.y })
72
76
  }
73
77
  }
74
78
 
@@ -27,9 +27,15 @@ export function resolvedClipboardBindings(
27
27
  }
28
28
 
29
29
  function unlinkedRun(run: StyleRun): StyleRun {
30
- const { boundVariables, textStyleId, fillStyleId } = run.style
31
- if (!boundVariables && !textStyleId && !fillStyleId) return run
32
- const { boundVariables: _variables, textStyleId: _text, fillStyleId: _fill, ...style } = run.style
30
+ const { boundVariables, variableBindingScales, textStyleId, fillStyleId } = run.style
31
+ if (!boundVariables && !variableBindingScales && !textStyleId && !fillStyleId) return run
32
+ const {
33
+ boundVariables: _variables,
34
+ variableBindingScales: _scales,
35
+ textStyleId: _text,
36
+ fillStyleId: _fill,
37
+ ...style
38
+ } = run.style
33
39
  return { ...run, style }
34
40
  }
35
41
 
@@ -12,6 +12,7 @@ import {
12
12
  TEXT_STYLE_FIELDS
13
13
  } from '@pairdraw/scene-graph/fields'
14
14
  import { STYLE_LINK_FIELDS, sharedStyleRefKey } from '@pairdraw/scene-graph/shared-styles'
15
+ import { withBoundBindingScales } from '@pairdraw/scene-graph/variables'
15
16
 
16
17
  import { parsePairdrawClipboard } from '#core/clipboard'
17
18
  import { importClipboardDependenciesWithUndo } from '#core/editor/clipboard/dependencies'
@@ -89,12 +90,13 @@ function pastedFields(source: SceneNode, target: SceneNode): PastedField[] {
89
90
  function runsWithout(runs: StyleRun[], fields: ReadonlySet<string>): StyleRun[] {
90
91
  const overrides = new Set([...fields].flatMap((field) => RUN_OVERRIDES[field] ?? [field]))
91
92
  return runs.flatMap((run) => {
92
- const style = omitBy(run.style, (_, key) => overrides.has(key))
93
+ let style = omitBy(run.style, (_, key) => overrides.has(key))
93
94
  if (style.boundVariables) {
94
95
  const bound = omitBy(style.boundVariables, (_, key) => fields.has(key))
95
96
  if (Object.keys(bound).length > 0) style.boundVariables = bound
96
97
  else delete style.boundVariables
97
98
  }
99
+ style = withBoundBindingScales(style)
98
100
  return Object.keys(style).length > 0 ? [{ ...run, style }] : []
99
101
  })
100
102
  }
@@ -121,12 +121,13 @@ export function createStructureActions(ctx: EditorContext) {
121
121
  .sort((a, b) => a.index - b.index)
122
122
  if (origins.length === 0) return
123
123
  const parentIds = new Set(origins.map((origin) => origin.parentId))
124
+ const prevSelection = new Set(ctx.state.selectedIds)
124
125
  const move = () => {
125
126
  for (const { id } of origins) ctx.graph.reparentNode(id, pageId)
126
127
  for (const parentId of parentIds) ctx.runLayoutForNode(parentId)
128
+ ctx.setSelectedIds(new Set())
127
129
  }
128
130
  move()
129
- ctx.setSelectedIds(new Set())
130
131
  ctx.undo.push({
131
132
  label: 'Move to page',
132
133
  forward: move,
@@ -136,6 +137,7 @@ export function createStructureActions(ctx: EditorContext) {
136
137
  ctx.graph.updateNode(id, place)
137
138
  }
138
139
  for (const parentId of parentIds) ctx.runLayoutForNode(parentId)
140
+ ctx.setSelectedIds(new Set(prevSelection))
139
141
  }
140
142
  })
141
143
  }
@@ -69,7 +69,7 @@ export function createViewportActions(ctx: EditorContext) {
69
69
  const h = maxY - minY + padding * 2
70
70
 
71
71
  const { width: viewW, height: viewH } = ctx.getViewportSize()
72
- const zoom = Math.min(viewW / w, viewH / h, 1)
72
+ const zoom = Math.max(0.02, Math.min(viewW / w, viewH / h, 1))
73
73
 
74
74
  ctx.state.zoom = zoom
75
75
  ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom
@@ -147,7 +147,7 @@ export function createViewportActions(ctx: EditorContext) {
147
147
  .filter((n): n is NonNullable<typeof n> => n != null)
148
148
  if (nodes.length === 0) return
149
149
 
150
- const b = computeAbsoluteBounds(nodes, (id) => ctx.graph.getAbsolutePosition(id))
150
+ const b = computeAbsoluteBounds(nodes, ctx.graph)
151
151
  zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)
152
152
  }
153
153
 
@@ -53,10 +53,46 @@ import { combineComponentsAsVariants } from './variants'
53
53
 
54
54
  const noop = () => undefined
55
55
 
56
+ /** A view of the document: its centre point and its zoom. */
57
+ export interface FigmaViewport {
58
+ center: Vector
59
+ zoom: number
60
+ }
61
+
56
62
  /** What a host passes to `FigmaAPI` beyond the document. */
57
63
  export interface FigmaAPIOptions {
58
64
  /** Fetches the HTTP(S) URLs `figma.createImageAsync` loads; the global `fetch` by default. */
59
65
  fetch?: images.ImageFetch
66
+ /**
67
+ * Runs when a script puts the API on another page, so a host can show that page too. The host
68
+ * owns which page is on screen, and a plugin that switches page expects to see it switched.
69
+ */
70
+ onPageChange?: (pageId: string) => void | Promise<void>
71
+ /**
72
+ * Runs when a script moves the viewport, so a host can show the same view. A host owns the
73
+ * viewport on screen, and a plugin that pans or zooms expects to see the result.
74
+ */
75
+ onViewportChange?: (viewport: FigmaViewport) => void
76
+ /**
77
+ * The page the host already shows. Seeded here rather than assigned after construction, so a
78
+ * plain tool call does not ask the host to switch to the page it is already on.
79
+ */
80
+ pageId?: string
81
+ /**
82
+ * The view the host already shows, seeded for the same reason: a tool that only reads or draws
83
+ * must not move the viewport of whoever is looking at the document.
84
+ */
85
+ viewport?: FigmaViewport
86
+ /**
87
+ * Runs when a script sets the page selection, so a host can select those layers too. The host
88
+ * owns which layers are selected on screen, and a plugin that selects expects to see them selected.
89
+ */
90
+ onSelectionChange?: (ids: readonly string[], pageId: string) => void
91
+ /**
92
+ * The selection the host already shows, seeded for the same reason as the page and the viewport:
93
+ * a tool that only reads must not reselect what is already selected.
94
+ */
95
+ selection?: readonly string[]
60
96
  }
61
97
 
62
98
  export { FigmaNodeProxy } from './proxy'
@@ -121,14 +157,33 @@ export class FigmaAPI implements NodeProxyHost {
121
157
 
122
158
  /** How `createImageAsync` fetches HTTP(S) URLs; a host passes one that gets past CORS. */
123
159
  readonly #fetch: images.ImageFetch
160
+ readonly #onPageChange: ((pageId: string) => void | Promise<void>) | undefined
161
+ readonly #onViewportChange: ((viewport: FigmaViewport) => void) | undefined
162
+ readonly #onSelectionChange: ((ids: readonly string[], pageId: string) => void) | undefined
163
+ /** The last host page switch, so `setCurrentPageAsync` can wait for it. */
164
+ #pageChange: Promise<void> = Promise.resolve()
124
165
 
125
166
  constructor(graph: SceneGraph, options: FigmaAPIOptions = {}) {
126
167
  this.graph = graph
127
168
  this.#fetch = options.fetch ?? ((input, init) => fetch(input, init))
169
+ this.#onPageChange = options.onPageChange
170
+ this.#onViewportChange = options.onViewportChange
171
+ this.#onSelectionChange = options.onSelectionChange
128
172
  this.variables = new FigmaVariablesAPI(graph)
129
173
  startPendingLayout(graph)
130
- const pages = graph.getPages()
131
- this._currentPageId = pages[0]?.id ?? graph.rootId
174
+ this._currentPageId = pageIdToStart(graph, options.pageId)
175
+ if (options.viewport) {
176
+ this._viewport = {
177
+ x: options.viewport.center.x,
178
+ y: options.viewport.center.y,
179
+ zoom: options.viewport.zoom
180
+ }
181
+ }
182
+ // Seeded here, not assigned through the setter, so a tool that only reads does not ask the
183
+ // host to select the layers it is already showing.
184
+ this._selection = (options.selection ?? []).flatMap((id) =>
185
+ this.graph.getNode(id) ? [this.wrapNode(id)] : []
186
+ )
132
187
  }
133
188
 
134
189
  setRenderer(renderer: SkiaRenderer | null): void {
@@ -159,7 +214,12 @@ export class FigmaAPI implements NodeProxyHost {
159
214
  Object.defineProperty(proxy, 'selection', {
160
215
  get: () => this._selection,
161
216
  set: (nodes: FigmaNodeProxy[]) => {
217
+ const next = nodes.map((node) => node[INTERNAL_ID])
218
+ const current = this._selection.map((node) => node[INTERNAL_ID])
162
219
  this._selection = nodes
220
+ if (next.length === current.length && next.every((id, index) => id === current[index]))
221
+ return
222
+ this.#onSelectionChange?.(next, this._currentPageId)
163
223
  },
164
224
  enumerable: true,
165
225
  configurable: true
@@ -178,7 +238,10 @@ export class FigmaAPI implements NodeProxyHost {
178
238
  }
179
239
 
180
240
  set currentPage(page: FigmaNodeProxy) {
181
- this._currentPageId = page[INTERNAL_ID]
241
+ const pageId = page[INTERNAL_ID]
242
+ if (pageId === this._currentPageId) return
243
+ this._currentPageId = pageId
244
+ this.#pageChange = Promise.resolve(this.#onPageChange?.(pageId))
182
245
  }
183
246
 
184
247
  getNodeById(id: string): FigmaNodeProxy | null {
@@ -204,7 +267,8 @@ export class FigmaAPI implements NodeProxyHost {
204
267
  return Promise.reject(new Error('figma.setCurrentPageAsync expects a PageNode'))
205
268
  }
206
269
  this._currentPageId = this._nodeId(page)
207
- return Promise.resolve()
270
+ this.#pageChange = Promise.resolve(this.#onPageChange?.(this._currentPageId))
271
+ return this.#pageChange
208
272
  }
209
273
 
210
274
  // --- Node Creation ---
@@ -497,9 +561,7 @@ export class FigmaAPI implements NodeProxyHost {
497
561
 
498
562
  private _viewport = { x: 0, y: 0, zoom: 1 }
499
563
 
500
- get viewport(): {
501
- center: Vector
502
- zoom: number
564
+ get viewport(): FigmaViewport & {
503
565
  scrollAndZoomIntoView: (nodes: readonly { absoluteBoundingBox: Rect }[]) => void
504
566
  } {
505
567
  return {
@@ -515,13 +577,26 @@ export class FigmaAPI implements NodeProxyHost {
515
577
  const viewW = IS_BROWSER ? window.innerWidth : 1280
516
578
  const viewH = IS_BROWSER ? window.innerHeight : 720
517
579
  const zoom = Math.min(viewW / contentW, viewH / contentH, 1)
580
+ // A script scrolling to its own result must not move the view someone else is looking at:
581
+ // only `viewport` and a page switch do that.
518
582
  this._viewport = { x: b.x + b.width / 2, y: b.y + b.height / 2, zoom }
519
583
  }
520
584
  }
521
585
  }
522
586
 
523
- set viewport(v: { center: Vector; zoom: number }) {
524
- this._viewport = { x: v.center.x, y: v.center.y, zoom: v.zoom }
587
+ set viewport(v: FigmaViewport) {
588
+ this._showViewport({ x: v.center.x, y: v.center.y, zoom: v.zoom })
589
+ }
590
+
591
+ /**
592
+ * Moves the viewport and puts the host on the same view. A tool that scrolls nodes into view
593
+ * does not call this: only a viewport a writer asks for moves the view of whoever is looking.
594
+ */
595
+ private _showViewport(next: { x: number; y: number; zoom: number }): void {
596
+ const current = this._viewport
597
+ this._viewport = next
598
+ if (current.x === next.x && current.y === next.y && current.zoom === next.zoom) return
599
+ this.#onViewportChange?.({ center: { x: next.x, y: next.y }, zoom: next.zoom })
525
600
  }
526
601
 
527
602
  createImage(data: Uint8Array): Image {
@@ -607,3 +682,9 @@ export class FigmaAPI implements NodeProxyHost {
607
682
  /** The document as it was before the current AI run first edited `pageId`, or null if unedited. */
608
683
  changeBaseline?: (pageId: string) => SceneGraph | null
609
684
  }
685
+
686
+ /** The page an API starts on: the one the host shows, else the document's first page. */
687
+ function pageIdToStart(graph: SceneGraph, pageId?: string): string {
688
+ const pages = graph.getPages()
689
+ return pageId ?? (pages.length > 0 ? pages[0].id : graph.rootId)
690
+ }
@@ -58,6 +58,9 @@ export function nodeProxyToJSON(
58
58
  if (n.strokes.length > 0) obj.strokes = figmaStrokes(graph, n)
59
59
  if (n.effects.length > 0) obj.effects = n.effects
60
60
  if (n.opacity !== 1) obj.opacity = n.opacity
61
+ // The angle `set_rotation` writes, as the Figma API reports it. The scene stores the turn in
62
+ // the opposite direction and keeps floating-point noise, so read it through the proxy.
63
+ if (n.rotation !== 0) obj.rotation = api.wrapNode(nodeId).rotation
61
64
  if (n.cornerRadius > 0) obj.cornerRadius = n.cornerRadius
62
65
  if (!n.visible) obj.visible = false
63
66
  if (n.text) obj.characters = n.text
@@ -65,9 +68,20 @@ export function nodeProxyToJSON(
65
68
  appendTextProps(obj, n)
66
69
  }
67
70
  if (n.layoutMode !== 'NONE') {
71
+ // An auto layout frame reports the insets and alignment a tool sets, so a caller can read back
72
+ // what it wrote instead of measuring the result.
73
+ const proxy = api.wrapNode(nodeId)
68
74
  obj.layoutMode = n.layoutMode
69
75
  obj.layoutDirection = n.layoutDirection
70
76
  obj.itemSpacing = n.itemSpacing
77
+ obj.paddingTop = proxy.paddingTop
78
+ obj.paddingRight = proxy.paddingRight
79
+ obj.paddingBottom = proxy.paddingBottom
80
+ obj.paddingLeft = proxy.paddingLeft
81
+ obj.primaryAxisAlignItems = proxy.primaryAxisAlignItems
82
+ obj.counterAxisAlignItems = proxy.counterAxisAlignItems
83
+ obj.primaryAxisSizingMode = proxy.primaryAxisSizingMode
84
+ obj.counterAxisSizingMode = proxy.counterAxisSizingMode
71
85
  }
72
86
  // Include variable bindings with resolved values
73
87
  const bindings = resolveBindings(graph, n)
@@ -11,10 +11,16 @@ import {
11
11
  } from '@pairdraw/scene-graph'
12
12
  import { copyFills } from '@pairdraw/scene-graph/copy'
13
13
  import { getSharedStyles, SHARED_TEXT_STYLE_FIELDS } from '@pairdraw/scene-graph/shared-styles'
14
+ import {
15
+ boundNumberValue,
16
+ SCALED_RUN_BINDING_FIELDS,
17
+ variableBindingOwner
18
+ } from '@pairdraw/scene-graph/variables'
14
19
 
15
20
  import { variableAlias, type FigmaVariableAlias } from '#core/figma-api/variables/values'
16
21
  import { styleRunsWithPatch } from '#core/text/character-style'
17
22
  import { faceForStyle } from '#core/text/font/names'
23
+ import { getStyleAt } from '#core/text/style-runs'
18
24
 
19
25
  import { getStyledTextSegments } from './style'
20
26
 
@@ -77,12 +83,16 @@ function boundVariable(
77
83
  return found
78
84
  }
79
85
 
80
- /** What the characters show for a bound field: the variable's value in their mode. */
86
+ /**
87
+ * What the characters show for a bound field: the variable's value in their mode, a number in
88
+ * the scale the characters' binding keeps.
89
+ */
81
90
  function boundValue(
82
91
  graph: SceneGraph,
83
92
  node: SceneNode,
84
93
  field: TextBindableField,
85
- variable: Variable
94
+ variable: Variable,
95
+ scale: number
86
96
  ): CharacterStyleOverride {
87
97
  if (STRING_FIELDS.has(field)) {
88
98
  const value = graph.resolveVariableForNode(node.id, variable.id)
@@ -94,7 +104,7 @@ function boundValue(
94
104
  }
95
105
  const value = graph.resolveNumberVariableForNode(node.id, variable.id)
96
106
  if (value === undefined || !Number.isFinite(value) || isParagraphField(field)) return {}
97
- return { [field]: value }
107
+ return { [field]: boundNumberValue(field, value * scale) }
98
108
  }
99
109
 
100
110
  /**
@@ -112,17 +122,25 @@ export function rangeBindingChanges(
112
122
  ): { styleRuns: StyleRun[]; paragraphValue: number | null } {
113
123
  const bound =
114
124
  variable === null ? null : boundVariable(graph, 'setRangeBoundVariable', field, variable)
115
- const value = bound ? boundValue(graph, node, field, bound) : {}
125
+ // A new binding starts at the variable's number in the scope that declares it, as a layer's does
126
+ // (`assignVariableBindingUnits`), not at a scale a rescale left on the characters' old binding.
127
+ const scaled = SCALED_RUN_BINDING_FIELDS.has(field)
128
+ const scale = scaled
129
+ ? (variableBindingOwner(graph, node).variableAssignmentScales[field] ?? 1)
130
+ : 1
116
131
  let styleRuns = node.styleRuns
117
132
  // Characters bound apart keep their other bindings.
118
133
  for (const segment of getStyledTextSegments(node, ['boundVariables'], start, end)) {
119
134
  const aliases = (segment.boundVariables ?? {}) as Record<string, FigmaVariableAlias>
120
135
  const ids = mapValues(aliases, (alias) => alias.id)
121
136
  const boundVariables = bound ? { ...ids, [field]: bound.id } : omit(ids, [field])
122
- styleRuns = styleRunsWithPatch({ ...node, styleRuns }, segment.start, segment.end, {
123
- ...value,
124
- boundVariables
125
- })
137
+ const scales = getStyleAt(node.styleRuns, segment.start).variableBindingScales ?? {}
138
+ const patch: CharacterStyleOverride = bound
139
+ ? { ...boundValue(graph, node, field, bound, scale), boundVariables }
140
+ : { boundVariables }
141
+ // An unbound range's scale goes with its binding (`withBoundBindingScales`).
142
+ if (bound && scaled) patch.variableBindingScales = { ...scales, [field]: scale }
143
+ styleRuns = styleRunsWithPatch({ ...node, styleRuns }, segment.start, segment.end, patch)
126
144
  }
127
145
  const resolved = bound ? graph.resolveNumberVariableForNode(node.id, bound.id) : undefined
128
146
  const paragraphValue =
@@ -8,7 +8,7 @@ import {
8
8
  import Matrix from '@pairdraw/scene-graph/matrix'
9
9
  import type { Rect, Vector } from '@pairdraw/scene-graph/primitives'
10
10
 
11
- import { createSceneGeometry } from './scene'
11
+ import { createSceneGeometry, nodeScreenBounds } from './scene'
12
12
  import type { RotationPreview, ViewportTransform } from './types'
13
13
 
14
14
  /** Where a connector's line starts and ends on screen, where its end handles sit. */
@@ -88,15 +88,5 @@ export function connectorScreenLabel(
88
88
  ): Rect | null {
89
89
  const parts = connectorSublayers(graph, connector)
90
90
  if (!parts || parts.label.text === '' || !parts.labelBackground.visible) return null
91
- const plate = parts.labelBackground
92
- const [x0, y0, x1, y1] = Matrix.mapPoints(
93
- createSceneGeometry(graph, preview).screenMatrix(plate, viewport),
94
- [0, 0, plate.width, plate.height]
95
- )
96
- return {
97
- x: Math.min(x0, x1),
98
- y: Math.min(y0, y1),
99
- width: Math.abs(x1 - x0),
100
- height: Math.abs(y1 - y0)
101
- }
91
+ return nodeScreenBounds(graph, parts.labelBackground, viewport, preview)
102
92
  }
@@ -98,4 +98,4 @@ export {
98
98
  } from './transform-zones'
99
99
  export type { CornerPosition, HandlePosition, TransformZone } from './transform-zones'
100
100
  export type { RotationHandleLayout } from './selection'
101
- export type { RotationPreview, ViewportTransform } from './types'
101
+ export type { LineSegment, RotationPreview, ViewportTransform } from './types'
@@ -27,6 +27,25 @@ export function viewportMatrix(viewport: ViewportTransform) {
27
27
  )
28
28
  }
29
29
 
30
+ /** A node's axis-aligned box on screen, around its corners as drawn. */
31
+ export function nodeScreenBounds(
32
+ graph: SceneGraph,
33
+ node: SceneNode,
34
+ viewport: ViewportTransform,
35
+ preview?: RotationPreview | null
36
+ ): Rect {
37
+ const [x0, y0, x1, y1] = Matrix.mapPoints(
38
+ createSceneGeometry(graph, preview).screenMatrix(node, viewport),
39
+ [0, 0, node.width, node.height]
40
+ )
41
+ return {
42
+ x: Math.min(x0, x1),
43
+ y: Math.min(y0, y1),
44
+ width: Math.abs(x1 - x0),
45
+ height: Math.abs(y1 - y0)
46
+ }
47
+ }
48
+
30
49
  /** A read-only view for one draw or input operation. Recreate when the preview changes. */
31
50
  export function createSceneGeometry(graph: SceneGraph, preview?: RotationPreview | null) {
32
51
  const node = (source: SceneNode) => projectedNode(source, preview)
@@ -1,3 +1,11 @@
1
+ import type { Vector } from '@pairdraw/scene-graph/primitives'
2
+
3
+ /** A straight segment between two points. */
4
+ export interface LineSegment {
5
+ from: Vector
6
+ to: Vector
7
+ }
8
+
1
9
  export interface RotationPreview {
2
10
  nodeId: string
3
11
  angle: number