@open-pencil/scene-graph 0.17.0-beta.4 → 0.17.0-beta.5

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 (283) hide show
  1. package/dist/arrays.d.ts +17 -0
  2. package/dist/arrays.d.ts.map +1 -0
  3. package/dist/arrays.js +38 -0
  4. package/dist/arrays.js.map +1 -0
  5. package/dist/buffered-events.js +1 -1
  6. package/dist/buffered-events.js.map +1 -1
  7. package/dist/clipping.d.ts +7 -1
  8. package/dist/clipping.d.ts.map +1 -1
  9. package/dist/clipping.js +23 -19
  10. package/dist/clipping.js.map +1 -1
  11. package/dist/components/index.d.ts +2 -2
  12. package/dist/components/index.js +2 -2
  13. package/dist/components/properties.d.ts +1 -3
  14. package/dist/components/properties.d.ts.map +1 -1
  15. package/dist/components/properties.js +2 -9
  16. package/dist/components/properties.js.map +1 -1
  17. package/dist/corners.d.ts +22 -0
  18. package/dist/corners.d.ts.map +1 -0
  19. package/dist/corners.js +52 -0
  20. package/dist/corners.js.map +1 -0
  21. package/dist/css/grid.d.ts +4 -1
  22. package/dist/css/grid.d.ts.map +1 -1
  23. package/dist/css/grid.js +16 -7
  24. package/dist/css/grid.js.map +1 -1
  25. package/dist/css/index.d.ts +2 -2
  26. package/dist/css/index.js +2 -2
  27. package/dist/css/values.d.ts +6 -1
  28. package/dist/css/values.d.ts.map +1 -1
  29. package/dist/font-style.d.ts +2 -1
  30. package/dist/font-style.d.ts.map +1 -1
  31. package/dist/font-style.js +31 -6
  32. package/dist/font-style.js.map +1 -1
  33. package/dist/geometry.d.ts +68 -3
  34. package/dist/geometry.d.ts.map +1 -1
  35. package/dist/geometry.js +155 -5
  36. package/dist/geometry.js.map +1 -1
  37. package/dist/gradient.d.ts +9 -2
  38. package/dist/gradient.d.ts.map +1 -1
  39. package/dist/gradient.js +29 -1
  40. package/dist/gradient.js.map +1 -1
  41. package/dist/graph.d.ts +4 -0
  42. package/dist/graph.d.ts.map +1 -1
  43. package/dist/graph.js +30 -4
  44. package/dist/graph.js.map +1 -1
  45. package/dist/group-bounds.d.ts.map +1 -1
  46. package/dist/group-bounds.js +4 -3
  47. package/dist/group-bounds.js.map +1 -1
  48. package/dist/guides.d.ts +11 -2
  49. package/dist/guides.d.ts.map +1 -1
  50. package/dist/guides.js +30 -1
  51. package/dist/guides.js.map +1 -1
  52. package/dist/hit-test.d.ts.map +1 -1
  53. package/dist/hit-test.js +57 -5
  54. package/dist/hit-test.js.map +1 -1
  55. package/dist/icons/fit.d.ts +17 -0
  56. package/dist/icons/fit.d.ts.map +1 -0
  57. package/dist/icons/fit.js +21 -0
  58. package/dist/icons/fit.js.map +1 -0
  59. package/dist/icons/glyph.d.ts.map +1 -1
  60. package/dist/icons/glyph.js +5 -4
  61. package/dist/icons/glyph.js.map +1 -1
  62. package/dist/icons/index.d.ts +2 -1
  63. package/dist/icons/index.js +2 -1
  64. package/dist/images.d.ts +14 -4
  65. package/dist/images.d.ts.map +1 -1
  66. package/dist/images.js +45 -5
  67. package/dist/images.js.map +1 -1
  68. package/dist/instances/assignments.js +39 -6
  69. package/dist/instances/assignments.js.map +1 -1
  70. package/dist/instances/index.d.ts.map +1 -1
  71. package/dist/instances/index.js +39 -2
  72. package/dist/instances/index.js.map +1 -1
  73. package/dist/instances/kept-overrides.js +2 -2
  74. package/dist/instances/kept-overrides.js.map +1 -1
  75. package/dist/instances/matching.js +68 -0
  76. package/dist/instances/matching.js.map +1 -0
  77. package/dist/instances/overrides.d.ts +4 -1
  78. package/dist/instances/overrides.d.ts.map +1 -1
  79. package/dist/instances/overrides.js +13 -1
  80. package/dist/instances/overrides.js.map +1 -1
  81. package/dist/instances/protection.js +67 -0
  82. package/dist/instances/protection.js.map +1 -0
  83. package/dist/instances/swap.js +7 -5
  84. package/dist/instances/swap.js.map +1 -1
  85. package/dist/instances/sync.js +10 -116
  86. package/dist/instances/sync.js.map +1 -1
  87. package/dist/layout/guides.d.ts +17 -1
  88. package/dist/layout/guides.d.ts.map +1 -1
  89. package/dist/layout/guides.js +31 -11
  90. package/dist/layout/guides.js.map +1 -1
  91. package/dist/layout/index.d.ts +4 -2
  92. package/dist/layout/index.js +4 -2
  93. package/dist/layout/limits.d.ts +40 -0
  94. package/dist/layout/limits.d.ts.map +1 -0
  95. package/dist/layout/limits.js +54 -0
  96. package/dist/layout/limits.js.map +1 -0
  97. package/dist/layout/sizing.d.ts.map +1 -1
  98. package/dist/layout/sizing.js +0 -1
  99. package/dist/layout/sizing.js.map +1 -1
  100. package/dist/layout/spacing.d.ts +10 -0
  101. package/dist/layout/spacing.d.ts.map +1 -0
  102. package/dist/layout/spacing.js +12 -0
  103. package/dist/layout/spacing.js.map +1 -0
  104. package/dist/masks.d.ts +28 -0
  105. package/dist/masks.d.ts.map +1 -0
  106. package/dist/masks.js +53 -0
  107. package/dist/masks.js.map +1 -0
  108. package/dist/matrix.d.ts +2 -1
  109. package/dist/matrix.d.ts.map +1 -1
  110. package/dist/matrix.js +14 -1
  111. package/dist/matrix.js.map +1 -1
  112. package/dist/node-defaults.d.ts +9 -1
  113. package/dist/node-defaults.d.ts.map +1 -1
  114. package/dist/node-defaults.js +16 -1
  115. package/dist/node-defaults.js.map +1 -1
  116. package/dist/outline/flatten.d.ts.map +1 -1
  117. package/dist/outline/flatten.js +24 -17
  118. package/dist/outline/flatten.js.map +1 -1
  119. package/dist/outline/hit.d.ts +2 -8
  120. package/dist/outline/hit.d.ts.map +1 -1
  121. package/dist/outline/hit.js +16 -25
  122. package/dist/outline/hit.js.map +1 -1
  123. package/dist/outline/index.d.ts +3 -3
  124. package/dist/outline/index.js +3 -3
  125. package/dist/outline/shapes.d.ts +3 -1
  126. package/dist/outline/shapes.d.ts.map +1 -1
  127. package/dist/outline/shapes.js +18 -39
  128. package/dist/outline/shapes.js.map +1 -1
  129. package/dist/paints/index.d.ts +3 -1
  130. package/dist/paints/index.js +3 -1
  131. package/dist/paints/pattern.d.ts +13 -0
  132. package/dist/paints/pattern.d.ts.map +1 -0
  133. package/dist/paints/pattern.js +47 -0
  134. package/dist/paints/pattern.js.map +1 -0
  135. package/dist/paints/shows.d.ts +11 -0
  136. package/dist/paints/shows.d.ts.map +1 -0
  137. package/dist/paints/shows.js +16 -0
  138. package/dist/paints/shows.js.map +1 -0
  139. package/dist/paths/arc.d.ts +32 -0
  140. package/dist/paths/arc.d.ts.map +1 -0
  141. package/dist/paths/arc.js +49 -0
  142. package/dist/paths/arc.js.map +1 -0
  143. package/dist/paths/index.d.ts +5 -0
  144. package/dist/paths/index.js +5 -0
  145. package/dist/paths/network.d.ts +43 -0
  146. package/dist/paths/network.d.ts.map +1 -0
  147. package/dist/paths/network.js +249 -0
  148. package/dist/paths/network.js.map +1 -0
  149. package/dist/paths/sink.d.ts +20 -0
  150. package/dist/paths/sink.d.ts.map +1 -0
  151. package/dist/paths/sink.js +32 -0
  152. package/dist/paths/sink.js.map +1 -0
  153. package/dist/paths/smooth-corners.d.ts +25 -0
  154. package/dist/paths/smooth-corners.d.ts.map +1 -0
  155. package/dist/paths/smooth-corners.js +196 -0
  156. package/dist/paths/smooth-corners.js.map +1 -0
  157. package/dist/plugin-data/fields.d.ts +4 -0
  158. package/dist/plugin-data/fields.d.ts.map +1 -1
  159. package/dist/plugin-data/fields.js +2 -0
  160. package/dist/plugin-data/fields.js.map +1 -1
  161. package/dist/polygon.d.ts +1 -3
  162. package/dist/polygon.d.ts.map +1 -1
  163. package/dist/polygon.js +1 -16
  164. package/dist/polygon.js.map +1 -1
  165. package/dist/resize.d.ts.map +1 -1
  166. package/dist/resize.js +5 -5
  167. package/dist/resize.js.map +1 -1
  168. package/dist/scaling/node.d.ts.map +1 -1
  169. package/dist/scaling/node.js +25 -3
  170. package/dist/scaling/node.js.map +1 -1
  171. package/dist/text/auto-resize.d.ts +15 -0
  172. package/dist/text/auto-resize.d.ts.map +1 -0
  173. package/dist/text/auto-resize.js +23 -0
  174. package/dist/text/auto-resize.js.map +1 -0
  175. package/dist/text/index.d.ts +4 -3
  176. package/dist/text/index.js +4 -3
  177. package/dist/text/lengths.d.ts +6 -1
  178. package/dist/text/lengths.d.ts.map +1 -1
  179. package/dist/text/lengths.js +10 -1
  180. package/dist/text/lengths.js.map +1 -1
  181. package/dist/text/overflow.d.ts +14 -5
  182. package/dist/text/overflow.d.ts.map +1 -1
  183. package/dist/text/overflow.js +24 -6
  184. package/dist/text/overflow.js.map +1 -1
  185. package/dist/text/path.js +10 -0
  186. package/dist/text/path.js.map +1 -0
  187. package/dist/text/picture.js +5 -5
  188. package/dist/text/picture.js.map +1 -1
  189. package/dist/transfer/dependencies.d.ts.map +1 -1
  190. package/dist/transfer/dependencies.js +3 -2
  191. package/dist/transfer/dependencies.js.map +1 -1
  192. package/dist/transfer/nodes.js +2 -1
  193. package/dist/transfer/nodes.js.map +1 -1
  194. package/dist/types.d.ts +21 -8
  195. package/dist/types.d.ts.map +1 -1
  196. package/dist/types.js.map +1 -1
  197. package/dist/variables/index.d.ts +4 -3
  198. package/dist/variables/index.d.ts.map +1 -1
  199. package/dist/variables/index.js +4 -3
  200. package/dist/variables/index.js.map +1 -1
  201. package/dist/variables/lookup.d.ts +20 -0
  202. package/dist/variables/lookup.d.ts.map +1 -0
  203. package/dist/variables/lookup.js +34 -0
  204. package/dist/variables/lookup.js.map +1 -0
  205. package/dist/variables/paints.d.ts +35 -4
  206. package/dist/variables/paints.d.ts.map +1 -1
  207. package/dist/variables/paints.js +67 -16
  208. package/dist/variables/paints.js.map +1 -1
  209. package/dist/variables/resolution.d.ts +3 -1
  210. package/dist/variables/resolution.d.ts.map +1 -1
  211. package/dist/variables/resolution.js +8 -3
  212. package/dist/variables/resolution.js.map +1 -1
  213. package/dist/variables/subtree.js +1 -1
  214. package/dist/variables/subtree.js.map +1 -1
  215. package/dist/vector-network.d.ts.map +1 -1
  216. package/dist/vector-network.js +12 -76
  217. package/dist/vector-network.js.map +1 -1
  218. package/package.json +25 -1
  219. package/src/arrays.ts +37 -0
  220. package/src/buffered-events.ts +2 -1
  221. package/src/clipping.ts +11 -8
  222. package/src/components/properties.ts +1 -13
  223. package/src/corners.ts +93 -0
  224. package/src/css/grid.ts +21 -7
  225. package/src/css/index.ts +1 -1
  226. package/src/font-style.ts +38 -4
  227. package/src/geometry.ts +219 -6
  228. package/src/gradient.ts +23 -1
  229. package/src/graph.ts +22 -4
  230. package/src/group-bounds.ts +7 -3
  231. package/src/guides.ts +26 -1
  232. package/src/hit-test.ts +68 -10
  233. package/src/icons/fit.ts +24 -0
  234. package/src/icons/glyph.ts +5 -4
  235. package/src/icons/index.ts +1 -0
  236. package/src/images.ts +67 -7
  237. package/src/instances/assignments.ts +65 -7
  238. package/src/instances/index.ts +53 -4
  239. package/src/instances/kept-overrides.ts +2 -5
  240. package/src/instances/matching.ts +101 -0
  241. package/src/instances/overrides.ts +18 -0
  242. package/src/instances/protection.ts +103 -0
  243. package/src/instances/swap.ts +11 -9
  244. package/src/instances/sync.ts +11 -184
  245. package/src/layout/guides.ts +42 -9
  246. package/src/layout/index.ts +2 -0
  247. package/src/layout/limits.ts +64 -0
  248. package/src/layout/sizing.ts +0 -2
  249. package/src/layout/spacing.ts +11 -0
  250. package/src/masks.ts +51 -0
  251. package/src/matrix.ts +15 -2
  252. package/src/node-defaults.ts +23 -3
  253. package/src/outline/flatten.ts +30 -18
  254. package/src/outline/hit.ts +16 -33
  255. package/src/outline/index.ts +2 -2
  256. package/src/outline/shapes.ts +19 -36
  257. package/src/paints/index.ts +2 -0
  258. package/src/paints/pattern.ts +45 -0
  259. package/src/paints/shows.ts +13 -0
  260. package/src/paths/arc.ts +59 -0
  261. package/src/paths/index.ts +4 -0
  262. package/src/paths/network.ts +334 -0
  263. package/src/paths/sink.ts +50 -0
  264. package/src/paths/smooth-corners.ts +356 -0
  265. package/src/plugin-data/fields.ts +2 -0
  266. package/src/polygon.ts +0 -17
  267. package/src/resize.ts +6 -7
  268. package/src/scaling/node.ts +29 -3
  269. package/src/text/auto-resize.ts +25 -0
  270. package/src/text/index.ts +1 -0
  271. package/src/text/lengths.ts +11 -0
  272. package/src/text/overflow.ts +32 -6
  273. package/src/text/path.ts +13 -0
  274. package/src/text/picture.ts +5 -5
  275. package/src/transfer/dependencies.ts +3 -2
  276. package/src/transfer/nodes.ts +2 -1
  277. package/src/types.ts +25 -8
  278. package/src/variables/index.ts +1 -0
  279. package/src/variables/lookup.ts +31 -0
  280. package/src/variables/paints.ts +101 -20
  281. package/src/variables/resolution.ts +14 -2
  282. package/src/variables/subtree.ts +1 -1
  283. package/src/vector-network.ts +17 -138
