@pairdraw/scene-graph 0.19.0 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/behaviours/index.d.ts +2 -2
  2. package/dist/behaviours/index.js +2 -2
  3. package/dist/behaviours/spec.d.ts +6 -1
  4. package/dist/behaviours/spec.d.ts.map +1 -1
  5. package/dist/behaviours/spec.js +62 -5
  6. package/dist/behaviours/spec.js.map +1 -1
  7. package/dist/canvas-layout.js +66 -0
  8. package/dist/canvas-layout.js.map +1 -0
  9. package/dist/coordinate.js +1 -1
  10. package/dist/css/index.d.ts +2 -2
  11. package/dist/css/index.js +2 -2
  12. package/dist/css/text.d.ts +6 -1
  13. package/dist/css/text.d.ts.map +1 -1
  14. package/dist/css/text.js +20 -1
  15. package/dist/css/text.js.map +1 -1
  16. package/dist/generated/index.d.ts +2 -2
  17. package/dist/generated/index.js +2 -2
  18. package/dist/generated/shape-with-text.d.ts +7 -2
  19. package/dist/generated/shape-with-text.d.ts.map +1 -1
  20. package/dist/generated/shape-with-text.js +20 -3
  21. package/dist/generated/shape-with-text.js.map +1 -1
  22. package/dist/graph.d.ts.map +1 -1
  23. package/dist/graph.js +11 -5
  24. package/dist/graph.js.map +1 -1
  25. package/dist/group-bounds.d.ts +4 -1
  26. package/dist/group-bounds.d.ts.map +1 -1
  27. package/dist/group-bounds.js +11 -1
  28. package/dist/group-bounds.js.map +1 -1
  29. package/dist/hit-test.d.ts.map +1 -1
  30. package/dist/hit-test.js +47 -24
  31. package/dist/hit-test.js.map +1 -1
  32. package/dist/index.d.ts +2 -2
  33. package/dist/node-defaults.d.ts +21 -1
  34. package/dist/node-defaults.d.ts.map +1 -1
  35. package/dist/node-defaults.js +22 -14
  36. package/dist/node-defaults.js.map +1 -1
  37. package/dist/resize.d.ts.map +1 -1
  38. package/dist/resize.js +3 -6
  39. package/dist/resize.js.map +1 -1
  40. package/dist/scaling/node.d.ts.map +1 -1
  41. package/dist/scaling/node.js +23 -3
  42. package/dist/scaling/node.js.map +1 -1
  43. package/dist/shared-styles.d.ts +3 -1
  44. package/dist/shared-styles.d.ts.map +1 -1
  45. package/dist/shared-styles.js +7 -1
  46. package/dist/shared-styles.js.map +1 -1
  47. package/dist/text/path.js +11 -0
  48. package/dist/text/path.js.map +1 -0
  49. package/dist/text/picture.d.ts.map +1 -1
  50. package/dist/text/picture.js +5 -5
  51. package/dist/text/picture.js.map +1 -1
  52. package/dist/transfer/copied.d.ts +14 -0
  53. package/dist/transfer/copied.d.ts.map +1 -0
  54. package/dist/transfer/copied.js +52 -0
  55. package/dist/transfer/copied.js.map +1 -0
  56. package/dist/transfer/index.d.ts +2 -1
  57. package/dist/transfer/index.js +2 -1
  58. package/dist/transfer/nodes.js +7 -0
  59. package/dist/transfer/nodes.js.map +1 -1
  60. package/dist/types.d.ts +3 -2
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/types.js.map +1 -1
  63. package/dist/undo.d.ts +6 -0
  64. package/dist/undo.d.ts.map +1 -1
  65. package/dist/undo.js +13 -0
  66. package/dist/undo.js.map +1 -1
  67. package/dist/variables/index.d.ts.map +1 -1
  68. package/dist/variables/index.js.map +1 -1
  69. package/package.json +1 -1
  70. package/src/behaviours/spec.ts +94 -4
  71. package/src/canvas-layout.ts +76 -0
  72. package/src/css/index.ts +6 -1
  73. package/src/css/text.ts +24 -0
  74. package/src/generated/shape-with-text.ts +28 -2
  75. package/src/graph.ts +14 -4
  76. package/src/group-bounds.ts +13 -0
  77. package/src/hit-test.ts +95 -39
  78. package/src/node-defaults.ts +22 -13
  79. package/src/resize.ts +3 -14
  80. package/src/scaling/node.ts +27 -3
  81. package/src/shared-styles.ts +8 -0
  82. package/src/text/path.ts +14 -0
  83. package/src/text/picture.ts +5 -2
  84. package/src/transfer/copied.ts +72 -0
  85. package/src/transfer/index.ts +1 -0
  86. package/src/transfer/nodes.ts +10 -0
  87. package/src/types.ts +2 -1
  88. package/src/undo.ts +11 -0
  89. package/src/variables/index.ts +1 -4
