@open-pencil/scene-graph 0.15.1 → 0.16.0-beta.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 (234) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +607 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +577 -522
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2291 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/group-bounds.js +104 -0
  34. package/dist/chunks/group-bounds.js.map +1 -0
  35. package/dist/chunks/icons/glyph.js +147 -0
  36. package/dist/chunks/icons/glyph.js.map +1 -0
  37. package/dist/chunks/index.js +1724 -663
  38. package/dist/chunks/index.js.map +1 -1
  39. package/dist/color.d.ts +72 -0
  40. package/dist/color.d.ts.map +1 -0
  41. package/dist/color.js +3 -0
  42. package/dist/constants.d.ts +2 -2
  43. package/dist/constants.js +2 -2
  44. package/dist/constants2.d.ts +3 -1
  45. package/dist/constants2.d.ts.map +1 -1
  46. package/dist/coordinate.d.ts +2 -448
  47. package/dist/coordinate.js +2 -2
  48. package/dist/copy.d.ts +1 -1
  49. package/dist/copy.js +1 -1
  50. package/dist/css.d.ts +39 -0
  51. package/dist/css.d.ts.map +1 -0
  52. package/dist/css.js +3 -0
  53. package/dist/geometry.d.ts +1 -1
  54. package/dist/geometry.js +1 -1
  55. package/dist/gradient.d.ts +51 -0
  56. package/dist/gradient.d.ts.map +1 -0
  57. package/dist/gradient.js +132 -0
  58. package/dist/gradient.js.map +1 -0
  59. package/dist/guides.d.ts +2 -2
  60. package/dist/guides.js +39 -0
  61. package/dist/guides.js.map +1 -0
  62. package/dist/hit-test.d.ts +2 -9
  63. package/dist/hit-test.js +176 -34
  64. package/dist/hit-test.js.map +1 -1
  65. package/dist/index.d.ts +4 -8
  66. package/dist/index.js +19 -5
  67. package/dist/instances.d.ts +2 -2
  68. package/dist/instances.js +2 -2
  69. package/dist/layout.d.ts +2 -0
  70. package/dist/layout.js +4 -0
  71. package/dist/node-defaults.d.ts +2 -8
  72. package/dist/node-defaults.js +2 -2
  73. package/dist/order-keys.d.ts +39 -0
  74. package/dist/order-keys.d.ts.map +1 -0
  75. package/dist/order-keys.js +136 -0
  76. package/dist/order-keys.js.map +1 -0
  77. package/dist/parse-path.d.ts +7 -1
  78. package/dist/parse-path.d.ts.map +1 -1
  79. package/dist/parse-path.js +6 -2
  80. package/dist/parse-path.js.map +1 -1
  81. package/dist/polygon.d.ts +53 -0
  82. package/dist/polygon.d.ts.map +1 -0
  83. package/dist/polygon.js +205 -0
  84. package/dist/polygon.js.map +1 -0
  85. package/dist/preview.d.ts +1 -1
  86. package/dist/random.d.ts +7 -0
  87. package/dist/random.d.ts.map +1 -0
  88. package/dist/random.js +2 -0
  89. package/dist/resize.d.ts +11 -2
  90. package/dist/resize.d.ts.map +1 -1
  91. package/dist/resize.js +2 -184
  92. package/dist/snap.d.ts +1 -1
  93. package/dist/text-direction.d.ts +13 -0
  94. package/dist/text-direction.d.ts.map +1 -0
  95. package/dist/text-direction.js +31 -0
  96. package/dist/text-direction.js.map +1 -0
  97. package/dist/text-picture.d.ts +1 -1
  98. package/dist/text-picture.d.ts.map +1 -1
  99. package/dist/text.d.ts +2 -0
  100. package/dist/text.js +3 -0
  101. package/dist/types.d.ts +2121 -15
  102. package/dist/types.d.ts.map +1 -1
  103. package/dist/types.js +2 -1
  104. package/dist/types2.d.ts +2 -2
  105. package/dist/undo.d.ts +2 -2
  106. package/dist/undo.js +2 -2
  107. package/dist/undo2.d.ts +29 -1
  108. package/dist/undo2.d.ts.map +1 -1
  109. package/dist/variables.d.ts +2 -29
  110. package/dist/variables.js +2 -2
  111. package/dist/variant-properties.d.ts +9 -1
  112. package/dist/variant-properties.d.ts.map +1 -1
  113. package/dist/variant-properties.js +36 -1
  114. package/dist/variant-properties.js.map +1 -1
  115. package/dist/vector-network.d.ts +1 -1
  116. package/dist/vector-network.js +1 -1
  117. package/package.json +60 -9
  118. package/src/behaviours/kinds.ts +185 -0
  119. package/src/behaviours/layers.ts +51 -0
  120. package/src/behaviours/model.ts +192 -0
  121. package/src/behaviours/schema.ts +58 -0
  122. package/src/behaviours/spec.ts +223 -0
  123. package/src/buffered-events.ts +64 -0
  124. package/src/color/contrast.ts +31 -0
  125. package/src/color/index.ts +88 -0
  126. package/src/color/management.ts +210 -0
  127. package/src/color/normalize.ts +7 -0
  128. package/src/color/okhcl.ts +201 -0
  129. package/src/comments/document.ts +51 -0
  130. package/src/comments/list.ts +52 -0
  131. package/src/comments/merge.ts +63 -0
  132. package/src/comments/threads.ts +156 -0
  133. package/src/components/exposure.ts +61 -0
  134. package/src/components/properties.ts +18 -15
  135. package/src/components/variants.ts +53 -0
  136. package/src/constants.ts +2 -0
  137. package/src/coordinate.ts +100 -43
  138. package/src/copy.ts +17 -6
  139. package/src/css/grid.ts +70 -0
  140. package/src/css/index.ts +9 -0
  141. package/src/css/layout.ts +53 -0
  142. package/src/css/shadows.ts +68 -0
  143. package/src/css/values.ts +42 -0
  144. package/src/export-format.ts +12 -0
  145. package/src/fields/geometry.ts +11 -0
  146. package/src/fields/text.ts +35 -0
  147. package/src/gradient.ts +166 -0
  148. package/src/group-bounds.ts +131 -0
  149. package/src/guides.ts +39 -0
  150. package/src/hit-test.ts +262 -46
  151. package/src/icons/glyph.ts +128 -0
  152. package/src/icons/model.ts +54 -0
  153. package/src/icons/schema.ts +18 -0
  154. package/src/index.ts +347 -57
  155. package/src/instance-overrides.ts +27 -0
  156. package/src/instances/content-size.ts +58 -0
  157. package/src/instances/copies.ts +239 -0
  158. package/src/instances/cycles.ts +73 -0
  159. package/src/instances/fields.ts +143 -0
  160. package/src/instances/main-component.ts +19 -0
  161. package/src/instances/placement.ts +29 -0
  162. package/src/instances/source-walk.ts +41 -0
  163. package/src/instances/sync.ts +600 -0
  164. package/src/instances/vector-geometry.ts +81 -0
  165. package/src/instances.ts +125 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +41 -12
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/shared-styles.ts +5 -2
  187. package/src/slots/authoring.ts +101 -0
  188. package/src/slots/content.ts +124 -0
  189. package/src/slots/frames.ts +160 -0
  190. package/src/slots/limits.ts +49 -0
  191. package/src/text/direction.ts +55 -0
  192. package/src/text/index.ts +3 -0
  193. package/src/text/lists.ts +138 -0
  194. package/src/text/paragraphs.ts +241 -0
  195. package/src/{text-picture.ts → text/picture.ts} +21 -29
  196. package/src/text/references.ts +50 -0
  197. package/src/transfer/apply.ts +84 -0
  198. package/src/transfer/history.ts +49 -0
  199. package/src/transfer/identity.ts +16 -0
  200. package/src/transfer/index.ts +6 -0
  201. package/src/transfer/nodes.ts +120 -0
  202. package/src/transfer/plan.ts +130 -0
  203. package/src/transfer/references.ts +9 -0
  204. package/src/transfer/remove.ts +39 -0
  205. package/src/transfer/validation.ts +59 -0
  206. package/src/transfer/variables.ts +82 -0
  207. package/src/types.ts +257 -13
  208. package/src/undo.ts +54 -2
  209. package/src/variables/bindings.ts +224 -0
  210. package/src/variables/fields.ts +43 -0
  211. package/src/variables/token.ts +14 -0
  212. package/src/variables/units.ts +15 -0
  213. package/src/variables.ts +118 -69
  214. package/src/variant-properties.ts +50 -0
  215. package/dist/chunks/components/properties.js.map +0 -1
  216. package/dist/chunks/export-scale.js +0 -19
  217. package/dist/chunks/export-scale.js.map +0 -1
  218. package/dist/coordinate.d.ts.map +0 -1
  219. package/dist/coordinate2.d.ts +0 -2
  220. package/dist/guides2.d.ts +0 -11
  221. package/dist/guides2.d.ts.map +0 -1
  222. package/dist/hit-test.d.ts.map +0 -1
  223. package/dist/layout-guides.d.ts +0 -2
  224. package/dist/layout-guides.js +0 -2
  225. package/dist/layout-guides2.d.ts +0 -16
  226. package/dist/layout-guides2.d.ts.map +0 -1
  227. package/dist/node-defaults.d.ts.map +0 -1
  228. package/dist/preview2.d.ts +0 -12
  229. package/dist/preview2.d.ts.map +0 -1
  230. package/dist/resize.js.map +0 -1
  231. package/dist/variables.d.ts.map +0 -1
  232. package/dist/vector-network2.d.ts +0 -32
  233. package/dist/vector-network2.d.ts.map +0 -1
  234. package/src/instance-overrides.test.ts +0 -67