package/src/geometry.ts CHANGED
@@ -1,6 +1,14 @@
1
1
  import { arrowCapOverflow } from './arrow-caps'
2
2
  import type { Rect, Vector } from './primitives'
3
- import type { Effect, SceneNode, Stroke, StrokeCap, StrokeJoin, VectorNetwork } from './types'
3
+ import type {
4
+ ArcData,
5
+ Effect,
6
+ SceneNode,
7
+ Stroke,
8
+ StrokeCap,
9
+ StrokeJoin,
10
+ VectorNetwork
11
+ } from './types'
4
12
 
5
13
  export { cubicPoint } from './cubic'
6
14
 
@@ -12,6 +20,47 @@ export function radToDeg(radians: number): number {
12
20
  return (radians * 180) / Math.PI
13
21
  }
14
22
 
23
+ const FULL_TURN = 2 * Math.PI
24
+
25
+ /** Layers whose shadows Figma never spreads: a text, boolean, star, polygon or vector. */
26
+ const UNSPREAD_TYPES: ReadonlySet<SceneNode['type']> = new Set<SceneNode['type']>([
27
+ 'TEXT',
28
+ 'BOOLEAN_OPERATION',
29
+ 'STAR',
30
+ 'POLYGON',
31
+ 'VECTOR'
32
+ ])
33
+
34
+ /**
35
+ * Whether a layer's shadows take their spread. Figma spreads those of boxes and ellipses, arcs
36
+ * among them, and frames, and counts it in their render bounds; a text, boolean, star, polygon or
37
+ * vector never spreads (Figma desktop, live).
38
+ */
39
+ export function shadowSpreads(node: Pick<SceneNode, 'type'>): boolean {
40
+ return !UNSPREAD_TYPES.has(node.type)
41
+ }
42
+
43
+ /** The spread a shadow on `node` takes: its own, or none on a layer Figma never spreads. */
44
+ export function shadowSpreadOf(
45
+ node: Pick<SceneNode, 'type'>,
46
+ effect: Pick<Effect, 'spread'>
47
+ ): number {
48
+ return shadowSpreads(node) ? effect.spread : 0
49
+ }
50
+
51
+ /**
52
+ * Whether a sweep from `start` to `end` is a whole turn: less than 0.001 rad short of one draws the
53
+ * whole ellipse in Figma (desktop, live: 0.00095 short is whole, 0.001 short an arc).
54
+ */
55
+ export function sweepsWholeTurn(start: number, end: number): boolean {
56
+ return FULL_TURN - Math.abs(end - start) < 0.001
57
+ }
58
+
59
+ /** Whether an arc sweeps a whole turn, so it is drawn and edited as a whole ellipse or ring. */
60
+ export function isWholeArc(arc: Pick<ArcData, 'startingAngle' | 'endingAngle'>): boolean {
61
+ return sweepsWholeTurn(arc.startingAngle, arc.endingAngle)
62
+ }
63
+
15
64
  export function rotatePoint(px: number, py: number, cx: number, cy: number, rad: number): Vector {
16
65
  const cos = Math.cos(rad)
17
66
  const sin = Math.sin(rad)
@@ -143,16 +192,122 @@ export function polygonVertices(node: {
143
192
  })
144
193
  }