@@ -0,0 +1,76 @@
1
+ import { FRAME_LAYOUT_DEFAULTS } from './node-defaults'
2
+ import type { SceneNode } from './types'
3
+
4
+ type FrameLayoutField = keyof typeof FRAME_LAYOUT_DEFAULTS
5
+
6
+ /**
7
+ * `overrides` for a node of `type`, without the layout a page cannot hold. A document that names
8
+ * one on a page still loads: the field a page never stores simply does not arrive.
9
+ */
10
+ export function pageLayoutOverrides(
11
+ type: SceneNode['type'],
12
+ overrides: Partial<SceneNode>
13
+ ): Partial<SceneNode> {
14
+ if (type !== 'CANVAS') return overrides
15
+ const kept: Partial<SceneNode> = { ...overrides }
16
+ const taken = (field: FrameLayoutField) =>
17
+ kept[field] !== undefined && kept[field] !== FRAME_LAYOUT_DEFAULTS[field]
18
+ if (taken('layoutMode')) delete kept.layoutMode
19
+ if (taken('layoutDirection')) delete kept.layoutDirection
20
+ if (taken('layoutWrap')) delete kept.layoutWrap
21
+ if (taken('primaryAxisAlign')) delete kept.primaryAxisAlign
22
+ if (taken('counterAxisAlign')) delete kept.counterAxisAlign
23
+ if (taken('primaryAxisSizing')) delete kept.primaryAxisSizing
24
+ if (taken('counterAxisSizing')) delete kept.counterAxisSizing
25
+ if (taken('itemSpacing')) delete kept.itemSpacing
26
+ if (taken('counterAxisSpacing')) delete kept.counterAxisSpacing
27
+ if (taken('paddingTop')) delete kept.paddingTop
28
+ if (taken('paddingRight')) delete kept.paddingRight
29
+ if (taken('paddingBottom')) delete kept.paddingBottom
30
+ if (taken('paddingLeft')) delete kept.paddingLeft
31
+ return kept
32
+ }
33
+
34
+ /** A page was given auto layout or one of the properties an auto layout frame holds. */
35
+ export class CanvasLayoutError extends Error {
36
+ readonly pageId: string
37
+ readonly field: FrameLayoutField
38
+
39
+ constructor(pageId: string, field: FrameLayoutField) {
40
+ super(
41
+ `A page cannot hold auto layout (${field} was set on ${pageId}). Set auto layout on a frame inside the page.`
42
+ )
43
+ this.name = 'CanvasLayoutError'
44
+ this.pageId = pageId
45
+ this.field = field
46
+ }
47
+ }
48
+
49
+ /**
50
+ * `changes` without a geometry value that is not finite. A layout that cannot use its container
51
+ * can compute one; dropping it leaves the layer where it was rather than corrupting the document.
52
+ */
53
+ export function finiteGeometry(changes: Partial<SceneNode>): Partial<SceneNode> {
54
+ const usable = (value: number | undefined) => value === undefined || Number.isFinite(value)
55
+ const { x, y, width, height } = changes
56
+ if (usable(x) && usable(y) && usable(width) && usable(height)) return changes
57
+ const kept: Partial<SceneNode> = { ...changes }
58
+ if (!usable(x)) delete kept.x
59
+ if (!usable(y)) delete kept.y
60
+ if (!usable(width)) delete kept.width
61
+ if (!usable(height)) delete kept.height
62
+ return kept
63
+ }
64
+
65
+ /**
66
+ * Refuses the layout a page cannot hold, before it reaches the graph. Values equal to the ones a
67
+ * page already holds pass, so a reader that writes a whole node leaves a page alone.
68
+ */
69
+ export function assertPageLayout(node: SceneNode, changes: Partial<SceneNode>): void {
70
+ if (node.type !== 'CANVAS') return
71
+ for (const [field, empty] of Object.entries(FRAME_LAYOUT_DEFAULTS)) {
72
+ const value = changes[field as FrameLayoutField]
73
+ if (value !== undefined && value !== empty)
74
+ throw new CanvasLayoutError(node.id, field as FrameLayoutField)
75
+ }
76
+ }
package/src/css/index.ts CHANGED
@@ -7,5 +7,10 @@ export {
7
7
  parseCSSJustifyContent
8
8
  } from './layout'
9
9
  export { parseCSSShadows } from './shadows'