package/src/resize.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  copyStrokes,
6
6
  scaleGeometryPaths
7
7
  } from './copy'
8
+ import { enforcedAspectRatio } from './layout/aspect-ratio'
8
9
  import type { Rect } from './primitives'
9
10
  import type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'
10
11
  import { cloneVectorNetwork } from './vector-network'
@@ -61,21 +62,51 @@ function constrainedAxis(
61
62
  return { position, size }
62
63
  }
63
64
 
65
+ type AxisPlacement = { position: number; size: number }
66
+
67
+ const FLEXIBLE_CONSTRAINTS: ReadonlySet<ConstraintType> = new Set(['STRETCH', 'SCALE'])
68
+
69
+ /** The axis at `size`, keeping the edge or centre its constraint pins where it was placed. */
70
+ function resizedInPlace(
71
+ placed: AxisPlacement,
72
+ size: number,
73
+ constraint: ConstraintType
74
+ ): AxisPlacement {
75
+ if (constraint === 'MAX') return { position: placed.position + placed.size - size, size }
76
+ if (constraint === 'CENTER') return { position: placed.position + (placed.size - size) / 2, size }
77
+ return { position: placed.position, size }
78
+ }
79
+
80
+ /**
81
+ * A locked aspect ratio holds when exactly one axis follows the parent, as in Figma: that axis
82
+ * sizes the other. With both axes following the parent, or neither, the ratio gives way.
83
+ */
84
+ function keepLockedRatio(
85
+ x: AxisPlacement,
86
+ y: AxisPlacement,
87
+ horizontal: ConstraintType,
88
+ vertical: ConstraintType,
89
+ aspectRatio: number | null
90
+ ): { x: AxisPlacement; y: AxisPlacement } {
91
+ const flexibleX = FLEXIBLE_CONSTRAINTS.has(horizontal)
92
+ if (aspectRatio === null || flexibleX === FLEXIBLE_CONSTRAINTS.has(vertical)) return { x, y }
93
+ return flexibleX
94
+ ? { x, y: resizedInPlace(y, x.size / aspectRatio, vertical) }
95
+ : { x: resizedInPlace(x, y.size * aspectRatio, horizontal), y }
96
+ }
97
+
98
+ /** A child's box after its parent resizes, keeping a locked aspect ratio as Figma does. */
64
99
  export function constrainedChildRect(
65
100
  child: Rect,
66
101
  parentBefore: Pick<Rect, 'width' | 'height'>,
67
102
  parentAfter: Pick<Rect, 'width' | 'height'>,
68
103
  horizontal: ConstraintType,
69
- vertical: ConstraintType
104
+ vertical: ConstraintType,
105
+ aspectRatio: number | null = null
70
106
  ): Rect {
71
- const x = constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal)
72
- const y = constrainedAxis(
73
- child.y,
74
- child.height,
75
- parentBefore.height,
76
- parentAfter.height,
77
- vertical
78
- )
107
+ let x = constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal)
108
+ let y = constrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical)
109
+ ;({ x, y } = keepLockedRatio(x, y, horizontal, vertical, aspectRatio))
79
110
  return {
80
111
  x: Math.round(x.position),
81
112
  y: Math.round(y.position),
@@ -84,6 +115,56 @@ export function constrainedChildRect(
84
115
  }
85
116
  }
