@pairdraw/scene-graph 0.19.2 → 0.20.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 (166) hide show
  1. package/dist/components/index.d.ts +2 -2
  2. package/dist/components/index.js +2 -2
  3. package/dist/components/variants.d.ts +12 -1
  4. package/dist/components/variants.d.ts.map +1 -1
  5. package/dist/components/variants.js +30 -1
  6. package/dist/components/variants.js.map +1 -1
  7. package/dist/constants.d.ts +25 -1
  8. package/dist/constants.d.ts.map +1 -1
  9. package/dist/constants.js +94 -1
  10. package/dist/constants.js.map +1 -1
  11. package/dist/copy.d.ts.map +1 -1
  12. package/dist/copy.js +17 -1
  13. package/dist/copy.js.map +1 -1
  14. package/dist/css/index.d.ts +2 -2
  15. package/dist/css/index.js +2 -2
  16. package/dist/css/text.d.ts +17 -1
  17. package/dist/css/text.d.ts.map +1 -1
  18. package/dist/css/text.js +62 -1
  19. package/dist/css/text.js.map +1 -1
  20. package/dist/design-memory/index.d.ts +3 -0
  21. package/dist/design-memory/index.js +3 -0
  22. package/dist/design-memory/model.d.ts +33 -0
  23. package/dist/design-memory/model.d.ts.map +1 -0
  24. package/dist/design-memory/model.js +142 -0
  25. package/dist/design-memory/model.js.map +1 -0
  26. package/dist/design-memory/schema.d.ts +76 -0
  27. package/dist/design-memory/schema.d.ts.map +1 -0
  28. package/dist/design-memory/schema.js +72 -0
  29. package/dist/design-memory/schema.js.map +1 -0
  30. package/dist/effects.d.ts +7 -4
  31. package/dist/effects.d.ts.map +1 -1
  32. package/dist/effects.js +9 -4
  33. package/dist/effects.js.map +1 -1
  34. package/dist/empty-values.js +93 -0
  35. package/dist/empty-values.js.map +1 -0
  36. package/dist/fields/components.d.ts +9 -0
  37. package/dist/fields/components.d.ts.map +1 -0
  38. package/dist/fields/components.js +24 -0
  39. package/dist/fields/components.js.map +1 -0
  40. package/dist/fields/index.d.ts +3 -2
  41. package/dist/fields/index.js +3 -2
  42. package/dist/fields/layout.d.ts +3 -1
  43. package/dist/fields/layout.d.ts.map +1 -1
  44. package/dist/fields/layout.js +10 -1
  45. package/dist/fields/layout.js.map +1 -1
  46. package/dist/graph.d.ts +8 -1
  47. package/dist/graph.d.ts.map +1 -1
  48. package/dist/graph.js +28 -5
  49. package/dist/graph.js.map +1 -1
  50. package/dist/grid-values.d.ts +10 -0
  51. package/dist/grid-values.d.ts.map +1 -0
  52. package/dist/grid-values.js +53 -0
  53. package/dist/grid-values.js.map +1 -0
  54. package/dist/hit-test/drop.d.ts +20 -0
  55. package/dist/hit-test/drop.d.ts.map +1 -0
  56. package/dist/hit-test/drop.js +54 -0
  57. package/dist/hit-test/drop.js.map +1 -0
  58. package/dist/hit-test/geometry.js +86 -0
  59. package/dist/hit-test/geometry.js.map +1 -0
  60. package/dist/hit-test/masks.d.ts +14 -0
  61. package/dist/hit-test/masks.d.ts.map +1 -0
  62. package/dist/hit-test/masks.js +41 -0
  63. package/dist/hit-test/masks.js.map +1 -0
  64. package/dist/hit-test/paint.d.ts +6 -0
  65. package/dist/hit-test/paint.d.ts.map +1 -0
  66. package/dist/hit-test/paint.js +19 -0
  67. package/dist/hit-test/paint.js.map +1 -0
  68. package/dist/hit-test.d.ts +4 -15
  69. package/dist/hit-test.d.ts.map +1 -1
  70. package/dist/hit-test.js +5 -173
  71. package/dist/hit-test.js.map +1 -1
  72. package/dist/index.d.ts +2 -2
  73. package/dist/instances/fields.d.ts.map +1 -1
  74. package/dist/instances/fields.js +2 -0
  75. package/dist/instances/fields.js.map +1 -1
  76. package/dist/instances/index.d.ts +2 -1
  77. package/dist/instances/index.d.ts.map +1 -1
  78. package/dist/instances/index.js +1 -1
  79. package/dist/instances/index.js.map +1 -1
  80. package/dist/instances/source-walk.d.ts +12 -0
  81. package/dist/instances/source-walk.d.ts.map +1 -0
  82. package/dist/node-defaults.d.ts.map +1 -1
  83. package/dist/node-defaults.js +41 -36
  84. package/dist/node-defaults.js.map +1 -1
  85. package/dist/plugin-data/fields.d.ts +75 -0
  86. package/dist/plugin-data/fields.d.ts.map +1 -1
  87. package/dist/plugin-data/fields.js +18 -1
  88. package/dist/plugin-data/fields.js.map +1 -1
  89. package/dist/preview.d.ts.map +1 -1
  90. package/dist/preview.js +2 -0
  91. package/dist/preview.js.map +1 -1
  92. package/dist/scaling/node.d.ts.map +1 -1
  93. package/dist/scaling/node.js +5 -1
  94. package/dist/scaling/node.js.map +1 -1
  95. package/dist/token-sources/document.d.ts +26 -0
  96. package/dist/token-sources/document.d.ts.map +1 -0
  97. package/dist/token-sources/document.js +80 -0
  98. package/dist/token-sources/document.js.map +1 -0
  99. package/dist/token-sources/index.d.ts +3 -0
  100. package/dist/token-sources/index.js +3 -0
  101. package/dist/token-sources/schema.d.ts +43 -0
  102. package/dist/token-sources/schema.d.ts.map +1 -0
  103. package/dist/token-sources/schema.js +50 -0
  104. package/dist/token-sources/schema.js.map +1 -0
  105. package/dist/types.d.ts +102 -14
  106. package/dist/types.d.ts.map +1 -1
  107. package/dist/types.js.map +1 -1
  108. package/dist/variations/copy.d.ts +16 -0
  109. package/dist/variations/copy.d.ts.map +1 -0
  110. package/dist/variations/copy.js +78 -0
  111. package/dist/variations/copy.js.map +1 -0
  112. package/dist/variations/index.d.ts +6 -0
  113. package/dist/variations/index.js +6 -0
  114. package/dist/variations/match.d.ts +23 -0
  115. package/dist/variations/match.d.ts.map +1 -0
  116. package/dist/variations/match.js +80 -0
  117. package/dist/variations/match.js.map +1 -0
  118. package/dist/variations/model.d.ts +39 -0
  119. package/dist/variations/model.d.ts.map +1 -0
  120. package/dist/variations/model.js +90 -0
  121. package/dist/variations/model.js.map +1 -0
  122. package/dist/variations/pick.d.ts +43 -0
  123. package/dist/variations/pick.d.ts.map +1 -0
  124. package/dist/variations/pick.js +211 -0
  125. package/dist/variations/pick.js.map +1 -0
  126. package/dist/variations/schema.d.ts +27 -0
  127. package/dist/variations/schema.d.ts.map +1 -0
  128. package/dist/variations/schema.js +27 -0
  129. package/dist/variations/schema.js.map +1 -0
  130. package/package.json +21 -1
  131. package/src/components/variants.ts +39 -0
  132. package/src/constants.ts +75 -0
  133. package/src/copy.ts +20 -1
  134. package/src/css/index.ts +7 -1
  135. package/src/css/text.ts +62 -0
  136. package/src/design-memory/index.ts +2 -0
  137. package/src/design-memory/model.ts +143 -0
  138. package/src/design-memory/schema.ts +84 -0
  139. package/src/effects.ts +16 -7
  140. package/src/empty-values.ts +101 -0
  141. package/src/fields/components.ts +21 -0
  142. package/src/fields/index.ts +1 -0
  143. package/src/fields/layout.ts +10 -0
  144. package/src/graph.ts +37 -5
  145. package/src/grid-values.ts +47 -0
  146. package/src/hit-test/drop.ts +90 -0
  147. package/src/hit-test/geometry.ts +131 -0
  148. package/src/hit-test/masks.ts +57 -0
  149. package/src/hit-test/paint.ts +24 -0
  150. package/src/hit-test.ts +8 -277
  151. package/src/instances/fields.ts +2 -0
  152. package/src/instances/index.ts +1 -0
  153. package/src/node-defaults.ts +49 -39
  154. package/src/plugin-data/fields.ts +18 -1
  155. package/src/preview.ts +2 -0
  156. package/src/scaling/node.ts +7 -2
  157. package/src/token-sources/document.ts +104 -0
  158. package/src/token-sources/index.ts +2 -0
  159. package/src/token-sources/schema.ts +59 -0
  160. package/src/types.ts +115 -13
  161. package/src/variations/copy.ts +89 -0
  162. package/src/variations/index.ts +5 -0
  163. package/src/variations/match.ts +100 -0
  164. package/src/variations/model.ts +132 -0
  165. package/src/variations/pick.ts +293 -0
  166. package/src/variations/schema.ts +29 -0