10
- export { parseCSSFontFamily, parseCSSLetterSpacing, parseCSSLineHeight } from './text'
10
+ export {
11
+ parseCSSFontFamilies,
12
+ parseCSSFontFamily,
13
+ parseCSSLetterSpacing,
14
+ parseCSSLineHeight
15
+ } from './text'
11
16
  export { parseCSSColor, parseCSSNumber, splitCSSValue } from './values'
package/src/css/text.ts CHANGED
@@ -45,6 +45,30 @@ export function parseCSSFontFamily(value: string | undefined): string | null {
45
45
  return words.trim().replace(/\s+/gu, ' ') || null
46
46
  }
47
47
 
48
+ /**
49
+ * Every family of a CSS `font-family` list, in order, without quotes and escapes. A quoted family
50
+ * is one name; an unquoted one joins its words with single spaces.
51
+ */
52
+ export function parseCSSFontFamilies(value: string | undefined): string[] {
53
+ const text = value?.trim()
54
+ if (!text) return []
55
+ const families: string[] = []
56
+ let current: valueParser.Node[] = []
57
+ for (const node of valueParser(text).nodes) {
58
+ if (node.type === 'div' && node.value === ',') {
59
+ families.push(valueParser.stringify(current))
60
+ current = []
61
+ } else {
62
+ current.push(node)
63
+ }
64
+ }
65
+ families.push(valueParser.stringify(current))
66
+ return families.flatMap((family) => {
67
+ const parsed = parseCSSFontFamily(family)
68
+ return parsed ? [parsed] : []
69
+ })
70
+ }
71
+
48
72
  /** A CSS dimension's number and lowercase unit, or null. */
49
73
  function dimension(value: string): { number: number; unit: string } | null {
50
74
  const parsed = valueParser.unit(value)
@@ -9,9 +9,15 @@ import type { GeneratedFrameKind } from './kind'
9
9
 
10
10
  /** FigJam makes a shape with text 176 px square, from its tool and from its plugin API. */
11
11
  export const SHAPE_WITH_TEXT_SIZE = 176
12
- /** FigJam rounds every corner of a shape by 6 px. */
12
+ /** FigJam rounds every corner of a shape by 6 px, but a rounded rectangle's. */
13
13
  export const SHAPE_WITH_TEXT_CORNER_RADIUS = 6
14
14
 
15
+ /**
16
+ * FigJam keeps a rounded rectangle's corner radius at 0.4 of its shorter side, through resizes,
17
+ * measured in FigJam; Figma draws the shape from that radius.
18
+ */
19
+ const ROUNDED_RECTANGLE_RADIUS = 0.4
20
+
15
21
  const LABEL_FILL: Fill = { type: 'SOLID', color: { ...BLACK }, opacity: 0.8, visible: true }
16
22
 
17
23
  /** How the label sits in its shape: as wide as the label box, as tall as its text. */
@@ -42,7 +48,27 @@ export function shapeWithTextFrameFields(
42
48
  paddingRight: Math.max(0, width - box.x - box.width),
43
49
  paddingBottom: Math.max(0, height - box.y - box.height),
44
50
  paddingLeft: box.x,
45
- clipsContent: false
51
+ clipsContent: false,
52
+ ...(kind === 'ROUNDED_RECTANGLE'
53
+ ? { cornerRadius: ROUNDED_RECTANGLE_RADIUS * Math.min(width, height) }
54
+ : {})
55
+ }
56
+ }
57
+
58
+ /**
59
+ * What turning a shape into `kind` changes, keeping its size, as FigJam's shape switcher does: the
60
+ * label area, and the corners a rounded rectangle leaves go back to FigJam's 6.
61
+ */
62
+ export function shapeWithTextKindFields(
63
+ shape: Pick<SceneNode, 'shapeWithTextType' | 'width' | 'height'>,
64
+ kind: ShapeWithTextType
65
+ ): Partial<SceneNode> {
66
+ const leavesRounded =
67
+ shape.shapeWithTextType === 'ROUNDED_RECTANGLE' && kind !== shape.shapeWithTextType
68
+ return {
69
+ shapeWithTextType: kind,
70
+ ...(leavesRounded ? { cornerRadius: SHAPE_WITH_TEXT_CORNER_RADIUS } : {}),
71
+ ...shapeWithTextFrameFields(kind, shape.width, shape.height)
46
72
  }
47
73
  }
48
74
 
package/src/graph.ts CHANGED
@@ -4,6 +4,7 @@ import { isEmptyObject, isUndefined } from 'es-toolkit/predicate'
4
4
 
5
5
  import { removeStaleBindings } from './bindings'
6
6
  import { BufferedSceneEmitter } from './buffered-events'