145
194
 
195
+ /** A rectangle's stroke weights, side by side: top, right, bottom, left. */
196
+ export type SideWeights = readonly [top: number, right: number, bottom: number, left: number]
197
+
198
+ type SideStrokeNode = Pick<
199
+ SceneNode,
200
+ | 'independentStrokeWeights'
201
+ | 'borderTopWeight'
202
+ | 'borderRightWeight'
203
+ | 'borderBottomWeight'
204
+ | 'borderLeftWeight'
205
+ >
206
+
207
+ /** The layers the canvas strokes side by side when their sides have weights of their own. */
208
+ const SIDE_STROKE_TYPES: ReadonlySet<string> = new Set<SceneNode['type']>([
209
+ 'FRAME',
210
+ 'RECTANGLE',
211
+ 'ROUNDED_RECTANGLE',
212
+ 'COMPONENT',
213
+ 'INSTANCE',
214
+ 'SECTION',
215
+ 'GROUP'
216
+ ])
217
+
218
+ /**
219
+ * Whether `node` strokes each side by its own weight. A line or vector keeps one weight whatever
220
+ * the flag says, since its outline has no sides.
221
+ */
222
+ export function drawsStrokeSides(node: Partial<SideStrokeNode> & { type?: string }): boolean {
223
+ return node.independentStrokeWeights === true && (!node.type || SIDE_STROKE_TYPES.has(node.type))
224
+ }
225
+
226
+ /** The share of a stroke's weight that lies outside the shape it outlines. */
227
+ export function strokeAlignShare(align: Stroke['align']): number {
228
+ if (align === 'OUTSIDE') return 1
229
+ if (align === 'CENTER') return 0.5
230
+ return 0
231
+ }
232
+
233
+ /** A layer's own side weights: top, right, bottom, left. */
234
+ export function borderWeights(node: SideStrokeNode): SideWeights {
235
+ return [
236
+ node.borderTopWeight,
237
+ node.borderRightWeight,
238
+ node.borderBottomWeight,
239
+ node.borderLeftWeight
240
+ ]
241
+ }
242
+
243
+ /** The weight of each side of `node` under `stroke`, its own when its sides have their own. */
244
+ export function strokeSideWeights(
245
+ node: SideStrokeNode & { type?: string },
246
+ stroke: Pick<Stroke, 'weight'>
247
+ ): SideWeights {
248
+ if (!drawsStrokeSides(node)) return [stroke.weight, stroke.weight, stroke.weight, stroke.weight]
249
+ return borderWeights(node)
250
+ }
251
+
252
+ /** A stroke's weight, or with sides of their own the widest side, for what is not drawn per side. */
253
+ export function strokeWeightOf(
254
+ node: Partial<SideStrokeNode> & { type?: string },
255
+ stroke: Pick<Stroke, 'weight'>
256
+ ): number {
257
+ if (!drawsStrokeSides(node)) return stroke.weight
258
+ return Math.max(
259
+ node.borderTopWeight ?? 0,
260
+ node.borderRightWeight ?? 0,
261
+ node.borderBottomWeight ?? 0,
262
+ node.borderLeftWeight ?? 0
263
+ )
264
+ }
265
+
266
+ /**
267
+ * How far a layer's visible strokes reach past each side of its box: top, right, bottom, left.
268
+ * With sides of their own each side reaches by its own weight (Figma desktop, live: a 1px outside
269
+ * stroke with a 20px right side bounds a 100 × 100 rectangle at 121 × 102).
270
+ */
271
+ export function strokeSideReach(
272
+ node: SideStrokeNode & Pick<SceneNode, 'strokes'> & { type?: string }
273
+ ): SideWeights {
274
+ let reach: SideWeights = [0, 0, 0, 0]
275
+ for (const stroke of node.strokes) {
276
+ if (!stroke.visible) continue
277
+ const share = strokeAlignShare(stroke.align)
278
+ const sides = strokeSideWeights(node, stroke)
279
+ reach = [
280
+ Math.max(reach[0], sides[0] * share),
281
+ Math.max(reach[1], sides[1] * share),
282
+ Math.max(reach[2], sides[2] * share),
283
+ Math.max(reach[3], sides[3] * share)
284
+ ]
285
+ }
286
+ return reach
287
+ }
288
+
146
289
  /**
147
290
  * What shapes how far a layer's stroke reaches past its box: its type, since a line is stroked to
148
291
  * one side, and its join and miter limit, for the tips mitered path corners reach.
149
292
  */