86
117
 
118
+ function layoutConstrainedAxis(
119
+ position: number,
120
+ size: number,
121
+ parentBefore: number,
122
+ parentAfter: number,
123
+ constraint: ConstraintType
124
+ ): { position: number; size: number } {
125
+ const delta = Math.round(parentAfter) - Math.round(parentBefore)
126
+ if (constraint === 'MAX') return { position: position + delta, size }
127
+ if (constraint === 'CENTER') {
128
+ return { position: position + Math.round(parentAfter / 2) - Math.round(parentBefore / 2), size }
129
+ }
130
+ if (constraint === 'STRETCH') return { position, size: Math.abs(size + delta) }
131
+ if (constraint === 'SCALE' && parentBefore > 0) {
132
+ const scale = parentAfter / parentBefore
133
+ return { position: Math.round(position * scale * 128) / 128, size: size * scale }
134
+ }
135
+ return { position, size }
136
+ }
137
+
138
+ /**
139
+ * Where a child goes when layout resizes its parent, as Figma places a layer that ignores auto
140
+ * layout when its Hug frame grows (measured on desktop 126): Right and Left & right move or grow
141
+ * it by the change in the parent's size rounded to whole pixels, Center by the change in its
142
+ * rounded half, and Scale by the exact ratio, its position to 1/128 of a pixel. Sizes are not
143
+ * rounded, so applying a run of changes one at a time lands where applying them at once does.
144
+ */
145
+ export function layoutConstrainedChildRect(
146
+ child: Rect,
147
+ parentBefore: Pick<Rect, 'width' | 'height'>,
148
+ parentAfter: Pick<Rect, 'width' | 'height'>,
149
+ horizontal: ConstraintType,
150
+ vertical: ConstraintType,
151
+ aspectRatio: number | null = null
152
+ ): Rect {
153
+ const placed = keepLockedRatio(
154
+ layoutConstrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal),
155
+ layoutConstrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical),
156
+ horizontal,
157
+ vertical,
158
+ aspectRatio
159
+ )
160
+ return {
161
+ x: placed.x.position,
162
+ y: placed.y.position,
163
+ width: placed.x.size,
164
+ height: placed.y.size
165
+ }
166
+ }
167
+
87
168
  export function scaledChildRect(
88
169
  child: Rect,
89
170
  parentBefore: Pick<Rect, 'width' | 'height'>,
@@ -209,8 +290,13 @@ export function scaledGeometryChanges(
209
290
  if (orig.strokeGeometry.length > 0) {
210
291
  changes.strokeGeometry = scaleGeometryPaths(orig.strokeGeometry, sx, sy)
211
292
  }
212
- if (orig.derivedTextGlyphs?.length) {
213
- changes.derivedTextGlyphs = scaleDerivedGlyphs(orig.derivedTextGlyphs, sx, sy)
293
+ // Path text scales with its path, including baked path text that kept only rotated glyphs;
294
+ // other text reflows in the new box, so its glyphs are dropped.
295
+ const glyphs = orig.derivedTextGlyphs ?? []
296
+ const pathText =
297
+ !!orig.textPathData || !!orig.textPathBox || glyphs.some((glyph) => (glyph.rotation ?? 0) !== 0)
298
+ if (glyphs.length > 0 && pathText) {
299
+ changes.derivedTextGlyphs = scaleDerivedGlyphs(glyphs, sx, sy)
214
300
  // Keep the layout/selection box in sync with the scaled glyphs. reflow
215
301
  // overrides this when it applies; this covers the fallback where reflow
216
302
  // returns null (no path data) so the box doesn't carry a stale size.
@@ -285,7 +371,8 @@ export function computeConstrainedResizeChanges(
285
371
  parentBefore,
286
372
  parentAfter,
287
373
  child.horizontalConstraint,
288
- child.verticalConstraint
374
+ child.verticalConstraint,
375
+ enforcedAspectRatio(child)
289
376
  )
290
377
  const childChanges: Partial<SceneNode> = {
291
378
  ...rect,
@@ -0,0 +1,2 @@
1
+ export { scaleNodeChanges } from './node'
2
+ export { rescaleNodeTree } from './tree'
@@ -0,0 +1,164 @@
1
+ import { scaleGeometryPaths } from '../copy'
2
+ import { TEXT_PARAGRAPH_SPACING_FIELDS } from '../text/paragraphs'
3
+ import {
4
+ type Effect,
5
+ type Fill,
6
+ type GridTrack,
7
+ type LayoutGrid,
8
+ type SceneNode,
9
+ type Stroke,
10
+ type StyleRun,
11
+ type TextParagraphStyle
12
+ } from '../types'
13
+ import { cloneVectorNetwork } from '../vector-network'
14
+
15
+ function scaledOptional(value: number | null, scale: number): number | null {
16
+ return value == null ? null : value * scale
17
+ }
18
+
19
+ function scaledStrokes(strokes: readonly Stroke[], scale: number): Stroke[] {
20
+ return strokes.map((stroke) => ({
21
+ ...structuredClone(stroke),
22
+ weight: stroke.weight * scale,
23
+ dashPattern: stroke.dashPattern?.map((value) => value * scale)
24
+ }))
25
+ }
26
+
27
+ function scaledEffects(effects: readonly Effect[], scale: number): Effect[] {
28
+ return effects.map((effect) => ({
29
+ ...structuredClone(effect),
30
+ offset: { x: effect.offset.x * scale, y: effect.offset.y * scale },
31
+ radius: effect.radius * scale,
32
+ spread: effect.spread * scale
33
+ }))
34
+ }
35
+
36
+ function scaledFills(fills: readonly Fill[], scale: number): Fill[] {
37
+ return fills.map((fill) => ({
38
+ ...structuredClone(fill),
39
+ scale: fill.scale == null ? undefined : fill.scale * scale,
40
+ spacing: fill.spacing == null ? undefined : fill.spacing * scale,
41
+ patternSpacing: fill.patternSpacing
42
+ ? { x: fill.patternSpacing.x * scale, y: fill.patternSpacing.y * scale }
43
+ : undefined,
44
+ noiseSize: fill.noiseSize
45
+ ? { x: fill.noiseSize.x * scale, y: fill.noiseSize.y * scale }
46
+ : undefined
47
+ }))
48
+ }
49
+
50
+ function scaledStyleRuns(styleRuns: readonly StyleRun[], scale: number): StyleRun[] {
51
+ return styleRuns.map((run) => ({
52
+ ...structuredClone(run),
53
+ style: {
54
+ ...structuredClone(run.style),
55
+ fontSize: run.style.fontSize == null ? undefined : run.style.fontSize * scale,
56
+ letterSpacing: run.style.letterSpacing == null ? undefined : run.style.letterSpacing * scale,
57
+ lineHeight: scaledOptional(run.style.lineHeight ?? null, scale),
58
+ textDecorationThickness: scaledOptional(run.style.textDecorationThickness ?? null, scale),
59
+ textUnderlineOffset: scaledOptional(run.style.textUnderlineOffset ?? null, scale)
60
+ }
61
+ }))
62
+ }
63
+
64
+ function scaledParagraphStyles(
65
+ paragraphs: readonly TextParagraphStyle[],
66
+ scale: number
67
+ ): TextParagraphStyle[] {
68
+ return paragraphs.map((style) => {
69
+ const scaled = { ...style }
70
+ for (const field of TEXT_PARAGRAPH_SPACING_FIELDS) {
71
+ const value = style[field]
72
+ if (value !== undefined) scaled[field] = value * scale
73
+ }
74
+ return scaled
75
+ })
76
+ }
77
+
78
+ function scaledLayoutGrids(grids: readonly LayoutGrid[], scale: number): LayoutGrid[] {
79
+ return grids.map((grid) => ({
80
+ ...structuredClone(grid),
81
+ offset: grid.offset == null ? undefined : grid.offset * scale,
82
+ sectionSize: grid.sectionSize == null ? undefined : grid.sectionSize * scale,
83
+ gutterSize: grid.gutterSize == null ? undefined : grid.gutterSize * scale
84
+ }))
85
+ }
86
+
87
+ function scaledGridTracks(tracks: readonly GridTrack[], scale: number): GridTrack[] {
88
+ return tracks.map((track) => ({
89
+ ...track,
90
+ value: track.sizing === 'FIXED' ? track.value * scale : track.value
91
+ }))
92
+ }
93
+
94
+ function scaledVectorNetwork(node: SceneNode, scale: number): SceneNode['vectorNetwork'] {
95
+ if (!node.vectorNetwork) return null
96
+ const network = cloneVectorNetwork(node.vectorNetwork)
97
+ for (const vertex of network.vertices) {
98
+ vertex.x *= scale
99
+ vertex.y *= scale
100
+ }
101
+ for (const segment of network.segments) {
102
+ segment.tangentStart.x *= scale
103
+ segment.tangentStart.y *= scale
104
+ segment.tangentEnd.x *= scale
105
+ segment.tangentEnd.y *= scale
106
+ }
107
+ return network
108
+ }
109
+
110
+ export function scaleNodeChanges(
111
+ node: SceneNode,
112
+ scale: number,
113
+ scalePosition: boolean
114
+ ): Partial<SceneNode> {
115
+ return {
116
+ x: scalePosition ? node.x * scale : node.x,
117
+ y: scalePosition ? node.y * scale : node.y,
118
+ width: node.width * scale,
119
+ height: node.height * scale,
120
+ minWidth: scaledOptional(node.minWidth, scale),
121
+ maxWidth: scaledOptional(node.maxWidth, scale),
122
+ minHeight: scaledOptional(node.minHeight, scale),
123
+ maxHeight: scaledOptional(node.maxHeight, scale),
124
+ cornerRadius: node.cornerRadius * scale,
125
+ topLeftRadius: node.topLeftRadius * scale,
126
+ topRightRadius: node.topRightRadius * scale,
127
+ bottomRightRadius: node.bottomRightRadius * scale,
128
+ bottomLeftRadius: node.bottomLeftRadius * scale,
129
+ fontSize: node.fontSize * scale,
130
+ letterSpacing: node.letterSpacing * scale,
131
+ lineHeight: scaledOptional(node.lineHeight, scale),
132
+ textDecorationThickness: scaledOptional(node.textDecorationThickness, scale),
133
+ textUnderlineOffset: scaledOptional(node.textUnderlineOffset, scale),
134
+ styleRuns: scaledStyleRuns(node.styleRuns, scale),
135
+ listSpacing: node.listSpacing * scale,
136
+ paragraphSpacing: node.paragraphSpacing * scale,
137
+ paragraphIndent: node.paragraphIndent * scale,
138
+ textParagraphs: scaledParagraphStyles(node.textParagraphs, scale),
139
+ itemSpacing: node.itemSpacing * scale,
140
+ counterAxisSpacing: node.counterAxisSpacing * scale,
141
+ paddingTop: node.paddingTop * scale,
142
+ paddingRight: node.paddingRight * scale,
143
+ paddingBottom: node.paddingBottom * scale,
144
+ paddingLeft: node.paddingLeft * scale,
145
+ gridColumnGap: node.gridColumnGap * scale,
146
+ gridRowGap: node.gridRowGap * scale,
147
+ gridTemplateColumns: scaledGridTracks(node.gridTemplateColumns, scale),
148
+ gridTemplateRows: scaledGridTracks(node.gridTemplateRows, scale),
149
+ strokes: scaledStrokes(node.strokes, scale),
150
+ strokeWeight: node.strokeWeight * scale,
151
+ dashPattern: node.dashPattern.map((value) => value * scale),
152
+ borderTopWeight: node.borderTopWeight * scale,
153
+ borderRightWeight: node.borderRightWeight * scale,
154
+ borderBottomWeight: node.borderBottomWeight * scale,
155
+ borderLeftWeight: node.borderLeftWeight * scale,
156
+ strokeMiterLimit: node.strokeMiterLimit,
157
+ effects: scaledEffects(node.effects, scale),
158
+ fills: scaledFills(node.fills, scale),
159
+ layoutGrids: scaledLayoutGrids(node.layoutGrids, scale),
160
+ vectorNetwork: scaledVectorNetwork(node, scale),
161
+ fillGeometry: scaleGeometryPaths(node.fillGeometry, scale, scale),
162
+ strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale)
163
+ }
164
+ }
@@ -0,0 +1,50 @@
1
+ import type { SceneGraph } from '../index'
2
+ import { findInstanceAncestor } from '../instances'
3
+ import type { SceneNode } from '../types'
4
+ import { scaleVariableBindingUnits } from '../variables/units'
5
+ import { scaleNodeChanges } from './node'
6
+
7
+ const MIN_SCALE = 0.01
8
+ const RESCALABLE_NODE_TYPES = new Set<SceneNode['type']>([
9
+ 'BOOLEAN_OPERATION',
10
+ 'COMPONENT',
11
+ 'COMPONENT_SET',
12
+ 'ELLIPSE',
13
+ 'FRAME',
14
+ 'GROUP',
15
+ 'INSTANCE',
16
+ 'LINE',
17
+ 'POLYGON',
18
+ 'RECTANGLE',
19
+ 'STAR',
20
+ 'TEXT',
21
+ 'VECTOR'
22
+ ])
23
+
24
+ /** Scale a node tree from the root node's top-left, matching Figma's Scale tool. */
25
+ export function rescaleNodeTree(graph: SceneGraph, rootId: string, scale: number): void {
26
+ if (!Number.isFinite(scale)) throw new TypeError('Scale must be a finite number')
27
+ if (scale < MIN_SCALE) throw new RangeError(`Scale must be at least ${MIN_SCALE}`)
28
+ const root = graph.getNode(rootId)
29
+ if (!root || !RESCALABLE_NODE_TYPES.has(root.type))
30
+ throw new Error('rescale() is not supported on this node')
31
+ const nodes: SceneNode[] = [root]
32
+ const collect = (node: SceneNode): void => {
33
+ for (const childId of node.childIds) {
34
+ const child = graph.getNode(childId)
35
+ if (!child) continue
36
+ nodes.push(child)
37
+ collect(child)
38
+ }
39
+ }
40
+ collect(root)
41
+ for (const node of nodes) {
42
+ graph.updateNode(node.id, {
43
+ ...scaleNodeChanges(node, scale, node.id !== rootId),
44
+ ...scaleVariableBindingUnits(node, scale),
45
+ componentScale: findInstanceAncestor(graph, node.id)
46
+ ? node.componentScale * scale
47
+ : node.componentScale
48
+ })
49
+ }
50
+ }
@@ -0,0 +1,98 @@
1
+ import { TRANSPARENT } from '../constants'
2
+ import { computeImageHash } from '../images'
3
+ import { readAllPluginData, withAllPluginData } from '../plugin-data/field'
4
+ import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'
5
+ import { randomHex } from '../random'
6
+ import type { Fill, SceneNode } from '../types'
7
+ import type { ShaderPaint, ShaderPreset } from './schema'
8
+
9
+ /** What shader paints read of a node. */
10
+ type ShaderNode = Pick<SceneNode, 'fills' | 'strokes' | 'pluginData'>
11
+
12
+ /** Every shader a node's fills and strokes draw, whether or not a paint still shows it. */
13
+ export function readShaderPaints(node: Pick<SceneNode, 'pluginData'>): ShaderPaint[] {
14
+ return readAllPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.shader)
15
+ }
16
+
17
+ /**
18
+ * The shader a fill or stroke of `node` draws: an image paint whose image is a shader's frame.
19
+ * Null for any other paint, including one whose image was replaced, which then draws as the
20
+ * image it holds.
21
+ */
22
+ export function shaderOfPaint(
23
+ node: Pick<SceneNode, 'pluginData'>,
24
+ paint: Fill
25
+ ): ShaderPaint | null {
26
+ if (paint.type !== 'IMAGE' || !paint.imageHash) return null
27
+ return readShaderPaints(node).find((shader) => shader.image === paint.imageHash) ?? null
28
+ }
29
+
30
+ /** Whether any paint of `node` draws a shader. */
31
+ export function hasShaderPaint(node: ShaderNode): boolean {
32
+ return [...node.fills, ...node.strokes].some((paint) => shaderOfPaint(node, paint) !== null)
33
+ }
34
+
35
+ /**
36
+ * The node's plugin data with `shaders` set by their image, keeping only shaders a fill or
37
+ * stroke of `paints` still shows, so removing or replacing a paint leaves no entry behind.
38
+ */
39
+ export function withShaderPaints(
40
+ node: Pick<SceneNode, 'pluginData'>,
41
+ paints: readonly Fill[],
42
+ shaders: readonly ShaderPaint[] = []
43
+ ): SceneNode['pluginData'] {
44
+ const shown = new Set(
45
+ paints.flatMap((paint) => (paint.type === 'IMAGE' && paint.imageHash ? [paint.imageHash] : []))
46
+ )
47
+ const byImage = new Map(readShaderPaints(node).map((shader) => [shader.image, shader]))
48
+ for (const shader of shaders) byImage.set(shader.image, shader)
49
+ return withAllPluginData(
50
+ node.pluginData,
51
+ OPEN_PENCIL_PLUGIN_DATA.shader,
52
+ [...byImage.values()].filter((shader) => shown.has(shader.image))
53
+ )
54
+ }
55
+
56
+ /**
57
+ * A new paint that draws `preset`, and the shader entry it shows. Its image names a frame not yet
58
+ * rendered, unique to this paint, so no other paint's entry claims it until the frame is drawn.
59
+ */
60
+ export function createShaderPaint(preset: ShaderPreset): {
61
+ paint: Fill
62
+ shader: ShaderPaint
63
+ } {
64
+ const image = randomHex(20)
65
+ return {
66
+ paint: {
67
+ type: 'IMAGE',
68
+ color: TRANSPARENT,
69
+ opacity: 1,
70
+ visible: true,
71
+ imageHash: image,
72
+ imageScaleMode: 'FILL'
73
+ },
74
+ shader: { image, preset: structuredClone(preset) }
75
+ }
76
+ }
77
+
78
+ /** A short key that tells one preset from another, which a rendered frame records. */
79
+ export function shaderPresetKey(preset: ShaderPreset): string {
80
+ return computeImageHash(new TextEncoder().encode(JSON.stringify(preset)))
81
+ }
82
+
83
+ /**
84
+ * Whether a shader's frame was rendered for its preset at the size `node` has now, so undoing a
85
+ * preset change after reopening the document does not keep a frame of the newer preset.
86
+ */
87
+ export function isShaderFrameCurrent(
88
+ shader: ShaderPaint,
89
+ size: { width: number; height: number }
90
+ ): boolean {
91
+ const { frame } = shader
92
+ return (
93
+ frame !== undefined &&
94
+ frame.preset === shaderPresetKey(shader.preset) &&
95
+ Math.round(frame.width) === Math.round(size.width) &&
96
+ Math.round(frame.height) === Math.round(size.height)
97
+ )
98
+ }
@@ -0,0 +1,48 @@
1
+ import * as v from 'valibot'
2
+
3
+ /** One effect of a shader preset, as the `shaders` library names it, with the effects it holds. */
4
+ export interface ShaderComponent {
5
+ type: string
6
+ id?: string
7
+ props?: Record<string, unknown>
8
+ children?: ShaderComponent[]
9
+ }
10
+
11
+ const shaderComponent: v.GenericSchema<unknown, ShaderComponent> = v.object({
12
+ type: v.pipe(v.string(), v.nonEmpty(), v.maxLength(100)),
13
+ id: v.optional(v.string()),
14
+ props: v.optional(v.record(v.string(), v.unknown())),
15
+ children: v.optional(v.array(v.lazy(() => shaderComponent)))
16
+ })
17
+
18
+ /**
19
+ * A shader as the `shaders` library describes it and shaders.com exports it: a tree of effects,
20
+ * drawn first to last.
21
+ */
22
+ export const shaderPresetSchema = v.object({
23
+ components: v.pipe(v.array(shaderComponent), v.minLength(1)),
24
+ structureVersion: v.optional(v.number())
25
+ })
26
+
27
+ export type ShaderPreset = v.InferOutput<typeof shaderPresetSchema>
28
+
29
+ /**
30
+ * A paint that draws a shader. The paint itself is an image fill of the shader's still frame, so
31
+ * every format and renderer that reads images shows it; this entry says which image it is, the
32
+ * preset that draws it, and the layer size and preset the frame was rendered for, which is
33
+ * missing until it is first rendered.
34
+ */
35
+ export const shaderPaintSchema = v.object({
36
+ image: v.pipe(v.string(), v.nonEmpty()),
37
+ preset: shaderPresetSchema,
38
+ frame: v.optional(
39
+ v.object({
40
+ width: v.pipe(v.number(), v.finite(), v.minValue(0)),
41
+ height: v.pipe(v.number(), v.finite(), v.minValue(0)),
42
+ /** The preset's key (`shaderPresetKey`) when the frame was rendered. */
43
+ preset: v.pipe(v.string(), v.nonEmpty())
44
+ })
45
+ )
46
+ })
47
+
48
+ export type ShaderPaint = v.InferOutput<typeof shaderPaintSchema>
@@ -16,7 +16,8 @@ const STYLE_TYPES = {
16
16
  grid: 'GRID'
17
17
  } as const satisfies Record<SharedStyleKind, SharedStyleType>
18
18
 
19
- const TEXT_STYLE_KEYS = new Set<keyof SceneNode>([
19
+ /** The fields a text style gives what uses it; changing one leaves the style. */
20
+ export const SHARED_TEXT_STYLE_FIELDS = [
20
21
  'fontFamily',
21
22
  'fontWeight',
22
23
  'italic',
@@ -26,7 +27,9 @@ const TEXT_STYLE_KEYS = new Set<keyof SceneNode>([
26
27
  'textDecoration',
27
28
  'textCase',
28
29
  'fontFeatures'
29
- ])
30
+ ] as const satisfies readonly (keyof SceneNode)[]
31
+
32
+ const TEXT_STYLE_KEYS = new Set<keyof SceneNode>(SHARED_TEXT_STYLE_FIELDS)
30
33
 
31
34
  export function sharedStyleRefKey(kind: SharedStyleKind): (typeof STYLE_REF_KEYS)[SharedStyleKind] {
32
35
  return STYLE_REF_KEYS[kind]
@@ -0,0 +1,101 @@
1
+ import type { SceneGraph } from '../index'
2
+ import type { ComponentPropertyDefinition, SceneNode, SlotSettings } from '../types'
3
+ import { slotPropertyId } from './frames'
4
+
5
+ /** The settings a new slot starts with: no limits, any layer allowed. */
6
+ export const DEFAULT_SLOT_SETTINGS: SlotSettings = {
7
+ allowPreferredValuesOnly: false,
8
+ displayEmptyByDefault: false,
9
+ stretchChildOnInsert: false
10
+ }
11
+
12
+ /**
13
+ * The main component a layer belongs to, which defines the slots inside it. Layers of an
14
+ * instance are not authored there, so a layer under an instance has none.
15
+ */
16
+ export function slotOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {
17
+ let current = node.parentId ? graph.getNode(node.parentId) : undefined
18
+ while (current && current.type !== 'CANVAS') {
19
+ if (current.type === 'COMPONENT') return current
20
+ if (current.type === 'INSTANCE') return undefined
21
+ current = current.parentId ? graph.getNode(current.parentId) : undefined
22
+ }
23
+ return undefined
24
+ }
25
+
26
+ /** Whether a frame inside a main component can become a slot. */
27
+ export function canCreateSlot(graph: SceneGraph, node: SceneNode): boolean {
28
+ return node.type === 'FRAME' && !slotPropertyId(node) && !!slotOwner(graph, node)
29
+ }
30
+
31
+ function uniqueSlotName(owner: SceneNode, base: string): string {
32
+ const taken = new Set(owner.componentPropertyDefinitions.map((definition) => definition.name))
33
+ if (!taken.has(base)) return base
34
+ let index = 2
35
+ while (taken.has(`${base} ${index}`)) index++
36
+ return `${base} ${index}`
37
+ }
38
+
39
+ /**
40
+ * Make a frame of a main component a slot: define a SLOT property, named after the frame, on
41
+ * the component and bind the frame's children to it. Instances pick up the slot on their next
42
+ * sync.
43
+ */
44
+ export function createSlotProperty(
45
+ graph: SceneGraph,
46
+ frameId: string,
47
+ id: string
48
+ ): ComponentPropertyDefinition | null {
49
+ const frame = graph.getNode(frameId)
50
+ const owner = frame && canCreateSlot(graph, frame) ? slotOwner(graph, frame) : undefined
51
+ if (!frame || !owner) return null
52
+ const definition: ComponentPropertyDefinition = {
53
+ id,
54
+ name: uniqueSlotName(owner, frame.name.trim() || 'Slot'),
55
+ type: 'SLOT',
56
+ defaultValue: '',
57
+ preferredValues: [],
58
+ slotSettings: { ...DEFAULT_SLOT_SETTINGS }
59
+ }
60
+ graph.updateNode(owner.id, {
61
+ componentPropertyDefinitions: [...owner.componentPropertyDefinitions, definition]
62
+ })
63
+ graph.updateNode(frame.id, {
64
+ componentPropertyReferences: [
65
+ ...frame.componentPropertyReferences,
66
+ { propertyId: id, field: 'SLOT_CONTENT' }
67
+ ]
68
+ })
69
+ return definition
70
+ }
71
+
72
+ /** What a slot's settings panel can change. */
73
+ export type SlotPropertyPatch = Partial<
74
+ Pick<ComponentPropertyDefinition, 'name' | 'description' | 'preferredValues'>
75
+ > & { slotSettings?: Partial<SlotSettings> }
76
+
77
+ /** Change a slot property's name, description, preferred components, or limits. */
78
+ export function updateSlotProperty(
79
+ graph: SceneGraph,
80
+ ownerId: string,
81
+ propertyId: string,
82
+ patch: SlotPropertyPatch
83
+ ): boolean {
84
+ const owner = graph.getNode(ownerId)
85
+ const current = owner?.componentPropertyDefinitions.find(
86
+ (definition) => definition.id === propertyId && definition.type === 'SLOT'
87
+ )
88
+ if (!owner || !current) return false
89
+ const { slotSettings, ...fields } = patch
90
+ const next: ComponentPropertyDefinition = {
91
+ ...current,
92
+ ...fields,
93
+ slotSettings: { ...DEFAULT_SLOT_SETTINGS, ...current.slotSettings, ...slotSettings }
94
+ }
95
+ graph.updateNode(owner.id, {
96
+ componentPropertyDefinitions: owner.componentPropertyDefinitions.map((definition) =>
97
+ definition.id === propertyId ? next : definition
98
+ )
99
+ })
100
+ return true
101
+ }