package/src/css/text.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import valueParser from 'postcss-value-parser'
2
2
 
3
+ import { DEFAULT_FONT_FAMILY } from '../constants'
3
4
  import { percentLength, pixelLength } from '../text/lengths'
4
5
  import type { TextLength } from '../types'
5
6
  import { parseCSSNumber } from './values'
@@ -69,6 +70,67 @@ export function parseCSSFontFamilies(value: string | undefined): string[] {
69
70
  })
70
71
  }
71
72
 
73
+ /** CSS generic `font-family` keywords: names no font provider serves, drawn by a concrete face instead. */
74
+ export const GENERIC_FONT_FAMILIES: ReadonlySet<string> = new Set([
75
+ 'serif',
76
+ 'sans-serif',
77
+ 'monospace',
78
+ 'cursive',
79
+ 'fantasy',
80
+ 'system-ui',
81
+ 'ui-serif',
82
+ 'ui-sans-serif',
83
+ 'ui-monospace',
84
+ 'ui-rounded',
85
+ '-apple-system',
86
+ 'blinkmacsystemfont',
87
+ 'math',
88
+ 'emoji',
89
+ 'fangsong'
90
+ ])
91
+
92
+ /** Whether `family` is a CSS generic keyword rather than a face a provider or the host can load. */
93
+ export function isGenericFontFamily(family: string): boolean {
94
+ return GENERIC_FONT_FAMILIES.has(family.trim().toLowerCase())
95
+ }
96
+
97
+ /** The class a CSS generic keyword stands for, when a concrete face of it can draw the text. */
98
+ export type GenericFontClass = 'sans-serif' | 'serif' | 'monospace'
99
+
100
+ /** CSS generic keywords, by the concrete face class they stand for. */
101
+ export const GENERIC_FONT_FAMILY_CLASS: Readonly<Record<string, GenericFontClass>> = {
102
+ 'sans-serif': 'sans-serif',
103
+ 'ui-sans-serif': 'sans-serif',
104
+ 'system-ui': 'sans-serif',
105
+ '-apple-system': 'sans-serif',
106
+ blinkmacsystemfont: 'sans-serif',
107
+ serif: 'serif',
108
+ 'ui-serif': 'serif',
109
+ monospace: 'monospace',
110
+ 'ui-monospace': 'monospace'
111
+ }
112
+
113
+ /** Known system faces of each generic class, best first. The app bundles Inter for sans-serif. */
114
+ export const GENERIC_FONT_FAMILIES_BY_CLASS = {
115
+ 'sans-serif': [DEFAULT_FONT_FAMILY],
116
+ serif: ['Georgia', 'Times New Roman', 'Times', 'DejaVu Serif', 'Liberation Serif', 'Noto Serif'],
117
+ monospace: [
118
+ 'Menlo',
119
+ 'SF Mono',
120
+ 'Consolas',
121
+ 'Courier New',
122
+ 'DejaVu Sans Mono',
123
+ 'Liberation Mono',
124
+ 'Noto Sans Mono',
125
+ 'Ubuntu Mono'
126
+ ]
127
+ } as const satisfies Record<GenericFontClass, readonly string[]>
128
+
129
+ /** The concrete face class `family` stands for, or null when its name is no CSS generic keyword. */
130
+ export function genericFontFamilyClass(family: string): GenericFontClass | null {
131
+ return GENERIC_FONT_FAMILY_CLASS[family.trim().toLowerCase()] ?? null
132
+ }
133
+
72
134
  /** A CSS dimension's number and lowercase unit, or null. */