150
- export interface StrokeShape {
293
+ export interface StrokeShape extends Partial<SideStrokeNode> {
151
294
  type?: string
152
295
  strokeJoin?: StrokeJoin
153
296
  strokeMiterLimit?: number
154
297
  }
155
298
 
299
+ /** How far past a path a stroke of `weight` reaches, before mitered corners: a line's stroke lies wholly to one side. */
300
+ function strokeExtent(
301
+ weight: number,
302
+ align: Stroke['align'],
303
+ line: boolean,
304
+ open: boolean
305
+ ): number {
306
+ if (line || align === 'OUTSIDE') return weight
307
+ if (align === 'CENTER' || open) return weight / 2
308
+ return 0
309
+ }
310
+
156
311
  export function strokeOverflow(
157
312
  strokes?: Stroke[],
158
313
  fallbackCap?: StrokeCap,
@@ -168,10 +323,8 @@ export function strokeOverflow(
168
323
  let overflow = 0
169
324
  for (const stroke of strokes ?? []) {
170
325
  if (!stroke.visible) continue
171
- const align = sided ? stroke.align : 'CENTER'
172
- let extra = open ? stroke.weight / 2 : 0
173
- if (line || align === 'OUTSIDE') extra = stroke.weight
174
- else if (align === 'CENTER') extra = stroke.weight / 2
326
+ const weight = strokeWeightOf(shape ?? {}, stroke)
327
+ const extra = strokeExtent(weight, sided ? stroke.align : 'CENTER', line, open)
175
328
  const miter = network
176
329
  ? miterRatio(network, stroke.join ?? shape?.strokeJoin, shape?.strokeMiterLimit)
177
330
  : 1
@@ -247,11 +400,71 @@ export function blurSigma(radius: number): number {
247
400
  return drawnBlurRadius(radius) * BLUR_SIGMA_PER_RADIUS
248
401
  }
249
402
 
403
+ /** Skia's Gaussian kernels end at 3 sigma. */
404
+ const KERNEL_SIGMAS = 3
405
+
406
+ /**
407
+ * How far past what it blurs a Gaussian of `sigma` leaves ink on screen: where Skia's kernel
408
+ * ends, and one more pixel holds its rounding.
409
+ */
410
+ export function kernelReach(sigma: number): number {
411
+ return sigma > 0 ? Math.ceil(KERNEL_SIGMAS * sigma) + 1 : 0
412
+ }
413
+
414
+ /** How far past what it blurs a Figma blur of `radius` leaves ink on screen (`kernelReach`). */
415
+ export function blurReach(radius: number): number {
416
+ return kernelReach(blurSigma(radius))
417
+ }
418
+
419
+ /**
420
+ * The distance, in sigmas, past a straight edge blurred by a Gaussian at which the edge's share
421
+ * drops to `share`: the inverse of the normal tail Q, by Abramowitz and Stegun 26.2.23, which is
422
+ * within 0.00045 of it.
423
+ */
424
+ function gaussianTailDistance(share: number): number {
425
+ if (share <= 0) {
426
+ return Number.POSITIVE_INFINITY
427
+ }
428
+ if (share >= 0.5) {
429
+ return 0
430
+ }
431
+ const s = Math.sqrt(-2 * Math.log(share))
432
+ return (
433
+ s -
434
+ (2.515517 + 0.802853 * s + 0.010328 * s * s) /
435
+ (1 + 1.432788 * s + 0.189269 * s * s + 0.001308 * s * s * s)
436
+ )
437
+ }
438
+
439
+ const COLOR_LEVELS = 255
440
+
441
+ /**
442
+ * How far past its shape a drop shadow of `radius` and colour alpha `alpha` leaves ink on
443
+ * screen. Skia blurs the shape into an 8-bit mask and scales it by `alpha`, so a mask level shows
444
+ * once `alpha` times it rounds to a level: an opaque or half-opaque shadow shows its faintest
445
+ * level, out to where the kernel ends, and a fainter one ends sooner. Measured on CPU raster, the
446
+ * ink ends at 3.0 sigma for alpha 1 and 0.5, 2.4 for 0.25, and 2.1 for 0.1.
447
+ */
448
+ export function shadowReach(radius: number, alpha: number): number {
449
+ const sigma = blurSigma(radius)
450
+ const faintestShownLevel = Math.ceil(0.5 / Math.max(alpha, 1 / COLOR_LEVELS))
451
+ const sigmas = Math.min(
452
+ KERNEL_SIGMAS,
453
+ gaussianTailDistance((faintestShownLevel - 1) / COLOR_LEVELS)
454
+ )
455
+ return Math.ceil(sigmas * sigma) + 1
456
+ }
457
+
250
458
  /** The Figma blur radius that draws a Gaussian of `sigma`, the inverse of `blurSigma`. */
251
459
  export function blurRadiusForSigma(sigma: number): number {
252
460
  return Math.max(0, sigma) / BLUR_SIGMA_PER_RADIUS
253
461
  }
254
462
 
463
+ /**
464
+ * How far a layer's shadows and blurs reach past each side as Figma's render bounds count them:
465
+ * a blur by its radius, a shadow by its radius and spread, moved by its offset. Ink on screen
466
+ * reaches further, to `blurReach`.
467
+ */
255
468
  export function effectOverflow(effects?: Effect[]) {
256
469
  let left = 0
257
470
  let right = 0
package/src/gradient.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { Color, Vector } from './primitives'
1
+ import Matrix from './matrix'
2
+ import type { Color, Rect, Vector } from './primitives'
2
3
  import type { Fill, GradientStop, GradientTransform } from './types'
3
4
 
4
5
  /**
@@ -178,3 +179,24 @@ export function ellipticalGradientTransform(
178
179
  m12: center.y - (xAxis.y + yAxis.y) / 2
179
180
  })
180
181
  }
182
+
183
+ /**
184
+ * The transform that keeps a gradient where it was on the canvas when its layer's box becomes
185
+ * `box`, given in the old box's units, as Figma rewrites it when editing a path resizes the layer
186
+ * (Figma desktop 126: a 200 × 120 box grown to 380 × 160 and moved up 40 gives
187
+ * `[[1.9, 0, 0], [0, 1.333, -0.333]]` from the identity).
188
+ */
189
+ export function gradientTransformInBox(t: GradientTransform, box: Rect): GradientTransform {
190
+ const [m00, m01, m02, m10, m11, m12] = Matrix.multiply(Matrix.fromAffine(t), [
191
+ box.width,
192
+ 0,
193
+ box.x,
194
+ 0,
195
+ box.height,
196
+ box.y,
197
+ 0,
198
+ 0,
199
+ 1
200
+ ])
201
+ return { m00, m01, m02, m10, m11, m12 }
202
+ }
package/src/graph.ts CHANGED
@@ -588,6 +588,7 @@ export class SceneGraph {
588
588
  const node = this.nodes.get(id)
589
589
  if (node) changes = this.sizedChanges(node, changes)
590
590
  const appliedChanges = updateNodePreview(this, id, changes, (node, applied) => {
591
+ for (const observer of this.changeObservers) observer.previewed?.(node)
591
592
  for (const observe of this.previewObservers) observe(node, applied)
592
593
  })
593
594
  if (appliedChanges) this.emitter.emit('node:previewUpdated', id, appliedChanges)
@@ -919,16 +920,33 @@ export class SceneGraph {
919
920
  return Instances.getInstances(this, componentId)
920
921
  }
921
922
 
923
+ /**
924
+ * The descendants of a layer in depth-first order with their depths. Each layer with children is
925
+ * walked once, so a cycle or repeated links in bad data cannot hang it or repeat its subtree.
926
+ */
922
927
  flattenTree(parentId?: string, depth = 0): Array<{ node: SceneNode; depth: number }> {
923
928
  const id = parentId ?? this.rootId
924
929
  const parent = this.nodes.get(id)
925
930
  if (!parent) return []
926
931
  const result: Array<{ node: SceneNode; depth: number }> = []
927
- for (const childId of parent.childIds) {
928
- const child = this.nodes.get(childId)
932
+ const pending = [{ node: parent, depth, index: 0 }]
933
+ const walked = new Set([parent])
934
+ while (pending.length > 0) {
935
+ const frame = pending.at(-1)
936
+ if (!frame) break
937
+ if (frame.index >= frame.node.childIds.length) {
938
+ pending.pop()
939
+ continue
940
+ }
941
+ const child = this.nodes.get(frame.node.childIds[frame.index++])
929
942
  if (!child) continue
930
- result.push({ node: child, depth })
931
- if (child.childIds.length > 0) result.push(...this.flattenTree(childId, depth + 1))
943
+ const container = child.childIds.length > 0
944
+ if (container && walked.has(child)) continue
945
+ result.push({ node: child, depth: frame.depth })
946
+ if (container) {
947
+ walked.add(child)
948
+ pending.push({ node: child, depth: frame.depth + 1, index: 0 })
949
+ }
932
950
  }
933
951
  return result
934
952
  }
@@ -1,5 +1,6 @@
1
1
  import { getAxisAlignedBoundsInParent, getNodeLocalMatrix } from './coordinate'
2
2
  import type { SceneGraph } from './graph'
3
+ import { isVisibleMask, maskRuns } from './masks'
3
4
  import Matrix from './matrix'
4
5
  import { FITTED_CONTAINER_TYPES } from './node-defaults'
5
6
  import type { Rect, Vector } from './primitives'
@@ -77,9 +78,12 @@ function fittedAncestors(graph: SceneGraph, parentIds: Iterable<string>): SceneN
77
78
  */
78
79
  function groupBoundingLayers(children: readonly SceneNode[]): SceneNode[] {
79
80
  const shown = children.filter((child) => child.visible)
80
- const firstMask = shown.findIndex((child) => child.isMask)
81
- if (firstMask === -1) return shown
82
- return [...shown.slice(0, firstMask), ...shown.slice(firstMask).filter((c) => c.isMask)]
81
+ const runs = maskRuns(shown, isVisibleMask)
82
+ if (runs.length === 0) return shown
83
+ return [
84
+ ...shown.slice(0, runs[0].start),
85
+ ...runs.flatMap((run) => shown.slice(run.start, run.maskedStart))
86
+ ]
83
87
  }
84
88
 
85
89
  /**
package/src/guides.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import { getWorldMatrix } from './coordinate'
1
2
  import type { SceneGraph } from './graph'
2
- import type { GUID } from './primitives'
3
+ import Matrix from './matrix'
4
+ import type { GUID, Vector } from './primitives'
3
5
  import type { SceneNode } from './types'
4
6
 
5
7
  export interface CanvasGuide {
@@ -50,3 +52,26 @@ export function guideOwnersOnPage(graph: SceneGraph, pageId: string): SceneNode[
50
52
  }
51
53
  return owners
52
54
  }
55
+
56
+ /**
57
+ * A guide or layout line `owner` carries, across its box from edge to edge at `position` along
58
+ * `axis` in its own axes, in page coordinates: where the canvas draws it, a pointer finds it, and
59
+ * a drag snaps to it.
60
+ */
61
+ export function guideLineInWorld(
62
+ graph: SceneGraph,
63
+ owner: SceneNode,
64
+ axis: CanvasGuide['axis'],
65
+ position: number
66
+ ): { start: Vector; end: Vector } {
67
+ const matrix = getWorldMatrix(owner, graph)
68
+ return axis === 'x'
69
+ ? {
70
+ start: Matrix.mapPoint(matrix, { x: position, y: 0 }),
71
+ end: Matrix.mapPoint(matrix, { x: position, y: owner.height })
72
+ }
73
+ : {
74
+ start: Matrix.mapPoint(matrix, { x: 0, y: position }),
75
+ end: Matrix.mapPoint(matrix, { x: owner.width, y: position })
76
+ }
77
+ }
package/src/hit-test.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  import { hitsConnectorLine } from './connectors/hit'
2
2
  import { getWorldMatrix } from './coordinate'
3
3
  import type { SceneGraph } from './graph'
4
+ import { asMaskShape, isVisibleMask, maskRuns, type MaskRun } from './masks'
4
5
  import Matrix from './matrix'
5
- import { hitsShape, isHitPaint, strokeReach } from './outline/hit'
6
+ import { clipsChildren } from './node-defaults'
7
+ import { hitsShape, strokeReach } from './outline/hit'
8
+ import { paintShows } from './paints/shows'
6
9
  import type { SceneNode, NodeType } from './types'
7
10
 
8
11
  const CONTAINER_TYPES = new Set<NodeType>([
@@ -16,9 +19,9 @@ const CONTAINER_TYPES = new Set<NodeType>([
16
19
  ])
17
20
  const OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])
18
21
 
19
- /** Whether a container's own paints show, so its empty area is drawn (see `isHitPaint`). */
22
+ /** Whether a container's own paints show, so its empty area is drawn (`paintShows`). */
20
23
  function showsPaint(node: SceneNode): boolean {
21
- return node.fills.some(isHitPaint) || node.strokes.some(isHitPaint)
24
+ return node.fills.some(paintShows) || node.strokes.some(paintShows)
22
25
  }
23
26
 
24
27
  function isTopLevel(graph: SceneGraph, node: SceneNode): boolean {
@@ -145,6 +148,51 @@ function hitTestTransparentContainer(
145
148
  return null
146
149
  }
147
150
 
151
+ /**
152
+ * The mask run holding each child, asked for from the top child down: the walk steps back through
153
+ * the runs once rather than searching them for every child.
154
+ */
155
+ function maskRunCursor(
156
+ graph: SceneGraph,
157
+ childIds: readonly string[]
158
+ ): (index: number) => MaskRun | undefined {
159
+ const runs = maskRuns(childIds, (id) => {
160
+ const child = graph.nodes.get(id)
161
+ return child !== undefined && isVisibleMask(child)
162
+ })
163
+ let runIndex = runs.length - 1
164
+ return (index) => {
165
+ while (runIndex >= 0 && runs[runIndex].start > index) runIndex--
166
+ const run = runs.at(runIndex)
167
+ return run && runIndex >= 0 && index >= run.maskedStart ? run : undefined
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Whether the point lies on what a run's masks draw, or there is no run to hold it to. A container
173
+ * mask draws its own paint and its layers, so a click between its layers is outside it.
174
+ */
175
+ function insideMasks(
176
+ graph: SceneGraph,
177
+ px: number,
178
+ py: number,
179
+ childIds: readonly string[],
180
+ run: MaskRun | undefined,
181
+ walk: HitWalk
182
+ ): boolean {
183
+ if (!run) return true
184
+ return childIds.slice(run.start, run.maskedStart).some((id) => {
185
+ const mask = graph.nodes.get(id)
186
+ if (!mask) return false
187
+ if (!CONTAINER_TYPES.has(mask.type)) {
188
+ return hitsLeaf(graph, px, py, asMaskShape(mask), walk.transformCache, 0)
189
+ }
190
+ if (showsPaint(mask) && containsPoint(px, py, mask, graph, walk.transformCache)) return true
191
+ const drawn: HitWalk = { ...walk, deep: true, pad: 0, locked: true }
192
+ return hitTestChildren(graph, px, py, mask.id, drawn) !== null
193
+ })
194
+ }
195
+
148
196
  /** The topmost layer under the point among a container's children. */
149
197
  function hitTestChildren(
150
198
  graph: SceneGraph,
@@ -157,15 +205,30 @@ function hitTestChildren(
157
205
  if (!parent) return null
158
206
  const { transformCache, pad } = walk
159
207
 
160
- if (parent.clipsContent) {
208
+ if (clipsChildren(parent)) {
161
209
  if (!containsPoint(px, py, parent, graph, transformCache)) return null
162
210
  }
163
211
 
212
+ const runAt = maskRunCursor(graph, parent.childIds)
213
+ // Each run's masks are tested once per query, however many siblings they mask.
214
+ const covered = new Map<MaskRun, boolean>()
215
+ const inside = (run: MaskRun | undefined) => {
216
+ if (!run) return true
217
+ let hit = covered.get(run)
218
+ if (hit === undefined) {
219
+ hit = insideMasks(graph, px, py, parent.childIds, run, walk)
220
+ covered.set(run, hit)
221
+ }
222
+ return hit
223
+ }
164
224
  for (let i = parent.childIds.length - 1; i >= 0; i--) {
225
+ const run = runAt(i)
165
226
  const child = graph.nodes.get(parent.childIds[i])
166
227
  // A locked layer and everything in it are invisible to a press and to hover, as in Figma: a
167
228
  // click falls through to what lies under it, and a drag from it draws a marquee.
168
229
  if (!child || child.internalOnly || !child.visible || (child.locked && !walk.locked)) continue
230
+ // Where its masks cut a layer away, a click falls through to what lies under it (Figma, live).
231
+ if (!inside(run)) continue
169
232
  if (CONTAINER_TYPES.has(child.type)) {
170
233
  if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {
171
234
  // A plain click takes an instance or component anywhere in its box, with a fill or
@@ -430,12 +493,7 @@ function dropTargetIn(
430
493
  transformCache: Map<string, boolean>
431
494
  ): SceneNode | null {
432
495
  // A clipped-away part of a child is not under the cursor.
433
- if (
434
- parent.type !== 'CANVAS' &&
435
- parent.clipsContent &&
436
- !containsPoint(px, py, parent, graph, transformCache)
437
- )
438
- return null
496
+ if (clipsChildren(parent) && !containsPoint(px, py, parent, graph, transformCache)) return null
439
497
 
440
498
  for (let i = parent.childIds.length - 1; i >= 0; i--) {
441
499
  const childId = parent.childIds[i]
@@ -0,0 +1,24 @@
1
+ import type { SceneNode } from '../types'
2
+
3
+ /** What centering an icon's glyph needs of a graph. */
4
+ interface GlyphGraph {
5
+ getNode(id: string): SceneNode | undefined
6
+ getChildren(id: string): SceneNode[]
7
+ updateNode(id: string, changes: Partial<SceneNode>): void
8
+ }
9
+
10
+ /**
11
+ * Moves a glyph drawn `size` square at its frame's origin to the middle of the frame, as SVG fits
12
+ * a square view box into a box of another shape. An icon is drawn at its frame's shorter side, so
13
+ * it keeps its shape in a frame that is not square, whether placed or swapped.
14
+ */
15
+ export function centerGlyph(graph: GlyphGraph, frameId: string, size: number): void {
16
+ const frame = graph.getNode(frameId)
17
+ if (!frame) return
18
+ const x = (frame.width - size) / 2
19
+ const y = (frame.height - size) / 2
20
+ if (x === 0 && y === 0) return
21
+ for (const path of graph.getChildren(frameId)) {
22
+ graph.updateNode(path.id, { x: path.x + x, y: path.y + y })
23
+ }
24
+ }
@@ -1,5 +1,6 @@
1
1
  import { omit } from 'es-toolkit'
2
2
 
3
+ import { maxOf, minOf } from '../arrays'
3
4
  import type { Fill, SceneNode, Stroke, VectorNetwork } from '../types'
4
5
  import { readIcon, readIconTint } from './model'
5
6
 
@@ -25,10 +26,10 @@ function shape(network: VectorNetwork | null | undefined) {
25
26
  const f = Math.fround
26
27
  const xs = network.vertices.map((vertex) => f(vertex.x))
27
28
  const ys = network.vertices.map((vertex) => f(vertex.y))
28
- const minX = Math.min(...xs)
29
- const minY = Math.min(...ys)
30
- const sx = 1 / (Math.max(...xs) - minX || 1)
31
- const sy = 1 / (Math.max(...ys) - minY || 1)
29
+ const minX = minOf(xs)
30
+ const minY = minOf(ys)
31
+ const sx = 1 / (maxOf(xs) - minX || 1)
32
+ const sy = 1 / (maxOf(ys) - minY || 1)
32
33
  return {
33
34
  vertices: network.vertices.map((vertex) => [
34
35
  round((f(vertex.x) - minX) * sx),
@@ -1,3 +1,4 @@
1
+ export * from './fit'
1
2
  export * from './glyph'
2
3
  export * from './model'
3
4
  export * from './schema'
package/src/images.ts CHANGED
@@ -3,16 +3,25 @@ import { bytesToHex } from '@noble/hashes/utils.js'
3
3
  import { imageSize as readImageHeader } from 'image-size'
4
4
  import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
5
5
 
6
+ import MatrixMath, { type Mat3 } from './matrix'
6
7
  import type { Matrix, Size } from './primitives'
7
- import type { Fill } from './types'
8
+ import type { Fill, SceneNode } from './types'
9
+
10
+ /** Hashes already computed, by the bytes hashed: a save would otherwise hash every image again. */
11
+ const imageHashes = new WeakMap<Uint8Array, string>()
8
12
 
9
13
  /**
10
14
  * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,
11
15
  * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may
12
- * hold images under other names; anything that hands images to Figma still checks.
16
+ * hold images under other names; anything that hands images to Figma still checks. Each array is
17
+ * hashed once, as image bytes are never written into once read or stored.
13
18
  */
14
19
  export function computeImageHash(data: Uint8Array): string {
15
- return bytesToHex(sha1(data))
20
+ const known = imageHashes.get(data)
21
+ if (known) return known
22
+ const hash = bytesToHex(sha1(data))
23
+ imageHashes.set(data, hash)
24
+ return hash
16
25
  }
17
26
 
18
27
  export type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif'
@@ -134,11 +143,62 @@ export function coverImageTransform(
134
143
  return { m00, m01: 0, m02: (1 - m00) / 2, m10: 0, m11, m12: (1 - m11) / 2 }
135
144
  }
136
145
 
137
- /** The images `paints` show, by their hashes. */
138
- export function imagePaintHashes(paints: Iterable<Fill>): string[] {
139
- return [...paints].flatMap((paint) =>
140
- paint.type === 'IMAGE' && paint.imageHash ? [paint.imageHash] : []
146
+ /**
147
+ * Maps `img`'s pixels onto `node` as `fill` places them. `size` is the image's own size when `img`
148
+ * is a downscaled preview, so a tile keeps its size. A crop places the image by its transform;
149
+ * Fill, Fit and Tile ignore it, as Figma does, and turn the image by `imageRotation` first.
150
+ */
151
+ export function imageFillMatrix(
152
+ fill: Fill,
153
+ node: Pick<SceneNode, 'width' | 'height'>,
154
+ imgW: number,
155
+ imgH: number,
156
+ size: Size = { width: imgW, height: imgH }
157
+ ): Mat3 {
158
+ const scaleMode = fill.imageScaleMode ?? 'FILL'
159
+ if (scaleMode === 'CROP' && fill.imageTransform) {
160
+ const t = fill.imageTransform
161
+ const inverse = MatrixMath.invert(MatrixMath.fromAffine(t))
162
+ if (inverse)
163
+ return MatrixMath.multiply(
164
+ MatrixMath.scaled(node.width, node.height),
165
+ inverse,
166
+ MatrixMath.scaled(1 / imgW, 1 / imgH)
167
+ )
168
+ }
169
+
170
+ const radians = ((fill.imageRotation ?? 0) * Math.PI) / 180
171
+ const cos = Math.abs(Math.cos(radians))
172
+ const sin = Math.abs(Math.sin(radians))
173
+ const turnedW = size.width * cos + size.height * sin
174
+ const turnedH = size.width * sin + size.height * cos
175
+ const turned = MatrixMath.multiply(
176
+ MatrixMath.translated(turnedW / 2, turnedH / 2),
177
+ MatrixMath.rotated(radians),
178
+ MatrixMath.translated(-size.width / 2, -size.height / 2),
179
+ MatrixMath.scaled(size.width / imgW, size.height / imgH)
141
180
  )
181
+ if (scaleMode === 'TILE') {
182
+ const scale = fill.scale && fill.scale > 0 ? fill.scale : 1
183
+ return MatrixMath.multiply(MatrixMath.scaled(scale, scale), turned)
184
+ }
185
+ const fit = scaleMode === 'FIT'
186
+ const scale = (fit ? Math.min : Math.max)(node.width / turnedW, node.height / turnedH)
187
+ return MatrixMath.multiply(
188
+ MatrixMath.translated((node.width - turnedW * scale) / 2, (node.height - turnedH * scale) / 2),
189
+ MatrixMath.scaled(scale, scale),
190
+ turned
191
+ )
192
+ }
193
+
194
+ /** The image a paint draws: an IMAGE paint's own, or the poster frame of a VIDEO paint. */
195
+ export function drawnImageHash(paint: Pick<Fill, 'type' | 'imageHash'>): string | undefined {
196
+ return paint.type === 'IMAGE' || paint.type === 'VIDEO' ? paint.imageHash : undefined
197
+ }
198
+
199
+ /** The images `paints` show, by their hashes: a VIDEO paint shows its poster frame. */
200
+ export function imagePaintHashes(paints: Iterable<Fill>): string[] {
201
+ return [...paints].flatMap((paint) => drawnImageHash(paint) ?? [])
142
202
  }
143
203
 
144
204
  /**