@pairdraw/scene-graph 0.18.0 → 0.19.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 (181) hide show
  1. package/dist/components/index.d.ts +2 -2
  2. package/dist/components/index.js +2 -2
  3. package/dist/components/properties.d.ts +6 -1
  4. package/dist/components/properties.d.ts.map +1 -1
  5. package/dist/components/properties.js +14 -3
  6. package/dist/components/properties.js.map +1 -1
  7. package/dist/copy.d.ts.map +1 -1
  8. package/dist/copy.js +1 -0
  9. package/dist/copy.js.map +1 -1
  10. package/dist/css/gradient.d.ts +23 -0
  11. package/dist/css/gradient.d.ts.map +1 -0
  12. package/dist/css/gradient.js +404 -0
  13. package/dist/css/gradient.js.map +1 -0
  14. package/dist/css/index.d.ts +2 -1
  15. package/dist/css/index.js +2 -1
  16. package/dist/css/shadows.d.ts.map +1 -1
  17. package/dist/css/shadows.js +2 -13
  18. package/dist/css/shadows.js.map +1 -1
  19. package/dist/css/values.js +24 -1
  20. package/dist/css/values.js.map +1 -1
  21. package/dist/font-style.d.ts +2 -1
  22. package/dist/font-style.d.ts.map +1 -1
  23. package/dist/font-style.js +31 -6
  24. package/dist/font-style.js.map +1 -1
  25. package/dist/geometry.d.ts +10 -1
  26. package/dist/geometry.d.ts.map +1 -1
  27. package/dist/geometry.js +21 -6
  28. package/dist/geometry.js.map +1 -1
  29. package/dist/graph.d.ts +49 -3
  30. package/dist/graph.d.ts.map +1 -1
  31. package/dist/graph.js +179 -17
  32. package/dist/graph.js.map +1 -1
  33. package/dist/hit-test.d.ts +3 -1
  34. package/dist/hit-test.d.ts.map +1 -1
  35. package/dist/hit-test.js +38 -23
  36. package/dist/hit-test.js.map +1 -1
  37. package/dist/icons/index.d.ts +2 -2
  38. package/dist/icons/index.js +2 -2
  39. package/dist/icons/model.d.ts +8 -2
  40. package/dist/icons/model.d.ts.map +1 -1
  41. package/dist/icons/model.js +10 -1
  42. package/dist/icons/model.js.map +1 -1
  43. package/dist/index.d.ts +2 -2
  44. package/dist/instances/assignments.js +40 -6
  45. package/dist/instances/assignments.js.map +1 -1
  46. package/dist/instances/fields.d.ts +2 -2
  47. package/dist/instances/fields.d.ts.map +1 -1
  48. package/dist/instances/fields.js +18 -1
  49. package/dist/instances/fields.js.map +1 -1
  50. package/dist/instances/index.d.ts +38 -2
  51. package/dist/instances/index.d.ts.map +1 -1
  52. package/dist/instances/index.js +134 -15
  53. package/dist/instances/index.js.map +1 -1
  54. package/dist/instances/overrides.d.ts +10 -1
  55. package/dist/instances/overrides.d.ts.map +1 -1
  56. package/dist/instances/overrides.js +28 -2
  57. package/dist/instances/overrides.js.map +1 -1
  58. package/dist/instances/placement.js +1 -1
  59. package/dist/instances/placement.js.map +1 -1
  60. package/dist/instances/swap-overrides.js +94 -0
  61. package/dist/instances/swap-overrides.js.map +1 -0
  62. package/dist/instances/sync.js +90 -12
  63. package/dist/instances/sync.js.map +1 -1
  64. package/dist/layout/draw-order.d.ts +11 -0
  65. package/dist/layout/draw-order.d.ts.map +1 -0
  66. package/dist/layout/draw-order.js +14 -0
  67. package/dist/layout/draw-order.js.map +1 -0
  68. package/dist/layout/index.d.ts +2 -1
  69. package/dist/layout/index.js +2 -1
  70. package/dist/node-defaults.d.ts +11 -1
  71. package/dist/node-defaults.d.ts.map +1 -1
  72. package/dist/node-defaults.js +16 -1
  73. package/dist/node-defaults.js.map +1 -1
  74. package/dist/order-keys.d.ts +3 -1
  75. package/dist/order-keys.d.ts.map +1 -1
  76. package/dist/order-keys.js +6 -1
  77. package/dist/order-keys.js.map +1 -1
  78. package/dist/resize.d.ts +29 -9
  79. package/dist/resize.d.ts.map +1 -1
  80. package/dist/resize.js +95 -62
  81. package/dist/resize.js.map +1 -1
  82. package/dist/shared-styles.d.ts.map +1 -1
  83. package/dist/shared-styles.js +1 -8
  84. package/dist/shared-styles.js.map +1 -1
  85. package/dist/slots/authoring.d.ts +3 -2
  86. package/dist/slots/authoring.d.ts.map +1 -1
  87. package/dist/slots/authoring.js +5 -3
  88. package/dist/slots/authoring.js.map +1 -1
  89. package/dist/slots/content.d.ts.map +1 -1
  90. package/dist/slots/content.js +4 -1
  91. package/dist/slots/content.js.map +1 -1
  92. package/dist/source-metadata.d.ts +4 -2
  93. package/dist/source-metadata.d.ts.map +1 -1
  94. package/dist/source-metadata.js +10 -3
  95. package/dist/source-metadata.js.map +1 -1
  96. package/dist/strokes.d.ts +39 -0
  97. package/dist/strokes.d.ts.map +1 -0
  98. package/dist/strokes.js +104 -0
  99. package/dist/strokes.js.map +1 -0
  100. package/dist/text/direction.d.ts +6 -2
  101. package/dist/text/direction.d.ts.map +1 -1
  102. package/dist/text/direction.js +2 -1
  103. package/dist/text/direction.js.map +1 -1
  104. package/dist/text/index.d.ts +3 -3
  105. package/dist/text/index.js +3 -3
  106. package/dist/text/lengths.d.ts +6 -1
  107. package/dist/text/lengths.d.ts.map +1 -1
  108. package/dist/text/lengths.js +10 -1
  109. package/dist/text/lengths.js.map +1 -1
  110. package/dist/text/overflow.d.ts +22 -6
  111. package/dist/text/overflow.d.ts.map +1 -1
  112. package/dist/text/overflow.js +24 -6
  113. package/dist/text/overflow.js.map +1 -1
  114. package/dist/transfer/nodes.js +9 -5
  115. package/dist/transfer/nodes.js.map +1 -1
  116. package/dist/types.d.ts +18 -2
  117. package/dist/types.d.ts.map +1 -1
  118. package/dist/types.js.map +1 -1
  119. package/dist/undo.d.ts +36 -1
  120. package/dist/undo.d.ts.map +1 -1
  121. package/dist/undo.js +52 -2
  122. package/dist/undo.js.map +1 -1
  123. package/dist/variables/bindings.d.ts +14 -6
  124. package/dist/variables/bindings.d.ts.map +1 -1
  125. package/dist/variables/bindings.js +42 -67
  126. package/dist/variables/bindings.js.map +1 -1
  127. package/dist/variables/formula/signatures.js +1 -1
  128. package/dist/variables/index.d.ts +10 -4
  129. package/dist/variables/index.d.ts.map +1 -1
  130. package/dist/variables/index.js +58 -15
  131. package/dist/variables/index.js.map +1 -1
  132. package/dist/variables/paints.d.ts +101 -0
  133. package/dist/variables/paints.d.ts.map +1 -0
  134. package/dist/variables/paints.js +313 -0
  135. package/dist/variables/paints.js.map +1 -0
  136. package/dist/variables/resolution.d.ts +14 -1
  137. package/dist/variables/resolution.d.ts.map +1 -1
  138. package/dist/variables/resolution.js +44 -4
  139. package/dist/variables/resolution.js.map +1 -1
  140. package/dist/variables/subtree.js +17 -0
  141. package/dist/variables/subtree.js.map +1 -0
  142. package/package.json +6 -1
  143. package/src/components/properties.ts +17 -2
  144. package/src/copy.ts +1 -0
  145. package/src/css/gradient.ts +438 -0
  146. package/src/css/index.ts +1 -0
  147. package/src/css/shadows.ts +2 -18
  148. package/src/css/values.ts +27 -1
  149. package/src/font-style.ts +38 -4
  150. package/src/geometry.ts +25 -6
  151. package/src/graph.ts +207 -17
  152. package/src/hit-test.ts +67 -24
  153. package/src/icons/model.ts +11 -1
  154. package/src/instances/assignments.ts +65 -7
  155. package/src/instances/fields.ts +21 -0
  156. package/src/instances/index.ts +237 -14
  157. package/src/instances/overrides.ts +36 -1
  158. package/src/instances/placement.ts +5 -1
  159. package/src/instances/swap-overrides.ts +123 -0
  160. package/src/instances/sync.ts +139 -12
  161. package/src/layout/draw-order.ts +13 -0
  162. package/src/layout/index.ts +1 -0
  163. package/src/node-defaults.ts +21 -0
  164. package/src/order-keys.ts +6 -0
  165. package/src/resize.ts +133 -69
  166. package/src/shared-styles.ts +1 -3
  167. package/src/slots/authoring.ts +5 -3
  168. package/src/slots/content.ts +4 -1
  169. package/src/source-metadata.ts +18 -3
  170. package/src/strokes.ts +121 -0
  171. package/src/text/direction.ts +7 -5
  172. package/src/text/lengths.ts +10 -0
  173. package/src/text/overflow.ts +30 -7
  174. package/src/transfer/nodes.ts +7 -5
  175. package/src/types.ts +17 -0
  176. package/src/undo.ts +79 -2
  177. package/src/variables/bindings.ts +52 -74
  178. package/src/variables/index.ts +80 -14
  179. package/src/variables/paints.ts +413 -0
  180. package/src/variables/resolution.ts +56 -5
  181. package/src/variables/subtree.ts +15 -0