73
135
  function dimension(value: string): { number: number; unit: string } | null {
74
136
  const parsed = valueParser.unit(value)
@@ -0,0 +1,2 @@
1
+ export * from './model'
2
+ export * from './schema'
@@ -0,0 +1,143 @@
1
+ import { tryParseColor, colorToHex } from '../color'
2
+ import type { SceneGraph } from '../graph'
3
+ import { readPluginData, withPluginData } from '../plugin-data/field'
4
+ import { PAIRDRAW_PLUGIN_DATA } from '../plugin-data/fields'
5
+ import { randomHex } from '../random'
6
+ import type { PluginDataEntry } from '../types'
7
+ import {
8
+ DESIGN_MEMORY_LIMITS,
9
+ type DesignDecisionAuthor,
10
+ type DesignMemory,
11
+ type DesignMemoryGroup
12
+ } from './schema'
13
+
14
+ const { designMemory } = PAIRDRAW_PLUGIN_DATA
15
+
16
+ const GROUP_LIMITS = {
17
+ colors: DESIGN_MEMORY_LIMITS.colors,
18
+ fonts: DESIGN_MEMORY_LIMITS.fonts,
19
+ fontSizes: DESIGN_MEMORY_LIMITS.numbers,
20
+ spacing: DESIGN_MEMORY_LIMITS.numbers,
21
+ radius: DESIGN_MEMORY_LIMITS.numbers
22
+ } as const satisfies Record<DesignMemoryGroup, number>
23
+
24
+ /**
25
+ * A new memory: every group allows the document's own variables and styles. Off-system colors
26
+ * and fonts refuse an agent's edit; sizes, spacing and radii have real exceptions, so they warn.
27
+ */
28
+ export function createDesignMemory(): DesignMemory {
29
+ return {
30
+ version: 1,
31
+ colors: { fromSystem: true, values: [], enforce: 'refuse' },
32
+ fonts: { fromSystem: true, values: [], enforce: 'refuse' },
33
+ fontSizes: { fromSystem: true, values: [], enforce: 'warn' },
34
+ spacing: { fromSystem: true, values: [], enforce: 'warn' },
35
+ radius: { fromSystem: true, values: [], enforce: 'warn' },
36
+ decisions: [],
37
+ examples: []
38
+ }
39
+ }
40
+
41
+ /** The document's memory, or null when it has none or it is unreadable. */
42
+ export function readDesignMemory(graph: SceneGraph): DesignMemory | null {
43
+ return readPluginData(graph.getNode(graph.rootId)?.pluginData, designMemory) ?? null
44
+ }
45
+
46
+ const MEMORIES = new WeakMap<
47
+ SceneGraph,
48
+ { entries: readonly PluginDataEntry[] | undefined; memory: DesignMemory | null }
49
+ >()
50
+
51
+ /**
52
+ * The document's memory, read once per state of its document node: an edit replaces the node's
53
+ * plugin data, so a check on every agent call parses nothing new.
54
+ */
55
+ export function cachedDesignMemory(graph: SceneGraph): DesignMemory | null {
56
+ const entries = graph.getNode(graph.rootId)?.pluginData
57
+ const known = MEMORIES.get(graph)
58
+ if (known && known.entries === entries) return known.memory
59
+ const memory = readDesignMemory(graph)
60
+ MEMORIES.set(graph, { entries, memory })
61
+ return memory
62
+ }
63
+
64
+ /** Stores the memory on the document node as an undoable change; `null` removes it. */
65
+ export function writeDesignMemory(graph: SceneGraph, memory: DesignMemory | null): void {
66
+ const root = graph.getNode(graph.rootId)
67
+ if (!root) return
68
+ graph.updateNode(root.id, {
69
+ pluginData: withPluginData(root.pluginData, designMemory, memory ?? undefined)
70
+ })
71
+ }
72
+
73
+ /** A value as a group keeps it, or null when it is not one: colors become `#RRGGBB`. */
74
+ export function normalizeDesignValue(
75
+ group: DesignMemoryGroup,
76
+ value: string | number
77
+ ): string | number | null {
78
+ if (group === 'colors') {
79
+ const color = typeof value === 'string' ? tryParseColor(value.trim()) : null
80
+ return color ? colorToHex(color) : null
81
+ }
82
+ if (group === 'fonts') {
83
+ const family = typeof value === 'string' ? value.trim() : ''
84
+ return family && family.length <= DESIGN_MEMORY_LIMITS.fontLength ? family : null
85
+ }
86
+ const number = typeof value === 'number' ? value : Number(value)
87
+ if (!Number.isFinite(number)) return null
88
+ // A text has a size; spacing and radii may be zero.
89
+ return number > 0 || (number === 0 && group !== 'fontSizes') ? number : null
90
+ }
91
+
92
+ /**
93
+ * The memory with `value` allowed in `group`, once; a value the group cannot read, or one past
94
+ * its limit, leaves it as it was.
95
+ */
96
+ export function allowDesignValue(
97
+ memory: DesignMemory,
98
+ group: DesignMemoryGroup,
99
+ value: string | number
100
+ ): DesignMemory {
101
+ const normalized = normalizeDesignValue(group, value)
102
+ const values: readonly (string | number)[] = memory[group].values
103
+ if (normalized === null || values.includes(normalized) || values.length >= GROUP_LIMITS[group])
104
+ return memory
105
+ return { ...memory, [group]: { ...memory[group], values: [...values, normalized] } }
106
+ }
107
+
108
+ /** The memory with `value` no longer allowed in `group` by itself. */
109
+ export function disallowDesignValue(
110
+ memory: DesignMemory,
111
+ group: DesignMemoryGroup,
112
+ value: string | number
113
+ ): DesignMemory {
114
+ const values: readonly (string | number)[] = memory[group].values
115
+ return {
116
+ ...memory,
117
+ [group]: { ...memory[group], values: values.filter((item) => item !== value) }
118
+ }
119
+ }
120
+
121
+ /** The memory with a decision added last; blank text or a full list leaves it as it was. */
122
+ export function addDesignDecision(
123
+ memory: DesignMemory,
124
+ text: string,
125
+ author: DesignDecisionAuthor
126
+ ): DesignMemory {
127
+ const trimmed = text.trim().slice(0, DESIGN_MEMORY_LIMITS.decisionLength).trim()
128
+ if (!trimmed || memory.decisions.length >= DESIGN_MEMORY_LIMITS.decisions) return memory
129
+ return {
130
+ ...memory,
131
+ decisions: [...memory.decisions, { id: randomHex(8), text: trimmed, author }]
132
+ }
133
+ }
134
+
135
+ /** The memory with a layer pinned as an example, once; a full list leaves it as it was. */
136
+ export function pinDesignExample(memory: DesignMemory, nodeId: string): DesignMemory {
137
+ if (
138
+ memory.examples.some((example) => example.nodeId === nodeId) ||
139
+ memory.examples.length >= DESIGN_MEMORY_LIMITS.examples
140
+ )
141
+ return memory
142
+ return { ...memory, examples: [...memory.examples, { nodeId }] }
143
+ }
@@ -0,0 +1,84 @@
1
+ import * as v from 'valibot'
2
+
3
+ /** How many values, decisions and examples one document's memory keeps. */
4
+ export const DESIGN_MEMORY_LIMITS = {
5
+ colors: 128,
6
+ fonts: 16,
7
+ numbers: 32,
8
+ decisions: 40,
9
+ decisionLength: 400,
10
+ examples: 12,
11
+ fontLength: 100
12
+ } as const
13
+
14
+ /** The kinds of value a memory allows, each with its own list and enforcement. */
15
+ export const DESIGN_MEMORY_GROUPS = ['colors', 'fonts', 'fontSizes', 'spacing', 'radius'] as const
16
+ export type DesignMemoryGroup = (typeof DESIGN_MEMORY_GROUPS)[number]
17
+
18
+ /**
19
+ * What happens to an agent's edit that uses a value the memory does not allow: it is undone and
20
+ * the agent told the allowed values, it goes through with a warning, or nothing is checked.
21
+ * People's own edits are never refused; lint lists them.
22
+ */
23
+ export const DESIGN_MEMORY_ENFORCEMENTS = ['refuse', 'warn', 'off'] as const
24
+ export type DesignMemoryEnforcement = (typeof DESIGN_MEMORY_ENFORCEMENTS)[number]
25
+
26
+ export const DESIGN_DECISION_AUTHORS = ['person', 'agent'] as const
27
+ export type DesignDecisionAuthor = (typeof DESIGN_DECISION_AUTHORS)[number]
28
+
29
+ const enforcementSchema = v.picklist(DESIGN_MEMORY_ENFORCEMENTS)
30
+
31
+ /** A color as a memory keeps it: `#RRGGBB`, since alpha is never compared. */
32
+ const hexColorSchema = v.pipe(v.string(), v.regex(/^#[0-9A-F]{6}$/))
33
+ const fontFamilySchema = v.pipe(
34
+ v.string(),
35
+ v.trim(),
36
+ v.nonEmpty(),
37
+ v.maxLength(DESIGN_MEMORY_LIMITS.fontLength)
38
+ )
39
+ const fontSizeSchema = v.pipe(v.number(), v.finite(), v.gtValue(0))
40
+ const lengthSchema = v.pipe(v.number(), v.finite(), v.minValue(0))
41
+
42
+ /**
43
+ * One group: `fromSystem` allows what the document's variables and styles hold, and `values`
44
+ * adds values of the person's own.
45
+ */
46
+ function valueGroup<T>(value: v.GenericSchema<unknown, T>, max: number) {
47
+ return v.object({
48
+ fromSystem: v.boolean(),
49
+ values: v.pipe(v.array(value), v.maxLength(max)),
50
+ enforce: enforcementSchema
51
+ })
52
+ }
53
+
54
+ const decisionSchema = v.object({
55
+ id: v.pipe(v.string(), v.nonEmpty()),
56
+ text: v.pipe(
57
+ v.string(),
58
+ v.trim(),
59
+ v.nonEmpty(),
60
+ v.maxLength(DESIGN_MEMORY_LIMITS.decisionLength)
61
+ ),
62
+ author: v.picklist(DESIGN_DECISION_AUTHORS)
63
+ })
64
+
65
+ const exampleSchema = v.object({ nodeId: v.pipe(v.string(), v.nonEmpty()) })
66
+
67
+ /**
68
+ * A document's design rules for agents: the values its designs may use, decisions written down
69
+ * about them, and frames pinned as examples to follow.
70
+ */
71
+ export const designMemorySchema = v.object({
72
+ version: v.literal(1),
73
+ colors: valueGroup(hexColorSchema, DESIGN_MEMORY_LIMITS.colors),
74
+ fonts: valueGroup(fontFamilySchema, DESIGN_MEMORY_LIMITS.fonts),
75
+ fontSizes: valueGroup(fontSizeSchema, DESIGN_MEMORY_LIMITS.numbers),
76
+ spacing: valueGroup(lengthSchema, DESIGN_MEMORY_LIMITS.numbers),
77
+ radius: valueGroup(lengthSchema, DESIGN_MEMORY_LIMITS.numbers),
78
+ decisions: v.pipe(v.array(decisionSchema), v.maxLength(DESIGN_MEMORY_LIMITS.decisions)),
79
+ examples: v.pipe(v.array(exampleSchema), v.maxLength(DESIGN_MEMORY_LIMITS.examples))
80
+ })
81
+
82
+ export type DesignMemory = v.InferOutput<typeof designMemorySchema>
83
+ export type DesignDecision = DesignMemory['decisions'][number]
84
+ export type DesignExample = DesignMemory['examples'][number]
package/src/effects.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Vector } from './primitives'
2
- import type { Effect, ShaderEffect, ShadowEffect } from './types'
2
+ import type { Effect, ShadowEffect } from './types'
3
3
 
4
4
  const SHADOW_OFFSET: Vector = { x: 0, y: 4 }
5
5
  const BLUR_OFFSET: Vector = { x: 0, y: 0 }
@@ -9,6 +9,9 @@ type ShadowInput = Omit<ShadowEffect, 'offset'> & {
9
9
  offset?: Partial<Vector> | null
10
10
  }
11
11
 
12
+ /** An effect as a caller may pass it, before its geometry is made finite. */
13
+ type EffectInput = Effect | ShadowInput
14
+
12
15
  function fallbackOffset(type: ShadowEffect['type']): Vector {
13
16
  return type === 'DROP_SHADOW' || type === 'INNER_SHADOW' ? SHADOW_OFFSET : BLUR_OFFSET
14
17
  }
@@ -41,6 +44,11 @@ function isStoredShadow(effect: ShadowInput): effect is ShadowEffect {
41
44
  )
42
45
  }
43
46
 
47
+ /** An effect that carries geometry of its own, which has to be finite to render. */
48
+ function isOffsetEffect(effect: EffectInput): effect is ShadowInput {
49
+ return effect.type !== 'SHADER' && effect.type !== 'NOISE' && effect.type !== 'TEXTURE'
50
+ }
51
+
44
52
  function withFiniteOffset(effect: ShadowInput): Effect {
45
53
  const offset = finiteOffset(effect)
46
54
  if (!offset) {
@@ -50,19 +58,20 @@ function withFiniteOffset(effect: ShadowInput): Effect {
50
58
  return { ...effect, offset }
51
59
  }
52
60
 
53
- function isStoredEffect(effect: ShaderEffect | ShadowInput): effect is Effect {
54
- return effect.type === 'SHADER' || isStoredShadow(effect)
61
+ function isStoredEffect(effect: EffectInput): effect is Effect {
62
+ return !isOffsetEffect(effect) || isStoredShadow(effect)
55
63
  }
56
64
 
57
65
  /**
58
66
  * Shadows and blurs keep a finite offset. A drop or inner shadow missing one uses `{x: 0, y: 4}`,
59
- * the same default as `dropShadow()` and `set_effects`; a blur uses `{x: 0, y: 0}`. Shader effects
60
- * are left alone. An array that is already valid is returned as itself.
67
+ * the same default as `dropShadow()` and `set_effects`; a blur uses `{x: 0, y: 0}`. Shader, noise,
68
+ * and texture effects carry no offset and are left alone. An array that is already valid is
69
+ * returned as itself.
61
70
  */
62
- export function normalizeEffects(effects: (ShaderEffect | ShadowInput)[]): Effect[] {
71
+ export function normalizeEffects(effects: EffectInput[]): Effect[] {
63
72
  let next: Effect[] | null = null
64
73
  for (const [index, effect] of effects.entries()) {
65
- const normalized = effect.type === 'SHADER' ? effect : withFiniteOffset(effect)
74
+ const normalized = isOffsetEffect(effect) ? withFiniteOffset(effect) : effect
66
75
  if (normalized === effect) {
67
76
  if (next && isStoredEffect(effect)) next.push(effect)
68
77
  continue
@@ -0,0 +1,101 @@
1
+ import { isEmptyObject, isPlainObject } from 'es-toolkit'
2
+
3
+ import type { SceneNode, SourceMetadata } from './types'
4
+
5
+ /**
6
+ * The empty list and record every layer holds until a field gets a value of its own. All layers
7
+ * share them, so they are frozen: a field is replaced, never written into, and a write into one
8
+ * throws instead of reaching every layer of every document.
9
+ */
10
+ export const EMPTY_LIST: never[] = Object.freeze<never[]>([]) as never[]
11
+ export const EMPTY_RECORD: Record<string, never> = Object.freeze({})
12
+
13
+ /** The child list is the graph's to grow in place, so every layer keeps its own. */
14
+ const OWN_LIST_FIELDS: ReadonlySet<string> = new Set<keyof SceneNode>(['childIds'])
15
+
16
+ /** Fields keyed by name, such as bindings and property values, that start empty. */
17
+ const RECORD_FIELDS: ReadonlySet<string> = new Set<keyof SceneNode>([
18
+ 'componentPropertyAssignments',
19
+ 'componentPropertyValues',
20
+ 'boundVariables',
21
+ 'variableBindingScales',
22
+ 'variableAssignmentScales',
23
+ 'variableModes'
24
+ ])
25
+
26
+ const SOURCE_LIST_FIELDS = ['editedFields'] as const
27
+ const FIG_SOURCE_LIST_FIELDS = [
28
+ 'symbolOverrides',
29
+ 'componentPropAssignments',
30
+ 'derivedSymbolData'
31
+ ] as const
32
+
33
+ function sharedEmptyList(value: unknown): unknown {
34
+ return Array.isArray(value) && value.length === 0 ? EMPTY_LIST : value
35
+ }
36
+
37
+ function sharedEmptyRecord(value: unknown): unknown {
38
+ return isPlainObject(value) && isEmptyObject(value) ? EMPTY_RECORD : value
39
+ }
40
+
41
+ function sharedEmptyValue(field: string, value: unknown): unknown {
42
+ if (Array.isArray(value)) return OWN_LIST_FIELDS.has(field) ? value : sharedEmptyList(value)
43
+ return RECORD_FIELDS.has(field) ? sharedEmptyRecord(value) : value
44
+ }
45
+
46
+ /**
47
+ * `record` with the empty lists among `lists` and the empty record at `recordField` swapped for
48
+ * the shared ones: a copy when anything changes, so the caller's object is never written into.
49
+ * A field the record lacks stays absent.
50
+ */
51
+ function withSharedEmpties<T extends object>(
52
+ record: T,
53
+ lists: readonly string[],
54
+ recordField?: string
55
+ ): T {
56
+ const fields: [string, (value: unknown) => unknown][] = lists.map((field) => [
57
+ field,
58
+ sharedEmptyList
59
+ ])
60
+ if (recordField !== undefined) fields.push([recordField, sharedEmptyRecord])
61
+ let copy: T | null = null
62
+ for (const [field, shared] of fields) {
63
+ if (!Object.hasOwn(record, field)) continue
64
+ const value: unknown = Reflect.get(record, field)
65
+ const next = shared(value)
66
+ if (next === value) continue
67
+ copy ??= { ...record }
68
+ Reflect.set(copy, field, next)
69
+ }
70
+ return copy ?? record
71
+ }
72
+
73
+ /**
74
+ * Source metadata with its empty lists and raw fields swapped for the shared ones. The metadata
75
+ * object and its `fig` part stay the layer's own, since readers and edits write their scalars in
76
+ * place; metadata missing parts, as libraries and plugins may give, is kept as given.
77
+ */
78
+ function withSharedEmptySource(source: SourceMetadata): SourceMetadata {
79
+ const outer = withSharedEmpties(source, SOURCE_LIST_FIELDS)
80
+ const fig: unknown = Reflect.get(source, 'fig')
81
+ if (!isPlainObject(fig)) return outer
82
+ const sharedFig = withSharedEmpties(fig, FIG_SOURCE_LIST_FIELDS, 'rawNodeFields')
83
+ if (sharedFig === fig) return outer
84
+ return { ...outer, fig: { ...source.fig, ...sharedFig } }
85
+ }
86
+
87
+ /**
88
+ * Swap the `fields` of `node` that hold an empty list or record, its source metadata's included,
89
+ * for the shared ones. Writing known keys keeps the shape every layer shares.
90
+ */
91
+ export function shareEmptyNodeValues(node: SceneNode, fields: Iterable<string>): void {
92
+ for (const field of fields) {
93
+ const value: unknown = Reflect.get(node, field)
94
+ if (field === 'source') {
95
+ if (isPlainObject(value)) node.source = withSharedEmptySource(node.source)
96
+ continue
97
+ }
98
+ const shared = sharedEmptyValue(field, value)
99
+ if (shared !== value) Reflect.set(node, field, shared)
100
+ }
101
+ }
@@ -0,0 +1,21 @@
1
+ import type { SceneNode } from '../types'
2
+
3
+ /**
4
+ * What makes a layer a main component beyond its type: its key, its properties and variant
5
+ * specs, and how it is published to libraries.
6
+ */
7
+ export const MAIN_COMPONENT_FIELDS = [
8
+ 'componentKey',
9
+ 'componentPropertyDefinitions',
10
+ 'variantPropSpecs',
11
+ 'sourceLibraryKey',
12
+ 'publishId',
13
+ 'overrideKey',
14
+ 'sharedSymbolVersion',
15
+ 'publishedVersion',
16
+ 'librarySource',
17
+ 'isPublishable',
18
+ 'isSymbolPublishable',
19
+ 'symbolDescription',
20
+ 'symbolLinks'
21
+ ] as const satisfies readonly (keyof SceneNode)[]
@@ -1,4 +1,5 @@
1
1
  export * from './appearance'
2
+ export * from './components'
2
3
  export * from './geometry'
3
4
  export * from './layout'
4
5
  export * from './text'
@@ -24,6 +24,16 @@ export const AUTO_LAYOUT_FIELDS = [
24
24
  'gridRowGap'
25
25
  ] as const satisfies readonly (keyof SceneNode)[]
26
26
 
27
+ /** How a layer sits in its parent: its constraints and its place in an auto layout or grid. */
28
+ export const PARENT_LAYOUT_FIELDS = [
29
+ 'horizontalConstraint',
30
+ 'verticalConstraint',
31
+ 'layoutPositioning',
32
+ 'layoutGrow',
33
+ 'layoutAlignSelf',
34
+ 'gridPosition'
35
+ ] as const satisfies readonly (keyof SceneNode)[]
36
+
27
37
  /** Size limits a layer keeps however it is resized. */
28
38
  export const SIZE_CONSTRAINT_FIELDS = [
29
39
  'minWidth',
package/src/graph.ts CHANGED
@@ -14,16 +14,20 @@ import {
14
14
  } from './coordinate'
15
15
  import { cloneNodeProps, type NodeCloneMode } from './copy'
16
16
  import { normalizeEffects } from './effects'
17
+ import { shareEmptyNodeValues } from './empty-values'
17
18
  import { bindNodeEvents } from './events'
18
19
  import { TRANSFORM_FIELDS } from './fields/geometry'
19
20
  import { LAYOUT_AFFECTING_KEYS } from './fields/layout'
20
21
  import { withGeneratedFrameSize } from './generated'
22
+ import { gridLayoutChanges } from './grid-values'
21
23
  import * as HitTest from './hit-test'
22
24
  import { generateId } from './ids'
23
25
  import * as Instances from './instances'
24
26
  import { LayoutWrites } from './layout/writes'
25
27
  import Matrix from './matrix'
26
28
  import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'
29
+ import { withPluginData } from './plugin-data/field'
30
+ import { PAIRDRAW_PLUGIN_DATA } from './plugin-data/fields'
27
31
  import { updateNodePreview, type NodePreviewObserver } from './preview'
28
32
  import type { Color, Rect, Vector } from './primitives'
29
33
  /* eslint-disable max-lines -- SceneGraph is the facade over the domain modules */
@@ -495,7 +499,7 @@ export class SceneGraph {
495
499
  const node = createDefaultNode(
496
500
  () => this.generateEntityId(),
497
501
  type,
498
- pageLayoutOverrides(type, overrides)
502
+ pageLayoutOverrides(type, gridLayoutChanges(overrides))
499
503
  )
500
504
  Object.assign(node, strokeLineChanges(node, overrides))
501
505
  this.willChangeNode(parent)
@@ -514,7 +518,11 @@ export class SceneGraph {
514
518
  if (parentId === id) throw new Error(`Node "${id}" cannot be its own parent`)
515
519
  const parent = parentId === null ? undefined : this.nodes.get(parentId)
516
520
  if (parentId !== null && !parent) throw new Error(`Parent "${parentId}" does not exist`)
517
- const node = createDefaultNode(() => id, type, pageLayoutOverrides(type, overrides))
521
+ const node = createDefaultNode(
522
+ () => id,
523
+ type,
524
+ pageLayoutOverrides(type, gridLayoutChanges(overrides))
525
+ )
518
526
  // `overrides` may be another node's snapshot, ID included.
519
527
  node.id = id
520
528
  if (parent && !parent.childIds.includes(id)) {
@@ -668,7 +676,7 @@ export class SceneGraph {
668
676
 
669
677
  const node = this.nodes.get(id)
670
678
  if (!node) return
671
- const given = finiteGeometry(omitBy(changes, isUndefined))
679
+ const given = gridLayoutChanges(finiteGeometry(omitBy(changes, isUndefined)))
672
680
  assertPageLayout(node, given)
673
681
  this.applyNodeChanges(node, this.impliedChanges(node, given))
674
682
  }
@@ -727,6 +735,7 @@ export class SceneGraph {
727
735
  this.scopeDepths.sourceMetadata === 0 && !this.isApplyingDerivedLayout
728
736
  )
729
737
  Object.assign(node, changes)
738
+ shareEmptyNodeValues(node, Object.keys(changes))
730
739
  if (changes.fills) removeStaleBindings(node, 'fills', changes)
731
740
  if (changes.strokes) removeStaleBindings(node, 'strokes', changes)
732
741
  // A bound paint written keeps what it was given until its variable's color changes.
@@ -870,8 +879,23 @@ export class SceneGraph {
870
879
  }
871
880
  }
872
881
 
873
- for (const childId of Array.from(node.childIds)) {
874
- this.deleteNode(childId)
882
+ this.deleteSubtree(node)
883
+ }
884
+
885
+ /**
886
+ * Deletes `node` and its layers, children first. Their parent goes with them, so its child
887
+ * list is emptied once instead of being filtered for each child, which kept deleting a frame
888
+ * of thousands of layers quadratic. The list is emptied before the children go, so a listener
889
+ * of a child's deletion never finds it still listed.
890
+ */
891
+ private deleteSubtree(node: SceneNode): void {
892
+ const { id, childIds } = node
893
+ node.childIds = []
894
+ for (const childId of childIds) {
895
+ const child = this.nodes.get(childId)
896
+ if (!child) continue
897
+ this.willChangeNode(child)
898
+ this.deleteSubtree(child)
875
899
  }
876
900
 
877
901
  if (node.type === 'INSTANCE' && node.componentId) this.unindexInstance(node.componentId, id)
@@ -959,6 +983,14 @@ export class SceneGraph {
959
983
  if (props.source) props.source = { ...props.source, id: null, orderKey: null }
960
984
  // A copy is a new design nobody has reviewed: Figma's duplicate and clone() drop the status.
961
985
  props.status = null
986
+ // A stand-in mark names one layer's place in a version of a design; a copy is not that.
987
+ if (props.pluginData) {
988
+ props.pluginData = withPluginData(
989
+ props.pluginData,
990
+ PAIRDRAW_PLUGIN_DATA.variationStandIn,
991
+ undefined
992
+ )
993
+ }
962
994
  const clone = this.createNode(src.type, parentId, { ...props, ...overrides })
963
995
  Variables.copyAppliedBoundPaints(src, clone)
964
996
  copies.set(src.id, clone.id)
@@ -0,0 +1,47 @@
1
+ import type { GridTrack, SceneNode } from './types'
2
+
3
+ /**
4
+ * A gap or track a canvas can lay out. Figma holds gaps at zero or more and every track at a
5
+ * finite, usable size: a fixed or auto track that is negative or not a number becomes auto, and a
6
+ * fractional track needs a positive weight.
7
+ */
8
+ function safeTrack(track: GridTrack): GridTrack {
9
+ const value = track.value
10
+ const finite = Number.isFinite(value)
11
+ switch (track.sizing) {
12
+ case 'FR':
13
+ return finite && value > 0 ? track : { sizing: 'FR', value: 1 }
14
+ case 'FIXED':
15
+ return finite && value >= 0 ? track : { sizing: 'AUTO', value: 0 }
16
+ case 'AUTO':
17
+ return finite && value === 0 ? track : { sizing: 'AUTO', value: 0 }
18
+ default:
19
+ return { sizing: 'AUTO', value: 0 }
20
+ }
21
+ }
22
+
23
+ function safeGap(gap: number): number {
24
+ return Number.isFinite(gap) && gap >= 0 ? gap : 0
25
+ }
26
+
27
+ /**
28
+ * `changes` with grid gaps and tracks held to values the canvas can lay out. Only fields that
29
+ * needed holding move, so a write that already fits changes nothing.
30
+ */
31
+ export function gridLayoutChanges(changes: Partial<SceneNode>): Partial<SceneNode> {
32
+ const fixed: Partial<SceneNode> = {}
33
+ const { gridRowGap, gridColumnGap, gridTemplateRows, gridTemplateColumns } = changes
34
+ if (gridRowGap !== undefined && safeGap(gridRowGap) !== gridRowGap) fixed.gridRowGap = 0
35
+ if (gridColumnGap !== undefined && safeGap(gridColumnGap) !== gridColumnGap) {
36
+ fixed.gridColumnGap = 0
37
+ }
38
+ const rows = gridTemplateRows?.map(safeTrack)
39
+ if (rows?.some((track, index) => track !== gridTemplateRows?.[index])) {
40
+ fixed.gridTemplateRows = rows
41
+ }
42
+ const columns = gridTemplateColumns?.map(safeTrack)
43
+ if (columns?.some((track, index) => track !== gridTemplateColumns?.[index])) {
44
+ fixed.gridTemplateColumns = columns
45
+ }
46
+ return Object.keys(fixed).length === 0 ? changes : { ...changes, ...fixed }
47
+ }