7
+ import { assertPageLayout, finiteGeometry, pageLayoutOverrides } from './canvas-layout'
7
8
  import {
8
9
  getAbsolutePosition,
9
10
  getNodeLocalMatrix,
@@ -491,7 +492,11 @@ export class SceneGraph {
491
492
  createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {
492
493
  const parent = this.nodes.get(parentId)
493
494
  if (!parent) throw new Error(`Parent "${parentId}" does not exist`)
494
- const node = createDefaultNode(() => this.generateEntityId(), type, overrides)
495
+ const node = createDefaultNode(
496
+ () => this.generateEntityId(),
497
+ type,
498
+ pageLayoutOverrides(type, overrides)
499
+ )
495
500
  Object.assign(node, strokeLineChanges(node, overrides))
496
501
  this.willChangeNode(parent)
497
502
  parent.childIds.push(node.id)
@@ -509,7 +514,7 @@ export class SceneGraph {
509
514
  if (parentId === id) throw new Error(`Node "${id}" cannot be its own parent`)
510
515
  const parent = parentId === null ? undefined : this.nodes.get(parentId)
511
516
  if (parentId !== null && !parent) throw new Error(`Parent "${parentId}" does not exist`)
512
- const node = createDefaultNode(() => id, type, overrides)
517
+ const node = createDefaultNode(() => id, type, pageLayoutOverrides(type, overrides))
513
518
  // `overrides` may be another node's snapshot, ID included.
514
519
  node.id = id
515
520
  if (parent && !parent.childIds.includes(id)) {
@@ -641,7 +646,10 @@ export class SceneGraph {
641
646
  }
642
647
  updateNodePreview(id: string, changes: Partial<SceneNode>): void {
643
648
  const node = this.nodes.get(id)
644
- if (node) changes = this.impliedChanges(node, changes)
649
+ if (node) {
650
+ assertPageLayout(node, changes)
651
+ changes = this.impliedChanges(node, finiteGeometry(changes))
652
+ }
645
653
  const appliedChanges = updateNodePreview(this, id, changes, (node, applied) => {
646
654
  for (const observe of this.previewObservers) observe(node, applied)
647
655
  })
@@ -660,7 +668,9 @@ export class SceneGraph {
660
668
 
661
669
  const node = this.nodes.get(id)
662
670
  if (!node) return
663
- this.applyNodeChanges(node, this.impliedChanges(node, omitBy(changes, isUndefined)))
671
+ const given = finiteGeometry(omitBy(changes, isUndefined))
672
+ assertPageLayout(node, given)
673
+ this.applyNodeChanges(node, this.impliedChanges(node, given))
664
674
  }
665
675
 
666
676
  /**
@@ -140,6 +140,18 @@ function removeEmptyGroup(graph: SceneGraph, group: SceneNode, fit: GroupFit) {
140
140
  graph.deleteNode(group.id)
141
141
  }
142
142
 
143
+ /** Fits applied since the last reset, so a test can bound what one pass costs. */
144
+ let groupFits = 0
145
+
146
+ /** How many group fits have been applied since `resetGroupFitCount`. */
147
+ export function groupFitCount(): number {
148
+ return groupFits
149
+ }
150
+
151
+ export function resetGroupFitCount(): void {
152
+ groupFits = 0
153
+ }
154
+
143
155
  /**
144
156
  * Refits the groups and booleans around these parents to their children, keeping every child where
145
157
  * it is on the canvas, and removes groups left empty, as Figma does after a layer inside one moves,
@@ -153,6 +165,7 @@ export function fitEnclosingGroups(
153
165
  ): GroupFit | null {
154
166
  const fit: GroupFit = { before: new Map(), after: new Map(), removed: [] }
155
167
  for (const group of fittedAncestors(graph, parentIds)) {
168
+ groupFits += 1
156
169
  const children = graph.getChildren(group.id)
157
170
  if (children.length === 0) removeEmptyGroup(graph, group, fit)
158
171
  else fitGroup(graph, group, children, fit, options)
package/src/hit-test.ts CHANGED
@@ -23,8 +23,35 @@ const OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])
23
23
  */
24
24
  const DEGENERATE_AXIS_SLOP = 4
25
25
 
26
- function hasVisibleFillOrStroke(node: SceneNode): boolean {
27
- return node.fills.some((f) => f.visible) || node.strokes.some((s) => s.visible)
26
+ /**
27
+ * Whether a paint shows, so its container's empty area counts when a click reaches past
28
+ * containers: a paint at 0% opacity, or a gradient whose stops are all transparent, does not,
29
+ * while 1% does, and the layer's own opacity does not matter.
30
+ */
31
+ function isHitPaint(paint: SceneNode['fills'][number]): boolean {
32
+ if (!paint.visible || !(paint.opacity > 0)) return false
33
+ if (paint.type === 'SOLID') return paint.color.a > 0
34
+ if (
35
+ paint.type === 'GRADIENT_LINEAR' ||
36
+ paint.type === 'GRADIENT_RADIAL' ||
37
+ paint.type === 'GRADIENT_ANGULAR' ||
38
+ paint.type === 'GRADIENT_DIAMOND'
39
+ )
40
+ return (paint.gradientStops ?? []).some((stop) => stop.color.a > 0)
41
+ return true
42
+ }
43
+
44
+ function showsPaint(node: SceneNode): boolean {
45
+ return node.fills.some(isHitPaint) || node.strokes.some(isHitPaint)
46
+ }
47
+
48
+ /**
49
+ * Whether a container's empty area takes the click. Figma counts it only where a paint shows,
50
+ * except a main component's, which always counts, and an instance's when the click is a plain one.
51
+ */
52
+ function takesEmptyArea(graph: SceneGraph, node: SceneNode, instanceBodies: boolean): boolean {
53
+ if (node.type === 'COMPONENT' || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true
54
+ return instanceBodies && node.type === 'INSTANCE'
28
55
  }
29
56
 
30
57
  function isTopLevel(graph: SceneGraph, node: SceneNode): boolean {
@@ -188,32 +215,11 @@ function clippingMasks(graph: SceneGraph, childIds: readonly string[]): SceneNod
188
215
  return result
189
216
  }
190
217
 
191
- function hitTestOpaqueContainer(
192
- graph: SceneGraph,
193
- px: number,
194
- py: number,
195
- child: SceneNode,
196
- childId: string,
197
- deep: boolean,
198
- transformCache: Map<string, boolean>,
199
- pad: number,
200
- locked = false
201
- ): SceneNode | null {
202
- if (!containsPoint(px, py, child, graph, transformCache)) return null
203
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad, locked)
204
- if (childHit) return child
205
- if (hasVisibleFillOrStroke(child)) return child
206
- return null
207
- }
208
218
  /**
209
- * What a hit inside a container reports: the container itself when it is locked (a locked layer,
210
- * where one is hit at all, stands in for everything inside it) or the walk stops at containers.
219
+ * What a click inside a container reports. `opaque` is an instance or component whose body takes
220
+ * the click without looking through it; every other container looks through to its children first.
211
221
  */
212
- function standIn(container: SceneNode, hit: SceneNode, deep: boolean): SceneNode {
213
- return container.locked || !deep ? container : hit
214
- }
215
-
216
- function hitTestTransparentContainer(
222
+ function hitTestContainer(
217
223
  graph: SceneGraph,
218
224
  px: number,
219
225
  py: number,
@@ -222,26 +228,72 @@ function hitTestTransparentContainer(
222
228
  deep: boolean,
223
229
  transformCache: Map<string, boolean>,
224
230
  pad: number,
225
- locked = false
231
+ locked = false,
232
+ instanceBodies = false,
233
+ opaque = false
226
234
  ): SceneNode | null {
235
+ if (opaque) {
236
+ if (!containsPoint(px, py, child, graph, transformCache)) return null
237
+ const childHit = hitTestChildren(
238
+ graph,
239
+ px,
240
+ py,
241
+ childId,
242
+ deep,
243
+ transformCache,
244
+ pad,
245
+ locked,
246
+ instanceBodies
247
+ )
248
+ if (childHit) return child
249
+ if (takesEmptyArea(graph, child, instanceBodies)) return child
250
+ return null
251
+ }
227
252
  if (child.type === 'GROUP') {
228
253
  // A group fits its layers, so a padded click on one at its edge falls just outside it.
229
254
  if (!containsPoint(px, py, child, graph, transformCache, pad)) return null
230
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad, locked)
255
+ const childHit = hitTestChildren(
256
+ graph,
257
+ px,
258
+ py,
259
+ childId,
260
+ deep,
261
+ transformCache,
262
+ pad,
263
+ locked,
264
+ instanceBodies
265
+ )
231
266
  if (childHit) return standIn(child, childHit, deep)
232
267
  return containsPoint(px, py, child, graph, transformCache) ? child : null
233
268
  }
234
269
 
235
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad, locked)
270
+ const childHit = hitTestChildren(
271
+ graph,
272
+ px,
273
+ py,
274
+ childId,
275
+ deep,
276
+ transformCache,
277
+ pad,
278
+ locked,
279
+ instanceBodies
280
+ )
236
281
  if (childHit) return standIn(child, childHit, true)
237
282
 
238
283
  if (
239
284
  containsPoint(px, py, child, graph, transformCache) &&
240
- (hasVisibleFillOrStroke(child) || ownsItsEmptyArea(graph, child))
285
+ takesEmptyArea(graph, child, instanceBodies)
241
286
  )
242
287
  return child
243
288
  return null
244
289
  }
290
+ /**
291
+ * What a hit inside a container reports: the container itself when it is locked (a locked layer,
292
+ * where one is hit at all, stands in for everything inside it) or the walk stops at containers.
293
+ */
294
+ function standIn(container: SceneNode, hit: SceneNode, deep: boolean): SceneNode {
295
+ return container.locked || !deep ? container : hit
296
+ }
245
297
 
246
298
  /** Whether the masks that clip a layer leave the point outside every one of their outlines. */
247
299
  function isMaskedOut(
@@ -288,7 +340,8 @@ function hitTestChildren(
288
340
  deep = false,
289
341
  transformCache = new Map<string, boolean>(),
290
342
  pad = 0,
291
- locked = false
343
+ locked = false,
344
+ instanceBodies = false
292
345
  ): SceneNode | null {
293
346
  const parent = graph.nodes.get(parentId)
294
347
  if (!parent) return null
@@ -306,7 +359,7 @@ function hitTestChildren(
306
359
  if (!takesClick(graph, px, py, child, masks[i], locked, transformCache)) continue
307
360
  if (CONTAINER_TYPES.has(child.type)) {
308
361
  if (OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {
309
- const hit = hitTestOpaqueContainer(
362
+ const hit = hitTestContainer(
310
363
  graph,
311
364
  px,
312
365
  py,
@@ -315,13 +368,15 @@ function hitTestChildren(
315
368
  deep,
316
369
  transformCache,
317
370
  pad,
318
- locked
371
+ locked,
372
+ instanceBodies,
373
+ true
319
374
  )
320
375
  if (hit) return hit
321
376
  continue
322
377
  }
323
378
 
324
- const hit = hitTestTransparentContainer(
379
+ const hit = hitTestContainer(
325
380
  graph,
326
381
  px,
327
382
  py,
@@ -330,7 +385,8 @@ function hitTestChildren(
330
385
  deep,
331
386
  transformCache,
332
387
  pad,
333
- locked
388
+ locked,
389
+ instanceBodies
334
390
  )
335
391
  if (hit) return hit
336
392
  continue
@@ -353,7 +409,7 @@ export function hitTest(
353
409
  scopeId?: string
354
410
  ): SceneNode | null {
355
411
  const scope = scopeId ?? graph.rootId
356
- return hitTestChildren(graph, px, py, scope, false)
412
+ return hitTestChildren(graph, px, py, scope, false, new Map(), 0, false, true)
357
413
  }
358
414
 
359
415
  export function hitTestDeep(
@@ -449,7 +505,7 @@ export function hitTestSelectable(
449
505
  /** Whether locked layers are hit, as a right-click hits them; see `hitTestAtPoint`. */
450
506
  locked = false
451
507
  ): SceneNode | null {
452
- const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad, locked)
508
+ const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad, locked, true)
453
509
  if (!deepest) {
454
510
  const scope = graph.nodes.get(scopeId)
455
511
  return scope ? frameChildAt(graph, scope, px, py, locked) : null
@@ -492,7 +548,7 @@ export function hitTestOpenContainer(
492
548
  py: number,
493
549
  scopeId: string
494
550
  ): SceneNode | null {
495
- const deepest = hitTestChildren(graph, px, py, scopeId, true)
551
+ const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), 0, false, false)
496
552
  for (let node: SceneNode | undefined = deepest ?? undefined; node && node.id !== scopeId;) {
497
553
  if (!opensByItself(graph, node) || ownsItsEmptyArea(graph, node)) return null
498
554
  node = node.parentId ? graph.nodes.get(node.parentId) : undefined
@@ -523,7 +579,7 @@ function rectOverlap(a: Rect, b: Rect): Rect | null {
523
579
  */
524
580
  function selectsByOwnArea(graph: SceneGraph, node: SceneNode): boolean {
525
581
  if (node.type === 'GROUP' || ownsItsEmptyArea(graph, node)) return true
526
- return hasVisibleFillOrStroke(node) && !opensByItself(graph, node)
582
+ return showsPaint(node) && !opensByItself(graph, node)
527
583
  }
528
584
 
529
585
  /**
@@ -74,6 +74,27 @@ export function textLayerName(type: NodeType, text: string): string {
74
74
  return lines.join(' ') || defaultNodeName(type)
75
75
  }
76
76
 
77
+ /**
78
+ * The fields auto layout sets on the frame that holds it, with the value each holds when no frame
79
+ * lays anything out. A page holds layers; it is not one, so none of these apply to it and a page
80
+ * that took them would place its layers by a container nobody can see.
81
+ */
82
+ export const FRAME_LAYOUT_DEFAULTS = {
83
+ layoutMode: 'NONE',
84
+ layoutDirection: 'AUTO',
85
+ layoutWrap: 'NO_WRAP',
86
+ primaryAxisAlign: 'MIN',
87
+ counterAxisAlign: 'MIN',
88
+ primaryAxisSizing: 'FIXED',
89
+ counterAxisSizing: 'FIXED',
90
+ itemSpacing: 0,
91
+ counterAxisSpacing: 0,
92
+ paddingTop: 0,
93
+ paddingRight: 0,
94
+ paddingBottom: 0,
95
+ paddingLeft: 0
96
+ } as const satisfies Partial<SceneNode>
97
+
77
98
  export function createDefaultNode(
78
99
  generateId: () => string,
79
100
  type: NodeType,
@@ -127,19 +148,7 @@ export function createDefaultNode(
127
148
  leadingTrim: 'NONE',
128
149
  lineHeight: null,
129
150
  letterSpacing: NO_LETTER_SPACING,
130
- layoutMode: 'NONE',
131
- layoutDirection: 'AUTO',
132
- layoutWrap: 'NO_WRAP',
133
- primaryAxisAlign: 'MIN',
134
- counterAxisAlign: 'MIN',
135
- primaryAxisSizing: 'FIXED',
136
- counterAxisSizing: 'FIXED',
137
- itemSpacing: 0,
138
- counterAxisSpacing: 0,
139
- paddingTop: 0,
140
- paddingRight: 0,
141
- paddingBottom: 0,
142
- paddingLeft: 0,
151
+ ...FRAME_LAYOUT_DEFAULTS,
143
152
  blendMode: 'PASS_THROUGH',
144
153
  layoutPositioning: 'AUTO',
145
154
  layoutGrow: 0,
package/src/resize.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  } from './copy'
8
8
  import { enforcedAspectRatio } from './layout/aspect-ratio'
9
9
  import type { Rect } from './primitives'
10
+ import { followsPath } from './text/path'
10
11
  import type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'
11
12
  import { cloneVectorNetwork } from './vector-network'
12
13
 
@@ -332,7 +333,7 @@ export function scaledGeometryChanges(
332
333
  Object.assign(changes, scaledPathTextChanges(orig, sx, sy))
333
334
  // Glyphs scaled as a picture take their strokes along; any other stroke keeps its weight, as
334
335
  // Figma reports it, even where only a scaled outline can draw it.
335
- if (orig.strokes.length > 0 && isScaledPathText(orig)) {
336
+ if (orig.strokes.length > 0 && followsPath(orig)) {
336
337
  changes.strokes = scaleStrokes(orig.strokes, sx, sy)
337
338
  }
338
339
  return changes
@@ -369,25 +370,13 @@ export function shapeGeometryChanges(
369
370
 
370
371
  type PathTextFields = Pick<SceneNode, 'derivedTextGlyphs' | 'textPathData' | 'textPathBox'>
371
372
 
372
- // Path text scales with its path, including baked path text that kept only rotated glyphs;
373
- // other text reflows in the new box, so its glyphs are dropped.
374
- function isScaledPathText(orig: PathTextFields): boolean {
375
- const glyphs = orig.derivedTextGlyphs ?? []
376
- return (
377
- glyphs.length > 0 &&
378
- (!!orig.textPathData ||
379
- !!orig.textPathBox ||
380
- glyphs.some((glyph) => (glyph.rotation ?? 0) !== 0))
381
- )
382
- }
383
-
384
373
  /** The baked glyphs and layout box of path text, scaled with the layer; nothing for other text. */
385
374
  export function scaledPathTextChanges(
386
375
  orig: PathTextFields,
387
376
  sx: number,
388
377
  sy: number
389
378
  ): Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> {
390
- if (!isScaledPathText(orig)) return {}
379
+ if (!followsPath(orig)) return {}
391
380
  const changes: Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> = {
392
381
  derivedTextGlyphs: scaleDerivedGlyphs(orig.derivedTextGlyphs, sx, sy)
393
382
  }
@@ -1,7 +1,7 @@
1
- import { scaleGeometryPaths } from '../copy'
2
- import { scaledPathTextChanges } from '../resize'
1
+ import { copyDerivedGlyphs, scaleGeometryPaths } from '../copy'
3
2
  import { scaledTextLength } from '../text/lengths'
4
3
  import { TEXT_PARAGRAPH_SPACING_FIELDS } from '../text/paragraphs'
4
+ import { followsPath } from '../text/path'
5
5
  import {
6
6
  type Effect,
7
7
  type Fill,
@@ -14,6 +14,29 @@ import {
14
14
  } from '../types'
15
15
  import { cloneVectorNetwork } from '../vector-network'
16
16
 
17
+ function scaledPathText(node: SceneNode, scale: number): Partial<SceneNode> {
18
+ if (!node.textPathData && !followsPath(node)) {
19
+ return {}
20
+ }
21
+ const box = node.textPathBox
22
+ return {
23
+ derivedTextGlyphs:
24
+ copyDerivedGlyphs(node.derivedTextGlyphs)?.map((glyph) => ({
25
+ ...glyph,
26
+ x: glyph.x * scale,
27
+ y: glyph.y * scale,
28
+ fontSize: glyph.fontSize * scale,
29
+ ...(glyph.advance === undefined ? {} : { advance: glyph.advance * scale })
30
+ })) ?? null,
31
+ textPathBox: box && {
32
+ x: box.x * scale,
33
+ y: box.y * scale,
34
+ width: box.width * scale,
35
+ height: box.height * scale
36
+ }
37
+ }
38
+ }
39
+
17
40
  function scaledOptional(value: number | null, scale: number): number | null {
18
41
  return value == null ? null : value * scale
19
42
  }
@@ -141,6 +164,7 @@ export function scaleNodeChanges(
141
164
  paragraphSpacing: node.paragraphSpacing * scale,
142
165
  paragraphIndent: node.paragraphIndent * scale,
143
166
  textParagraphs: scaledParagraphStyles(node.textParagraphs, scale),
167
+ derivedTextHeight: scaledOptional(node.derivedTextHeight, scale),
144
168
  itemSpacing: node.itemSpacing * scale,
145
169
  counterAxisSpacing: node.counterAxisSpacing * scale,
146
170
  paddingTop: node.paddingTop * scale,
@@ -165,6 +189,6 @@ export function scaleNodeChanges(
165
189
  vectorNetwork: scaledVectorNetwork(node, scale),
166
190
  fillGeometry: scaleGeometryPaths(node.fillGeometry, scale, scale),
167
191
  strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale),
168
- ...scaledPathTextChanges(node, scale, scale)
192
+ ...scaledPathText(node, scale)
169
193
  }
170
194
  }
@@ -90,6 +90,14 @@ export function sharedStyleTypeForKind(kind: SharedStyleKind): SharedStyleType {
90
90
  return STYLE_TYPES[kind]
91
91
  }
92
92
 
93
+ /** The document's shared style layers, by the source ID layers link them by. */
94
+ export function sharedStyleLayers(graph: SceneGraph): Map<string, SceneNode> {
95
+ const styles = new Map<string, SceneNode>()
96
+ for (const node of graph.getAllNodes())
97
+ if (node.sharedStyleType !== null && node.source.id) styles.set(node.source.id, node)
98
+ return styles
99
+ }
100
+
93
101
  export function getSharedStyles(graph: SceneGraph, kind: SharedStyleKind): SharedStyle[] {
94
102
  const type = sharedStyleTypeForKind(kind)
95
103
  const styles: SharedStyle[] = []
@@ -0,0 +1,14 @@
1
+ import type { SceneNode } from '../types'
2
+
3
+ /** Whether the node's glyphs were baked along a path, including rotated-as-a-picture text. */
4
+ export function followsPath(
5
+ node: Pick<SceneNode, 'derivedTextGlyphs' | 'textPathData' | 'textPathBox'>
6
+ ): boolean {
7
+ const glyphs = node.derivedTextGlyphs ?? []
8
+ if (glyphs.length === 0) {
9
+ return false
10
+ }
11
+ return (
12
+ !!node.textPathData || !!node.textPathBox || glyphs.some((glyph) => (glyph.rotation ?? 0) !== 0)
13
+ )
14
+ }
@@ -39,13 +39,16 @@ export function textCacheInvalidationChanges(
39
39
  // A successful path-text edit supplies reflowed glyphs in `changes`. Every
40
40
  // other mutation path must drop stale baked glyphs and path identity rather
41
41
  // than pair new text/style with old visible outlines.
42
- if (node.derivedTextGlyphs && glyphsInvalidated && !changes.derivedTextGlyphs) {
42
+ if (glyphsInvalidated && !changes.derivedTextGlyphs) {
43
43
  // Path-text resize supplies transformed glyphs through the resize workflow. A raw box
44
44
  // preview keeps them until that workflow commits or an actual shaping edit occurs.
45
45
  const onlyPathBoxResize =
46
46
  !!node.textPathData && keys.every((key) => key === 'width' || key === 'height')
47
- if (!onlyPathBoxResize) {
47
+ const placesPath = keys.includes('textPathBox') && !!changes.textPathBox
48
+ if (node.derivedTextGlyphs && !onlyPathBoxResize) {
48
49
  invalidated.derivedTextGlyphs = null
50
+ }
51
+ if (node.textPathData && !onlyPathBoxResize && !placesPath) {
49
52
  invalidated.textPathData = null
50
53
  }
51
54
  }