package/src/copy.ts CHANGED
@@ -42,6 +42,7 @@ export function copyFill<T extends Fill>(f: T): T {
42
42
  }))
43
43
  }
44
44
  if (f.patternSpacing) copy.patternSpacing = { ...f.patternSpacing }
45
+ if (f.filters) copy.filters = { ...f.filters }
45
46
  if (f.noiseSize) copy.noiseSize = { ...f.noiseSize }
46
47
  return copy
47
48
  }
@@ -0,0 +1,438 @@
1
+ import valueParser, { type FunctionNode, type Node } from 'postcss-value-parser'
2
+
3
+ import { parseDisplayableColor } from '../color'
4
+ import { TRANSPARENT } from '../constants'
5
+ import { ellipticalGradientTransform, linearGradientTransform } from '../gradient'
6
+ import type { Color, Vector } from '../primitives'
7
+ import type { Fill, GradientStop } from '../types'
8
+ import { cssDimension, cssLayers } from './values'
9
+
10
+ /**
11
+ * One `background-image` layer as CSS paints it: a gradient paint, or an image address the
12
+ * importer fetches. Layers stay in CSS order, the first painted on top.
13
+ */
14
+ export type CSSBackgroundLayer = { kind: 'gradient'; fill: Fill } | { kind: 'image'; url: string }
15
+
16
+ /** The gradient's argument layers; an empty layer paints nothing, so it is dropped. */
17
+ function layersOf(nodes: Node[]): Node[][] {
18
+ return cssLayers(nodes).filter((layer) => layer.length > 0)
19
+ }
20
+
21
+ /** A CSS angle in degrees, or null for anything else. Unitless zero is allowed. */
22
+ function angleOf(node: Node | undefined): number | null {
23
+ const dimension = cssDimension(node)
24
+ if (!dimension) return null
25
+ const { value, unit } = dimension
26
+ switch (unit) {
27
+ case 'deg':
28
+ return value
29
+ case 'grad':
30
+ return value * 0.9
31
+ case 'rad':
32
+ return (value * 180) / Math.PI
33
+ case 'turn':
34
+ return value * 360
35
+ case '':
36
+ return value === 0 ? 0 : null
37
+ default:
38
+ return null
39
+ }
40
+ }
41
+
42
+ /** A length in pixels or a percentage of `basis`; null for anything else. */
43
+ function lengthOf(node: Node | undefined, basis: number): number | null {
44
+ const dimension = cssDimension(node)
45
+ if (!dimension) return null
46
+ const { value, unit } = dimension
47
+ switch (unit) {
48
+ case 'px':
49
+ return value
50
+ case '%':
51
+ return (value / 100) * basis
52
+ case '':
53
+ return value === 0 ? 0 : null
54
+ default:
55
+ return null
56
+ }
57
+ }
58
+
59
+ const SIDE_ANGLES: Record<string, number> = { top: 0, right: 90, bottom: 180, left: 270 }
60
+
61
+ /**
62
+ * The direction of a linear gradient in degrees, CSS convention: 0 points up, clockwise.
63
+ * `to <corner>` aims at that corner; the line length then follows from the angle.
64
+ */
65
+ function directionOf(nodes: Node[], width: number, height: number): number | null {
66
+ const first = nodes[0]
67
+ if (first.type === 'word' && first.value.toLowerCase() === 'to') {
68
+ const sides = nodes
69
+ .slice(1)
70
+ .map((node) => (node.type === 'word' ? node.value.toLowerCase() : ''))
71
+ if (sides.length === 1 && Object.hasOwn(SIDE_ANGLES, sides[0])) {
72
+ return SIDE_ANGLES[sides[0]]
73
+ }
74
+ if (sides.length === 2) {
75
+ const vertical = sides.find((side) => side === 'top' || side === 'bottom')
76
+ const horizontal = sides.find((side) => side === 'left' || side === 'right')
77
+ if (vertical && horizontal && width > 0 && height > 0) {
78
+ const corner = (Math.atan2(width, height) * 180) / Math.PI
79
+ if (vertical === 'top') return horizontal === 'right' ? corner : 360 - corner
80
+ return horizontal === 'right' ? 180 - corner : 180 + corner
81
+ }
82
+ }
83
+ return null
84
+ }
85
+ return angleOf(first)
86
+ }
87
+
88
+ /**
89
+ * A stop's color and its optional one or two positions, as fractions of the gradient line.
90
+ * A pixel position resolves against `pixelBasis`, the line's length in pixels; a gradient that
91
+ * has none (a conic sweep) rejects pixel positions.
92
+ */
93
+ interface StopDraft {
94
+ color: Color
95
+ positions: number[]
96
+ }
97
+
98
+ function stopFraction(node: Node, pixelBasis: number | null): number | null {
99
+ const dimension = cssDimension(node)
100
+ if (!dimension) return null
101
+ const { value, unit } = dimension
102
+ switch (unit) {
103
+ case 'px':
104
+ return pixelBasis === null || pixelBasis <= 0 ? null : value / pixelBasis
105
+ case '%':
106
+ return value / 100
107
+ case '':
108
+ return value === 0 ? 0 : null
109
+ default:
110
+ return null
111
+ }
112
+ }
113
+
114
+ function stopsOf(args: Node[][], pixelBasis: number | null): GradientStop[] | null {
115
+ const drafts: StopDraft[] = []
116
+ for (const arg of args) {
117
+ const color = parseDisplayableColor(valueParser.stringify(arg[0]))
118
+ if (!color) return null
119
+ const positions: number[] = []
120
+ for (const node of arg.slice(1)) {
121
+ const fraction = stopFraction(node, pixelBasis)
122
+ if (fraction === null) return null
123
+ positions.push(fraction)
124
+ }
125
+ if (positions.length > 2) return null
126
+ drafts.push({ color, positions })
127
+ }
128
+ if (drafts.length < 2) return null
129
+
130
+ // Missing positions spread evenly between the nearest positioned neighbors; a first stop
131
+ // without one sits at 0 and a last at 1. Positions never move backwards.
132
+ const resolved: (number | null)[] = drafts.map((draft) => draft.positions[0] ?? null)
133
+ resolved[0] ??= 0
134
+ resolved[resolved.length - 1] ??= 1
135
+ let anchor = 0
136
+ for (let index = 1; index < resolved.length - 1; index++) {
137
+ if (resolved[index] !== null) {
138
+ anchor = index
139
+ continue
140
+ }
141
+ let next = index + 1
142
+ while (resolved[next] === null) next++
143
+ const from = resolved[anchor] ?? 0
144
+ const to = resolved[next] ?? 1
145
+ resolved[index] = from + ((to - from) * (index - anchor)) / (next - anchor)
146
+ }
147
+ let previous = 0
148
+ const stops: GradientStop[] = []
149
+ drafts.forEach((draft, index) => {
150
+ const position = Math.max(resolved[index] ?? 0, previous)
151
+ previous = position
152
+ stops.push({ color: draft.color, position })
153
+ if (draft.positions.length === 2) {
154
+ previous = Math.max(draft.positions[1] ?? position, position)
155
+ stops.push({ color: draft.color, position: previous })
156
+ }
157
+ })
158
+ return stops
159
+ }
160
+
161
+ const POSITION_KEYWORDS: Record<string, Partial<Vector>> = {
162
+ left: { x: 0 },
163
+ right: { x: 1 },
164
+ top: { y: 0 },
165
+ bottom: { y: 1 },
166
+ center: {}
167
+ }
168
+
169
+ /** The unit-square point of a CSS position pair such as `25% 75%` or `left top`. */
170
+ function positionOf(nodes: Node[], width: number, height: number): Vector | null {
171
+ const point: Vector = { x: 0.5, y: 0.5 }
172
+ if (nodes.length === 0) return point
173
+ let axis = 0
174
+ for (const node of nodes) {
175
+ if (node.type === 'word' && node.value.toLowerCase() in POSITION_KEYWORDS) {
176
+ Object.assign(point, POSITION_KEYWORDS[node.value.toLowerCase()])
177
+ axis++
178
+ continue
179
+ }
180
+ const fraction = lengthOf(node, axis === 0 ? width : height)
181
+ if (fraction === null) return null
182
+ if (axis === 0) point.x = width > 0 ? fraction / width : 0.5
183
+ else point.y = height > 0 ? fraction / height : 0.5
184
+ axis++
185
+ }
186
+ return axis > 0 && axis <= 2 ? point : null
187
+ }
188
+
189
+ function linearGradient(fn: FunctionNode, width: number, height: number): Fill | null {
190
+ const args = layersOf(fn.nodes)
191
+ if (args.length === 0) return null
192
+ let stopArgs = args
193
+ let degrees = 180
194
+ const head = args[0] ?? []
195
+ const first = head[0]
196
+ const isDirection =
197
+ first.type === 'word' && (first.value.toLowerCase() === 'to' || angleOf(first) !== null)
198
+ if (isDirection) {
199
+ const direction = directionOf(head, width, height)
200
+ if (direction === null) return null
201
+ degrees = direction
202
+ stopArgs = args.slice(1)
203
+ }
204
+ // CSS gradient line: through the center, length |w sin a| + |h cos a|, so the bands at 0
205
+ // and 1 pass the box corners. Screen y grows downward; 0deg points up.
206
+ const radians = (degrees * Math.PI) / 180
207
+ const dir = { x: Math.sin(radians), y: -Math.cos(radians) }
208
+ const lineLength = Math.abs(width * dir.x) + Math.abs(height * dir.y)
209
+ const stops = stopsOf(stopArgs, lineLength)
210
+ if (!stops || width <= 0 || height <= 0) return null
211
+
212
+ const half = lineLength / 2
213
+ const start = { x: 0.5 - (dir.x * half) / width, y: 0.5 - (dir.y * half) / height }
214
+ const end = { x: 0.5 + (dir.x * half) / width, y: 0.5 + (dir.y * half) / height }
215
+ return {
216
+ type: 'GRADIENT_LINEAR',
217
+ color: { ...TRANSPARENT },
218
+ gradientStops: stops,
219
+ gradientTransform: linearGradientTransform(start, end, width, height),
220
+ opacity: 1,
221
+ visible: true
222
+ }
223
+ }
224
+
225
+ const SIZE_KEYWORDS: Record<string, true> = {
226
+ 'closest-side': true,
227
+ 'closest-corner': true,
228
+ 'farthest-side': true,
229
+ 'farthest-corner': true
230
+ }
231
+
232
+ /** Whether a radial gradient's first argument is its shape/size/position header, not a stop. */
233
+ function isRadialHeader(nodes: Node[], width: number): boolean {
234
+ if (nodes.length === 0) return false
235
+ const words = nodes.map((node) => (node.type === 'word' ? node.value.toLowerCase() : ''))
236
+ if (words.includes('at')) return true
237
+ if (
238
+ words.some(
239
+ (word) => word === 'circle' || word === 'ellipse' || Object.hasOwn(SIZE_KEYWORDS, word)
240
+ )
241
+ ) {
242
+ return true
243
+ }
244
+ if (parseDisplayableColor(valueParser.stringify(nodes[0])) !== null) return false
245
+ return nodes.length <= 2 && nodes.every((node) => lengthOf(node, width) !== null)
246
+ }
247
+
248
+ /** A radial gradient's shape: a circle or ellipse, its size keyword, and explicit radii. */
249
+ interface RadialShape {
250
+ circle: boolean
251
+ sizeKeyword: string
252
+ radii: number[]
253
+ center: Vector
254
+ }
255
+
256
+ /** The shape/size/position header, or null when it is malformed. */
257
+ function radialHeader(head: Node[], width: number, height: number): RadialShape | null {
258
+ const at = head.findIndex((node) => node.type === 'word' && node.value.toLowerCase() === 'at')
259
+ const shapePart = at === -1 ? head : head.slice(0, at)
260
+ const positionPart = at === -1 ? [] : head.slice(at + 1)
261
+ let circle = false
262
+ let sizeKeyword = 'farthest-corner'
263
+ const radii: number[] = []
264
+ for (const node of shapePart) {
265
+ if (node.type !== 'word') return null
266
+ const word = node.value.toLowerCase()
267
+ if (word === 'circle') circle = true
268
+ else if (word === 'ellipse') circle = false
269
+ else if (Object.hasOwn(SIZE_KEYWORDS, word)) sizeKeyword = word
270
+ else {
271
+ const radius = lengthOf(node, radii.length === 0 || circle ? width : height)
272
+ if (radius === null || radius < 0) return null
273
+ radii.push(radius)
274
+ }
275
+ }
276
+ if (radii.length === 1) circle = true
277
+ if (radii.length > 2 || (circle && radii.length === 2)) return null
278
+ const center = positionOf(positionPart, width, height)
279
+ if (!center) return null
280
+ return { circle, sizeKeyword, radii, center }
281
+ }
282
+
283
+ /** The ellipse radii in pixels a shape paints, per the CSS sizing keywords. */
284
+ function radialRadii(shape: RadialShape, width: number, height: number): Vector | null {
285
+ const { circle, sizeKeyword, radii, center } = shape
286
+ const cx = center.x * width
287
+ const cy = center.y * height
288
+ const farthest = sizeKeyword.startsWith('farthest')
289
+ const pick = (a: number, b: number) => (farthest ? Math.max(a, b) : Math.min(a, b))
290
+ const dx = pick(cx, width - cx)
291
+ const dy = pick(cy, height - cy)
292
+ if (radii.length > 0) {
293
+ const rx = radii[0] ?? 0
294
+ return { x: rx, y: circle ? rx : (radii[1] ?? 0) }
295
+ }
296
+ if (sizeKeyword.endsWith('corner')) {
297
+ // A corner ellipse keeps the side distances' aspect, scaled to reach the corner.
298
+ const distance = Math.hypot(dx, dy)
299
+ return circle ? { x: distance, y: distance } : { x: dx * Math.SQRT2, y: dy * Math.SQRT2 }
300
+ }
301
+ return { x: dx, y: circle ? dx : dy }
302
+ }
303
+
304
+ function radialGradient(fn: FunctionNode, width: number, height: number): Fill | null {
305
+ const args = layersOf(fn.nodes)
306
+ if (args.length === 0 || width <= 0 || height <= 0) return null
307
+ let shape: RadialShape = {
308
+ circle: false,
309
+ sizeKeyword: 'farthest-corner',
310
+ radii: [],
311
+ center: { x: 0.5, y: 0.5 }
312
+ }
313
+ let stopArgs = args
314
+ const head = args[0] ?? []
315
+ if (isRadialHeader(head, width)) {
316
+ const parsed = radialHeader(head, width, height)
317
+ if (!parsed) return null
318
+ shape = parsed
319
+ stopArgs = args.slice(1)
320
+ }
321
+ const radii = radialRadii(shape, width, height)
322
+ if (!radii) return null
323
+ const stops = stopsOf(stopArgs, radii.x)
324
+ if (!stops) return null
325
+ const { center } = shape
326
+ const rx = radii.x
327
+ const ry = radii.y
328
+ if (rx <= 0 || ry <= 0) return null
329
+
330
+ return {
331
+ type: 'GRADIENT_RADIAL',
332
+ color: { ...TRANSPARENT },
333
+ gradientStops: stops,
334
+ gradientTransform: ellipticalGradientTransform(
335
+ center,
336
+ { x: center.x + rx / width, y: center.y },
337
+ { x: center.x, y: center.y + ry / height }
338
+ ),
339
+ opacity: 1,
340
+ visible: true
341
+ }
342
+ }
343
+
344
+ function conicGradient(fn: FunctionNode, width: number, height: number): Fill | null {
345
+ const args = layersOf(fn.nodes)
346
+ if (args.length === 0 || width <= 0 || height <= 0) return null
347
+ let stopArgs = args
348
+ let degrees = 0
349
+ let center: Vector = { x: 0.5, y: 0.5 }
350
+
351
+ const head = args[0] ?? []
352
+ const from = head.findIndex((node) => node.type === 'word' && node.value.toLowerCase() === 'from')
353
+ const at = head.findIndex((node) => node.type === 'word' && node.value.toLowerCase() === 'at')
354
+ if (from !== -1 || at !== -1) {
355
+ if (from !== -1) {
356
+ const angle = angleOf(head[from + 1])
357
+ if (angle === null) return null
358
+ degrees = angle
359
+ }
360
+ if (at !== -1) {
361
+ const positioned = positionOf(head.slice(at + 1), width, height)
362
+ if (!positioned) return null
363
+ center = positioned
364
+ }
365
+ stopArgs = args.slice(1)
366
+ }
367
+
368
+ const stops = stopsOf(stopArgs, null)
369
+ if (!stops) return null
370
+
371
+ // Figma's angular paint starts along gradient-space +x and turns clockwise; CSS starts up.
372
+ // Rotate the start ray by (degrees - 90) so 0deg points up. The sweep is round on screen, so
373
+ // each radius reaches the box edge along its own axis, as a radial gradient's do.
374
+ const radians = ((degrees - 90) * Math.PI) / 180
375
+ const radiusX = {
376
+ x: center.x + (Math.cos(radians) * 0.5) / width,
377
+ y: center.y + (Math.sin(radians) * 0.5) / height
378
+ }
379
+ const radiusY = {
380
+ x: center.x - (Math.sin(radians) * 0.5) / width,
381
+ y: center.y + (Math.cos(radians) * 0.5) / height
382
+ }
383
+ return {
384
+ type: 'GRADIENT_ANGULAR',
385
+ color: { ...TRANSPARENT },
386
+ gradientStops: stops,
387
+ gradientTransform: ellipticalGradientTransform(center, radiusX, radiusY),
388
+ opacity: 1,
389
+ visible: true
390
+ }
391
+ }
392
+
393
+ /** The address inside a `url(...)` function, quotes stripped. */
394
+ function urlOf(fn: FunctionNode): string | null {
395
+ const inner = fn.nodes
396
+ .filter((node) => node.type !== 'space' && node.type !== 'comment')
397
+ .map((node) => (node.type === 'string' ? node.value : valueParser.stringify(node)))
398
+ .join('')
399
+ .trim()
400
+ return inner.length > 0 ? inner : null
401
+ }
402
+
403
+ const GRADIENT_BUILDERS: Partial<
404
+ Record<string, (fn: FunctionNode, width: number, height: number) => Fill | null>
405
+ > = {
406
+ 'linear-gradient': linearGradient,
407
+ 'radial-gradient': radialGradient,
408
+ 'conic-gradient': conicGradient
409
+ }
410
+
411
+ /**
412
+ * The layers of a CSS `background-image` list — `linear-gradient`, `radial-gradient`,
413
+ * `conic-gradient`, and `url(...)` — as paints for a `width` × `height` box, in CSS order
414
+ * (first on top). A layer that is none of these, or malformed, is dropped; an invalid value
415
+ * paints nothing.
416
+ */
417
+ export function parseCSSBackgroundImages(
418
+ value: string | undefined,
419
+ width: number,
420
+ height: number
421
+ ): CSSBackgroundLayer[] {
422
+ if (!value) return []
423
+ const layers: CSSBackgroundLayer[] = []
424
+ for (const layer of layersOf(valueParser(value).nodes)) {
425
+ const fn = layer[0]
426
+ if (fn.type !== 'function' || layer.length > 1) continue
427
+ if (fn.value.toLowerCase() === 'url') {
428
+ const url = urlOf(fn)
429
+ if (url) layers.push({ kind: 'image', url })
430
+ continue
431
+ }
432
+ const build = GRADIENT_BUILDERS[fn.value.toLowerCase()]
433
+ if (!build) continue
434
+ const fill = build(fn, width, height)
435
+ if (fill) layers.push({ kind: 'gradient', fill })
436
+ }
437
+ return layers
438
+ }
package/src/css/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { parseCSSGridTracks } from './grid'
2
+ export { parseCSSBackgroundImages, type CSSBackgroundLayer } from './gradient'
2
3
  export {
3
4
  parseCSSAlignItems,
4
5
  parseCSSAlignSelf,
@@ -4,23 +4,7 @@ import { tryParseColor } from '../color'
4
4
  import { BLACK } from '../constants'
5
5
  import type { Color } from '../primitives'
6
6
  import type { Effect } from '../types'
7
- import { parseCSSNumber } from './values'
8
-
9
- /** The layers of a shadow list, split at its top-level commas. */
10
- function layersOf(nodes: Node[]): Node[][] {
11
- const layers: Node[][] = []
12
- let current: Node[] = []
13
- for (const node of nodes) {
14
- if (node.type === 'div' && node.value === ',') {
15
- layers.push(current)
16
- current = []
17
- } else if (node.type !== 'space' && node.type !== 'comment') {
18
- current.push(node)
19
- }
20
- }
21
- layers.push(current)
22
- return layers
23
- }
7
+ import { cssLayers, parseCSSNumber } from './values'
24
8
 
25
9
  /**
26
10
  * One layer: `inset`, two to four lengths, and a color in any order. Without a color it is
@@ -64,5 +48,5 @@ function shadowOf(nodes: Node[]): Effect[] {
64
48
  */
65
49
  export function parseCSSShadows(value: string | undefined): Effect[] {
66
50
  if (!value) return []
67
- return layersOf(valueParser(value).nodes).flatMap(shadowOf)
51
+ return cssLayers(valueParser(value).nodes).flatMap(shadowOf)
68
52
  }
package/src/css/values.ts CHANGED
@@ -1,4 +1,4 @@
1
- import valueParser from 'postcss-value-parser'
1
+ import valueParser, { type Node } from 'postcss-value-parser'
2
2
 
3
3
  import { parseDisplayableColor } from '../color'
4
4
  import type { Color } from '../primitives'
@@ -41,3 +41,29 @@ export function splitCSSValue(value: string): string[] {
41
41
  .nodes.filter((node) => node.type !== 'space' && node.type !== 'comment')
42
42
  .map((node) => valueParser.stringify(node))
43
43
  }
44
+
45
+ /** The layers of a CSS value list, split at its top-level commas, spaces and comments dropped. */
46
+ export function cssLayers(nodes: Node[]): Node[][] {
47
+ const layers: Node[][] = []
48
+ let current: Node[] = []
49
+ for (const node of nodes) {
50
+ if (node.type === 'div' && node.value === ',') {
51
+ layers.push(current)
52
+ current = []
53
+ } else if (node.type !== 'space' && node.type !== 'comment') {
54
+ current.push(node)
55
+ }
56
+ }
57
+ layers.push(current)
58
+ return layers
59
+ }
60
+
61
+ /** A word's finite number and lowercased unit, or null for anything that is not a dimension. */
62
+ export function cssDimension(node: Node | undefined): { value: number; unit: string } | null {
63
+ if (node?.type !== 'word') return null
64
+ const dimension = valueParser.unit(node.value)
65
+ if (!dimension) return null
66
+ const value = Number(dimension.number)
67
+ if (!Number.isFinite(value)) return null
68
+ return { value, unit: dimension.unit.toLowerCase() }
69
+ }
package/src/font-style.ts CHANGED
@@ -47,17 +47,51 @@ function normalizeFontStyleName(style: string): string {
47
47
  .replace(/[^a-z0-9]+/gu, '')
48
48
  }
49
49
 
50
+ const FONT_WIDTH_NAMES = [
51
+ 'ultracondensed',
52
+ 'ultracompressed',
53
+ 'extracompressed',
54
+ 'extracondensed',
55
+ 'compressed',
56
+ 'condensed',
57
+ 'narrow',
58
+ 'semicompressed',
59
+ 'semicondensed',
60
+ 'demicondensed',
61
+ 'semiexpanded',
62
+ 'semiextended',
63
+ 'expanded',
64
+ 'extended',
65
+ 'wide',
66
+ 'extraexpanded',
67
+ 'extraextended',
68
+ 'ultraexpanded',
69
+ 'ultraextended'
70
+ ]
71
+
72
+ const FONT_WIDTH_NAME = new RegExp(
73
+ FONT_WIDTH_NAMES.toSorted((a, b) => b.length - a.length).join('|'),
74
+ 'u'
75
+ )
76
+
77
+ function weightOfStyleName(name: string): number {
78
+ const numericWeight = name.match(/(?:^|[^0-9])([1-9]00)(?:[^0-9]|$)/u)?.[1]
79
+ return numericWeight ? Number(numericWeight) : (FONT_WEIGHT_BY_STYLE.get(name) ?? 400)
80
+ }
81
+
50
82
  export function parseFontStyle(style: string | undefined): ParsedFontStyle {
51
83
  const raw = style ?? ''
52
- const italic = /(?:italic|oblique)/iu.test(raw)
53
84
  const normalized = normalizeFontStyleName(raw)
54
- const numericWeight = normalized.match(/(?:^|[^0-9])([1-9]00)(?:[^0-9]|$)/u)?.[1]
55
85
  return {
56
- weight: numericWeight ? Number(numericWeight) : (FONT_WEIGHT_BY_STYLE.get(normalized) ?? 400),
57
- italic
86
+ weight: weightOfStyleName(normalized.replace(FONT_WIDTH_NAME, '')),
87
+ italic: /(?:italic|oblique)/iu.test(raw)
58
88
  }
59
89
  }
60
90
 
91
+ export function namesWidth(style: string): boolean {
92
+ return FONT_WIDTH_NAME.test(normalizeFontStyleName(style))
93
+ }
94
+
61
95
  export function styleToWeight(style: string | undefined): number {
62
96
  return parseFontStyle(style).weight
63
97
  }
package/src/geometry.ts CHANGED
@@ -2,7 +2,7 @@ import { arrowCapOverflow } from './arrow-caps'
2
2
  import { getAxisAlignedWorldBounds } from './coordinate'
3
3
  import type { SceneGraph } from './graph'
4
4
  import type { Rect, Vector } from './primitives'
5
- import { textLinesOverflow } from './text/overflow'
5
+ import { textLinesReach } from './text/overflow'
6
6
  import type { Effect, SceneNode, Stroke, StrokeCap, StrokeJoin, VectorNetwork } from './types'
7
7
 
8
8
  export function degToRad(degrees: number): number {
@@ -218,6 +218,22 @@ function miterRatio(network: VectorNetwork, join: StrokeJoin | undefined, limit
218
218
  return ratio
219
219
  }
220
220
 
221
+ const BLUR_SIGMA_PER_RADIUS = 0.43
222
+
223
+ /**
224
+ * The Gaussian sigma that draws a Figma blur radius as Figma does. Measured on Figma 126 exports,
225
+ * layer blur, both shadows, and background blur fall off as a Gaussian of 0.43 × radius; Figma's
226
+ * SVG export writes radius / 2, which is wider (`packages/core/tests/canvas/blur.test.ts`).
227
+ */
228
+ export function blurSigma(radius: number): number {
229
+ return Math.max(0, radius) * BLUR_SIGMA_PER_RADIUS
230
+ }
231
+
232
+ /** The Figma blur radius that draws a Gaussian of `sigma`, the inverse of `blurSigma`. */
233
+ export function blurRadiusForSigma(sigma: number): number {
234
+ return Math.max(0, sigma) / BLUR_SIGMA_PER_RADIUS
235
+ }
236
+
221
237
  export function effectOverflow(effects?: Effect[]) {
222
238
  let left = 0
223
239
  let right = 0
@@ -306,6 +322,7 @@ export interface VisualBoundsNode {
306
322
  textUnderlineOffset?: number | null
307
323
  textDecorationThickness?: number | null
308
324
  derivedTextHeight?: number | null
325
+ textAlignVertical?: string
309
326
  }
310
327
 
311
328
  export function unionVisualBounds(
@@ -539,11 +556,13 @@ export function nodeVisualBounds(
539
556
  bounds = unionVisualBounds(bounds, transformedLocalBounds(node, localGeometry, abs)) ?? bounds
540
557
  }
541
558
 
542
- const linesOverflow = Math.max(textLinesOverflow(node), 0)
543
- // An underline or strikethrough reaches below the last line, turning with the text.
544
- const below = linesOverflow + textDecorationOverflow(node)
545
- if (below > 0) {
546
- const lines = { x: 0, y: 0, width: node.width, height: node.height + below }
559
+ // A fixed-size box lets its lines run past it on the side away from the vertical alignment,
560
+ // and an underline or strikethrough reaches below the last line, turning with the text.
561
+ const reach = textLinesReach(node)
562
+ const above = Math.min(reach.minY, 0)
563
+ const below = Math.max(reach.maxY, node.height) + textDecorationOverflow(node)
564
+ if (above < 0 || below > node.height) {
565
+ const lines = { x: 0, y: above, width: node.width, height: below - above }
547
566
  bounds = unionVisualBounds(bounds, transformedLocalBounds(node, lines, abs)) ?? bounds
548
567
  }
549
568